From 3b49b59c328b8f2f69a4b1b90857a0b2269f7929 Mon Sep 17 00:00:00 2001 From: sconel Date: Wed, 28 Apr 2021 12:03:09 -0700 Subject: [PATCH 001/100] Added AddProductDependency calls to PrefabProcessorContext --- .../Spawnable/PrefabCatchmentProcessor.cpp | 2 - .../Spawnable/PrefabProcessorContext.cpp | 53 ++++++++++--------- .../Prefab/Spawnable/PrefabProcessorContext.h | 12 +++-- 3 files changed, 38 insertions(+), 29 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp index 5d8f1f35e3..6f2a5d517c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp @@ -84,8 +84,6 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils } SpawnableUtils::SortEntitiesByTransformHierarchy(*spawnable); context.GetProcessedObjects().push_back(AZStd::move(object)); - - context.RemovePrefab(prefabName); } else { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp index eb206349d0..0d5f06d837 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp @@ -10,6 +10,8 @@ * */ +#include + #include namespace AzToolsFramework::Prefab::PrefabConversionUtils @@ -24,37 +26,14 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils return result.second; } - bool PrefabProcessorContext::RemovePrefab(AZStd::string_view prefabName) - { - if (!m_isIterating) - { - return m_prefabs.erase(prefabName) > 0; - } - else - { - m_delayedDelete.emplace_back(prefabName); - } - return false; - } - void PrefabProcessorContext::ListPrefabs(const AZStd::function& callback) { m_isIterating = true; for (auto& it : m_prefabs) { - if (AZStd::find(m_delayedDelete.begin(), m_delayedDelete.end(), it.first) == m_delayedDelete.end()) - { - callback(it.first, it.second); - } + callback(it.first, it.second); } m_isIterating = false; - - // Clear out any prefabs that have been deleted. - for (AZStd::string& deleted : m_delayedDelete) - { - m_prefabs.erase(deleted); - } - m_delayedDelete.clear(); } void PrefabProcessorContext::ListPrefabs(const AZStd::function& callback) const @@ -70,6 +49,32 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils return !m_prefabs.empty(); } + void PrefabProcessorContext::RegisterProductDependency(AZStd::string& prefabName, AZStd::string& dependentPrefabName) + { + using ConversionUtils = PrefabConversionUtils::ProcessedObjectStore; + + uint32_t prefabSubId = ConversionUtils::BuildSubId(prefabName + + AzFramework::Spawnable::DotFileExtension); + + uint32_t dependentPrefabSubId = ConversionUtils::BuildSubId(dependentPrefabName + + AzFramework::Spawnable::DotFileExtension); + + RegisterProductDependency(prefabSubId, dependentPrefabSubId); + } + + void PrefabProcessorContext::RegisterProductDependency(uint32_t spawnableAssetSubId, uint32_t dependentSpawnableAssetSubId) + { + AZ::Data::AssetId spawnableAssetId(GetSourceUuid(), spawnableAssetSubId); + AZ::Data::AssetId dependentSpawnableAssetId(GetSourceUuid(), dependentSpawnableAssetSubId); + + RegisterProductDependency(spawnableAssetId, dependentSpawnableAssetId); + } + + void PrefabProcessorContext::RegisterProductDependency(AZ::Data::AssetId& assetId, AZ::Data::AssetId& dependentAssetId) + { + m_registeredProductDependencies[assetId].emplace(dependentAssetId); + } + PrefabProcessorContext::ProcessedObjectStoreContainer& PrefabProcessorContext::GetProcessedObjects() { return m_products; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h index 66368f335b..b98ce9c12b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h @@ -37,11 +37,14 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils virtual ~PrefabProcessorContext() = default; virtual bool AddPrefab(AZStd::string prefabName, PrefabDom prefab); - virtual bool RemovePrefab(AZStd::string_view prefabName); virtual void ListPrefabs(const AZStd::function& callback); virtual void ListPrefabs(const AZStd::function& callback) const; virtual bool HasPrefabs() const; + virtual void RegisterProductDependency(AZStd::string& prefabName, AZStd::string& dependentPrefabName); + virtual void RegisterProductDependency(uint32_t spawnableAssetSubId, uint32_t dependentSpawnableAssetSubId); + virtual void RegisterProductDependency(AZ::Data::AssetId& assetId, AZ::Data::AssetId& dependentAssetId); + virtual ProcessedObjectStoreContainer& GetProcessedObjects(); virtual const ProcessedObjectStoreContainer& GetProcessedObjects() const; @@ -54,10 +57,13 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils protected: using NamedPrefabContainer = AZStd::unordered_map; - + using ProductDependencyContainer = + AZStd::unordered_map>; + NamedPrefabContainer m_prefabs; ProcessedObjectStoreContainer m_products; - AZStd::vector m_delayedDelete; + ProductDependencyContainer m_registeredProductDependencies; + AZ::PlatformTagSet m_platformTags; AZ::Uuid m_sourceUuid; bool m_isIterating{ false }; From 845b74806103e27b7c927867778cbe93403b6f66 Mon Sep 17 00:00:00 2001 From: sconel Date: Thu, 29 Apr 2021 14:15:48 -0700 Subject: [PATCH 002/100] Updated PrefabBuilder to include product dependencies defined in AddProductDependency --- .../Spawnable/PrefabProcessorContext.cpp | 38 +++++++++++++++---- .../Prefab/Spawnable/PrefabProcessorContext.h | 14 ++++--- .../PrefabBuilder/PrefabBuilderComponent.cpp | 16 +++++++- .../PrefabBuilder/PrefabBuilderComponent.h | 1 + 4 files changed, 55 insertions(+), 14 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp index 0d5f06d837..a17222cc1a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp @@ -49,30 +49,42 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils return !m_prefabs.empty(); } - void PrefabProcessorContext::RegisterProductDependency(AZStd::string& prefabName, AZStd::string& dependentPrefabName) + bool PrefabProcessorContext::RegisterProductDependency(const AZStd::string& prefabName, const AZStd::string& dependentPrefabName) { using ConversionUtils = PrefabConversionUtils::ProcessedObjectStore; - uint32_t prefabSubId = ConversionUtils::BuildSubId(prefabName + + uint32_t spawnableSubId = ConversionUtils::BuildSubId(prefabName + AzFramework::Spawnable::DotFileExtension); - uint32_t dependentPrefabSubId = ConversionUtils::BuildSubId(dependentPrefabName + + uint32_t spawnablePrefabSubId = ConversionUtils::BuildSubId(dependentPrefabName + AzFramework::Spawnable::DotFileExtension); - RegisterProductDependency(prefabSubId, dependentPrefabSubId); + return RegisterProductDependency(spawnableSubId, spawnablePrefabSubId); } - void PrefabProcessorContext::RegisterProductDependency(uint32_t spawnableAssetSubId, uint32_t dependentSpawnableAssetSubId) + bool PrefabProcessorContext::RegisterProductDependency(const AZStd::string& prefabName, const AZ::Data::AssetId& dependentAssetId) + { + using ConversionUtils = PrefabConversionUtils::ProcessedObjectStore; + + uint32_t spawnableSubId = ConversionUtils::BuildSubId(prefabName + + AzFramework::Spawnable::DotFileExtension); + + AZ::Data::AssetId spawnableAssetId(GetSourceUuid(), spawnableSubId); + + return RegisterProductDependency(spawnableAssetId, dependentAssetId); + } + + bool PrefabProcessorContext::RegisterProductDependency(uint32_t spawnableAssetSubId, uint32_t dependentSpawnableAssetSubId) { AZ::Data::AssetId spawnableAssetId(GetSourceUuid(), spawnableAssetSubId); AZ::Data::AssetId dependentSpawnableAssetId(GetSourceUuid(), dependentSpawnableAssetSubId); - RegisterProductDependency(spawnableAssetId, dependentSpawnableAssetId); + return RegisterProductDependency(spawnableAssetId, dependentSpawnableAssetId); } - void PrefabProcessorContext::RegisterProductDependency(AZ::Data::AssetId& assetId, AZ::Data::AssetId& dependentAssetId) + bool PrefabProcessorContext::RegisterProductDependency(const AZ::Data::AssetId& assetId, const AZ::Data::AssetId& dependentAssetId) { - m_registeredProductDependencies[assetId].emplace(dependentAssetId); + return m_registeredProductDependencies[assetId].emplace(dependentAssetId).second; } PrefabProcessorContext::ProcessedObjectStoreContainer& PrefabProcessorContext::GetProcessedObjects() @@ -85,6 +97,16 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils return m_products; } + PrefabProcessorContext::ProductDependencyContainer& PrefabProcessorContext::GetRegisteredProductDependencies() + { + return m_registeredProductDependencies; + } + + const PrefabProcessorContext::ProductDependencyContainer& PrefabProcessorContext::GetRegisteredProductDependencies() const + { + return m_registeredProductDependencies; + } + void PrefabProcessorContext::SetPlatformTags(AZ::PlatformTagSet tags) { m_platformTags = AZStd::move(tags); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h index b98ce9c12b..141b0b04cb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h @@ -29,6 +29,8 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils { public: using ProcessedObjectStoreContainer = AZStd::vector; + using ProductDependencyContainer = + AZStd::unordered_map>; AZ_CLASS_ALLOCATOR(PrefabProcessorContext, AZ::SystemAllocator, 0); AZ_RTTI(PrefabProcessorContext, "{C7D77E3A-C544-486B-B774-7C82C38FE22F}"); @@ -41,13 +43,17 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils virtual void ListPrefabs(const AZStd::function& callback) const; virtual bool HasPrefabs() const; - virtual void RegisterProductDependency(AZStd::string& prefabName, AZStd::string& dependentPrefabName); - virtual void RegisterProductDependency(uint32_t spawnableAssetSubId, uint32_t dependentSpawnableAssetSubId); - virtual void RegisterProductDependency(AZ::Data::AssetId& assetId, AZ::Data::AssetId& dependentAssetId); + virtual bool RegisterProductDependency(const AZStd::string& prefabName, const AZStd::string& dependentPrefabName); + virtual bool RegisterProductDependency(const AZStd::string& prefabName, const AZ::Data::AssetId& dependentAssetId); + virtual bool RegisterProductDependency(uint32_t spawnableAssetSubId, uint32_t dependentSpawnableAssetSubId); + virtual bool RegisterProductDependency(const AZ::Data::AssetId& assetId, const AZ::Data::AssetId& dependentAssetId); virtual ProcessedObjectStoreContainer& GetProcessedObjects(); virtual const ProcessedObjectStoreContainer& GetProcessedObjects() const; + virtual ProductDependencyContainer& GetRegisteredProductDependencies(); + virtual const ProductDependencyContainer& GetRegisteredProductDependencies() const; + virtual void SetPlatformTags(AZ::PlatformTagSet tags); virtual const AZ::PlatformTagSet& GetPlatformTags() const; virtual const AZ::Uuid& GetSourceUuid() const; @@ -57,8 +63,6 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils protected: using NamedPrefabContainer = AZStd::unordered_map; - using ProductDependencyContainer = - AZStd::unordered_map>; NamedPrefabContainer m_prefabs; ProcessedObjectStoreContainer m_products; diff --git a/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp b/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp index 84a4cd5cc6..c640f21000 100644 --- a/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp +++ b/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp @@ -176,6 +176,7 @@ namespace AZ::Prefab bool PrefabBuilderComponent::StoreProducts( AZ::IO::PathView tempDirPath, const AzToolsFramework::Prefab::PrefabConversionUtils::PrefabProcessorContext::ProcessedObjectStoreContainer& store, + const AzToolsFramework::Prefab::PrefabConversionUtils::PrefabProcessorContext::ProductDependencyContainer& registeredDependencies, AZStd::vector& outputProducts) const { outputProducts.reserve(store.size()); @@ -214,6 +215,18 @@ namespace AZ::Prefab if (AssetBuilderSDK::OutputObject(&object.GetAsset(), object.GetAssetType(), productPath.String(), object.GetAssetType(), object.GetAsset().GetId().m_subId, product)) { + auto findRegisteredDependencies = registeredDependencies.find(object.GetAsset().GetId()); + if (findRegisteredDependencies != registeredDependencies.end()) + { + AZStd::transform(findRegisteredDependencies->second.begin(), findRegisteredDependencies->second.end(), + AZStd::back_inserter(product.m_dependencies), + [](const AZ::Data::AssetId& productId) -> AssetBuilderSDK::ProductDependency + { + return AssetBuilderSDK::ProductDependency(productId, + AZ::Data::ProductDependencyInfo::CreateFlags(AZ::Data::AssetLoadBehavior::NoLoad)); + }); + } + outputProducts.push_back(AZStd::move(product)); } @@ -250,7 +263,8 @@ namespace AZ::Prefab AZ_TracePrintf("Prefab Builder", "Finalizing products.\n"); if (!context.HasPrefabs()) { - if (StoreProducts(tempDirPath, context.GetProcessedObjects(), jobProducts)) + if (StoreProducts(tempDirPath, context.GetProcessedObjects(), + context.GetRegisteredProductDependencies(), jobProducts)) { return true; } diff --git a/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.h b/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.h index 7fbd0b4be0..6aaae10d5b 100644 --- a/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.h +++ b/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.h @@ -69,6 +69,7 @@ namespace AZ::Prefab bool StoreProducts( AZ::IO::PathView tempDirPath, const AzToolsFramework::Prefab::PrefabConversionUtils::PrefabProcessorContext::ProcessedObjectStoreContainer& store, + const AzToolsFramework::Prefab::PrefabConversionUtils::PrefabProcessorContext::ProductDependencyContainer& registeredDependencies, AZStd::vector& outputProducts) const; void ProcessJob(const AssetBuilderSDK::ProcessJobRequest& request, AssetBuilderSDK::ProcessJobResponse& response); From 15b1ae4b2d62418899d9bd543d54f5395717db57 Mon Sep 17 00:00:00 2001 From: sconel Date: Thu, 29 Apr 2021 14:24:09 -0700 Subject: [PATCH 003/100] Removed excess whitespace --- .../AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h index 141b0b04cb..a9488e2730 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h @@ -63,7 +63,7 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils protected: using NamedPrefabContainer = AZStd::unordered_map; - + NamedPrefabContainer m_prefabs; ProcessedObjectStoreContainer m_products; ProductDependencyContainer m_registeredProductDependencies; From a9de24ef7df0725fc06905f5fbfc781bbc9f9c7c Mon Sep 17 00:00:00 2001 From: sconel Date: Thu, 29 Apr 2021 18:09:38 -0700 Subject: [PATCH 004/100] Addressed PR feedback on function args and names --- .../Spawnable/PrefabProcessorContext.cpp | 36 +++++++++---------- .../Prefab/Spawnable/PrefabProcessorContext.h | 16 ++++----- .../PrefabBuilder/PrefabBuilderComponent.cpp | 4 +-- .../PrefabBuilder/PrefabBuilderComponent.h | 2 +- 4 files changed, 29 insertions(+), 29 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp index a17222cc1a..ca790ee35a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp @@ -49,42 +49,42 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils return !m_prefabs.empty(); } - bool PrefabProcessorContext::RegisterProductDependency(const AZStd::string& prefabName, const AZStd::string& dependentPrefabName) + bool PrefabProcessorContext::RegisterSpawnableProductAssetDependency(AZStd::string prefabName, AZStd::string dependentPrefabName) { using ConversionUtils = PrefabConversionUtils::ProcessedObjectStore; - uint32_t spawnableSubId = ConversionUtils::BuildSubId(prefabName + - AzFramework::Spawnable::DotFileExtension); + uint32_t spawnableSubId = ConversionUtils::BuildSubId(AZStd::move(prefabName + + AzFramework::Spawnable::DotFileExtension)); - uint32_t spawnablePrefabSubId = ConversionUtils::BuildSubId(dependentPrefabName + - AzFramework::Spawnable::DotFileExtension); + uint32_t spawnablePrefabSubId = ConversionUtils::BuildSubId(AZStd::move(dependentPrefabName + + AzFramework::Spawnable::DotFileExtension)); - return RegisterProductDependency(spawnableSubId, spawnablePrefabSubId); + return RegisterSpawnableProductAssetDependency(spawnableSubId, spawnablePrefabSubId); } - bool PrefabProcessorContext::RegisterProductDependency(const AZStd::string& prefabName, const AZ::Data::AssetId& dependentAssetId) + bool PrefabProcessorContext::RegisterSpawnableProductAssetDependency(AZStd::string prefabName, const AZ::Data::AssetId& dependentAssetId) { using ConversionUtils = PrefabConversionUtils::ProcessedObjectStore; - uint32_t spawnableSubId = ConversionUtils::BuildSubId(prefabName + - AzFramework::Spawnable::DotFileExtension); + uint32_t spawnableSubId = ConversionUtils::BuildSubId(AZStd::move(prefabName + + AzFramework::Spawnable::DotFileExtension)); AZ::Data::AssetId spawnableAssetId(GetSourceUuid(), spawnableSubId); - return RegisterProductDependency(spawnableAssetId, dependentAssetId); + return RegisterProductAssetDependency(spawnableAssetId, dependentAssetId); } - bool PrefabProcessorContext::RegisterProductDependency(uint32_t spawnableAssetSubId, uint32_t dependentSpawnableAssetSubId) + bool PrefabProcessorContext::RegisterSpawnableProductAssetDependency(uint32_t spawnableAssetSubId, uint32_t dependentSpawnableAssetSubId) { AZ::Data::AssetId spawnableAssetId(GetSourceUuid(), spawnableAssetSubId); AZ::Data::AssetId dependentSpawnableAssetId(GetSourceUuid(), dependentSpawnableAssetSubId); - return RegisterProductDependency(spawnableAssetId, dependentSpawnableAssetId); + return RegisterProductAssetDependency(spawnableAssetId, dependentSpawnableAssetId); } - bool PrefabProcessorContext::RegisterProductDependency(const AZ::Data::AssetId& assetId, const AZ::Data::AssetId& dependentAssetId) + bool PrefabProcessorContext::RegisterProductAssetDependency(const AZ::Data::AssetId& assetId, const AZ::Data::AssetId& dependentAssetId) { - return m_registeredProductDependencies[assetId].emplace(dependentAssetId).second; + return m_registeredProductAssetDependencies[assetId].emplace(dependentAssetId).second; } PrefabProcessorContext::ProcessedObjectStoreContainer& PrefabProcessorContext::GetProcessedObjects() @@ -97,14 +97,14 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils return m_products; } - PrefabProcessorContext::ProductDependencyContainer& PrefabProcessorContext::GetRegisteredProductDependencies() + PrefabProcessorContext::ProductAssetDependencyContainer& PrefabProcessorContext::GetRegisteredProductAssetDependencies() { - return m_registeredProductDependencies; + return m_registeredProductAssetDependencies; } - const PrefabProcessorContext::ProductDependencyContainer& PrefabProcessorContext::GetRegisteredProductDependencies() const + const PrefabProcessorContext::ProductAssetDependencyContainer& PrefabProcessorContext::GetRegisteredProductAssetDependencies() const { - return m_registeredProductDependencies; + return m_registeredProductAssetDependencies; } void PrefabProcessorContext::SetPlatformTags(AZ::PlatformTagSet tags) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h index a9488e2730..3dc8c99bf3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h @@ -29,7 +29,7 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils { public: using ProcessedObjectStoreContainer = AZStd::vector; - using ProductDependencyContainer = + using ProductAssetDependencyContainer = AZStd::unordered_map>; AZ_CLASS_ALLOCATOR(PrefabProcessorContext, AZ::SystemAllocator, 0); @@ -43,16 +43,16 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils virtual void ListPrefabs(const AZStd::function& callback) const; virtual bool HasPrefabs() const; - virtual bool RegisterProductDependency(const AZStd::string& prefabName, const AZStd::string& dependentPrefabName); - virtual bool RegisterProductDependency(const AZStd::string& prefabName, const AZ::Data::AssetId& dependentAssetId); - virtual bool RegisterProductDependency(uint32_t spawnableAssetSubId, uint32_t dependentSpawnableAssetSubId); - virtual bool RegisterProductDependency(const AZ::Data::AssetId& assetId, const AZ::Data::AssetId& dependentAssetId); + virtual bool RegisterSpawnableProductAssetDependency(AZStd::string prefabName, AZStd::string dependentPrefabName); + virtual bool RegisterSpawnableProductAssetDependency(AZStd::string prefabName, const AZ::Data::AssetId& dependentAssetId); + virtual bool RegisterSpawnableProductAssetDependency(uint32_t spawnableAssetSubId, uint32_t dependentSpawnableAssetSubId); + virtual bool RegisterProductAssetDependency(const AZ::Data::AssetId& assetId, const AZ::Data::AssetId& dependentAssetId); virtual ProcessedObjectStoreContainer& GetProcessedObjects(); virtual const ProcessedObjectStoreContainer& GetProcessedObjects() const; - virtual ProductDependencyContainer& GetRegisteredProductDependencies(); - virtual const ProductDependencyContainer& GetRegisteredProductDependencies() const; + virtual ProductAssetDependencyContainer& GetRegisteredProductAssetDependencies(); + virtual const ProductAssetDependencyContainer& GetRegisteredProductAssetDependencies() const; virtual void SetPlatformTags(AZ::PlatformTagSet tags); virtual const AZ::PlatformTagSet& GetPlatformTags() const; @@ -66,7 +66,7 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils NamedPrefabContainer m_prefabs; ProcessedObjectStoreContainer m_products; - ProductDependencyContainer m_registeredProductDependencies; + ProductAssetDependencyContainer m_registeredProductAssetDependencies; AZ::PlatformTagSet m_platformTags; AZ::Uuid m_sourceUuid; diff --git a/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp b/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp index c640f21000..2b97b8a63d 100644 --- a/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp +++ b/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp @@ -176,7 +176,7 @@ namespace AZ::Prefab bool PrefabBuilderComponent::StoreProducts( AZ::IO::PathView tempDirPath, const AzToolsFramework::Prefab::PrefabConversionUtils::PrefabProcessorContext::ProcessedObjectStoreContainer& store, - const AzToolsFramework::Prefab::PrefabConversionUtils::PrefabProcessorContext::ProductDependencyContainer& registeredDependencies, + const AzToolsFramework::Prefab::PrefabConversionUtils::PrefabProcessorContext::ProductAssetDependencyContainer& registeredDependencies, AZStd::vector& outputProducts) const { outputProducts.reserve(store.size()); @@ -264,7 +264,7 @@ namespace AZ::Prefab if (!context.HasPrefabs()) { if (StoreProducts(tempDirPath, context.GetProcessedObjects(), - context.GetRegisteredProductDependencies(), jobProducts)) + context.GetRegisteredProductAssetDependencies(), jobProducts)) { return true; } diff --git a/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.h b/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.h index 6aaae10d5b..f78e2cb889 100644 --- a/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.h +++ b/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.h @@ -69,7 +69,7 @@ namespace AZ::Prefab bool StoreProducts( AZ::IO::PathView tempDirPath, const AzToolsFramework::Prefab::PrefabConversionUtils::PrefabProcessorContext::ProcessedObjectStoreContainer& store, - const AzToolsFramework::Prefab::PrefabConversionUtils::PrefabProcessorContext::ProductDependencyContainer& registeredDependencies, + const AzToolsFramework::Prefab::PrefabConversionUtils::PrefabProcessorContext::ProductAssetDependencyContainer& registeredDependencies, AZStd::vector& outputProducts) const; void ProcessJob(const AssetBuilderSDK::ProcessJobRequest& request, AssetBuilderSDK::ProcessJobResponse& response); From 6e8b1d10004a01d9ff3db0023a48763f9f348191 Mon Sep 17 00:00:00 2001 From: sconel Date: Thu, 29 Apr 2021 18:28:07 -0700 Subject: [PATCH 005/100] Update on how we move string values in AddProductDependency --- .../Prefab/Spawnable/PrefabProcessorContext.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp index ca790ee35a..38f58503ed 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp @@ -53,11 +53,11 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils { using ConversionUtils = PrefabConversionUtils::ProcessedObjectStore; - uint32_t spawnableSubId = ConversionUtils::BuildSubId(AZStd::move(prefabName + - AzFramework::Spawnable::DotFileExtension)); + prefabName += AzFramework::Spawnable::DotFileExtension; + uint32_t spawnableSubId = ConversionUtils::BuildSubId(AZStd::move(prefabName)); - uint32_t spawnablePrefabSubId = ConversionUtils::BuildSubId(AZStd::move(dependentPrefabName + - AzFramework::Spawnable::DotFileExtension)); + dependentPrefabName += AzFramework::Spawnable::DotFileExtension; + uint32_t spawnablePrefabSubId = ConversionUtils::BuildSubId(AZStd::move(dependentPrefabName)); return RegisterSpawnableProductAssetDependency(spawnableSubId, spawnablePrefabSubId); } @@ -66,8 +66,8 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils { using ConversionUtils = PrefabConversionUtils::ProcessedObjectStore; - uint32_t spawnableSubId = ConversionUtils::BuildSubId(AZStd::move(prefabName + - AzFramework::Spawnable::DotFileExtension)); + prefabName += AzFramework::Spawnable::DotFileExtension; + uint32_t spawnableSubId = ConversionUtils::BuildSubId(AZStd::move(prefabName)); AZ::Data::AssetId spawnableAssetId(GetSourceUuid(), spawnableSubId); From 6dcc75ed78a6478796888c273f0ddb15fe8fb3ac Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Wed, 5 May 2021 14:43:41 -0500 Subject: [PATCH 006/100] AtomBridge contains all runtime deps now --- .../Platform/Mac/runtime_dependencies.cmake | 2 -- .../Code/Platform/Mac/tool_dependencies.cmake | 4 --- .../Windows/runtime_dependencies.cmake | 3 -- .../Platform/Windows/tool_dependencies.cmake | 7 ---- .../Gem/Code/runtime_dependencies.cmake | 10 ------ .../Gem/Code/tool_dependencies.cmake | 15 --------- .../AtomBridge/Code/CMakeLists.txt | 33 +++++++++++++++++++ .../additional_windows_runtime_deps.cmake | 14 ++++++++ .../additional_windows_tool_deps.cmake | 13 ++++++++ .../additional_windows_runtime_deps.cmake | 14 ++++++++ .../Linux/additional_windows_tool_deps.cmake | 15 +++++++++ .../Mac/additional_windows_runtime_deps.cmake | 14 ++++++++ .../Mac/additional_windows_tool_deps.cmake | 19 +++++++++++ .../additional_windows_runtime_deps.cmake | 16 +++++++++ .../additional_windows_tool_deps.cmake | 20 +++++++++++ .../iOS/additional_windows_runtime_deps.cmake | 14 ++++++++ .../iOS/additional_windows_tool_deps.cmake | 13 ++++++++ 17 files changed, 185 insertions(+), 41 deletions(-) create mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_windows_runtime_deps.cmake create mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_windows_tool_deps.cmake create mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_windows_runtime_deps.cmake create mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_windows_tool_deps.cmake create mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_windows_runtime_deps.cmake create mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_windows_tool_deps.cmake create mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_runtime_deps.cmake create mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake create mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_windows_runtime_deps.cmake create mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_windows_tool_deps.cmake diff --git a/AutomatedTesting/Gem/Code/Platform/Mac/runtime_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Mac/runtime_dependencies.cmake index f9d1e60dda..ffcaf7293a 100644 --- a/AutomatedTesting/Gem/Code/Platform/Mac/runtime_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/Platform/Mac/runtime_dependencies.cmake @@ -10,6 +10,4 @@ # set(GEM_DEPENDENCIES - Gem::Atom_RHI_Metal.Private - Gem::Atom_RHI_Null.Private ) \ No newline at end of file diff --git a/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake index ee7be9ac6d..ffcaf7293a 100644 --- a/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake @@ -10,8 +10,4 @@ # set(GEM_DEPENDENCIES - Gem::Atom_RHI_Null.Private - Gem::Atom_RHI_Null.Builders - Gem::Atom_RHI_Metal.Private - Gem::Atom_RHI_Metal.Builders ) \ No newline at end of file diff --git a/AutomatedTesting/Gem/Code/Platform/Windows/runtime_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Windows/runtime_dependencies.cmake index 0a1541bcfc..ffcaf7293a 100644 --- a/AutomatedTesting/Gem/Code/Platform/Windows/runtime_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/Platform/Windows/runtime_dependencies.cmake @@ -10,7 +10,4 @@ # set(GEM_DEPENDENCIES - Gem::Atom_RHI_Vulkan.Private - Gem::Atom_RHI_DX12.Private - Gem::Atom_RHI_Null.Private ) \ No newline at end of file diff --git a/AutomatedTesting/Gem/Code/Platform/Windows/tool_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Windows/tool_dependencies.cmake index ddd3bfa6a7..933dd7927b 100644 --- a/AutomatedTesting/Gem/Code/Platform/Windows/tool_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/Platform/Windows/tool_dependencies.cmake @@ -11,11 +11,4 @@ set(GEM_DEPENDENCIES Gem::QtForPython.Editor - Gem::Atom_RHI_Vulkan.Private - Gem::Atom_RHI_Vulkan.Builders - Gem::Atom_RHI_DX12.Private - Gem::Atom_RHI_DX12.Builders - Gem::Atom_RHI_Null.Private - Gem::Atom_RHI_Null.Builders - Gem::Atom_RHI_Metal.Builders ) \ No newline at end of file diff --git a/AutomatedTesting/Gem/Code/runtime_dependencies.cmake b/AutomatedTesting/Gem/Code/runtime_dependencies.cmake index c8e66740e4..da0a70b9cd 100644 --- a/AutomatedTesting/Gem/Code/runtime_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/runtime_dependencies.cmake @@ -42,16 +42,6 @@ set(GEM_DEPENDENCIES Gem::SurfaceData Gem::GradientSignal Gem::Vegetation - Gem::Atom_RHI.Private - Gem::Atom_RPI.Private - Gem::Atom_Feature_Common - Gem::Atom_Bootstrap - Gem::Atom_Component_DebugCamera - Gem::AtomImGuiTools - Gem::AtomLyIntegration_CommonFeatures - Gem::EMotionFX_Atom - Gem::ImguiAtom Gem::Atom_AtomBridge - Gem::AtomFont Gem::Blast ) diff --git a/AutomatedTesting/Gem/Code/tool_dependencies.cmake b/AutomatedTesting/Gem/Code/tool_dependencies.cmake index 8c5da63f42..f0e73e8a11 100644 --- a/AutomatedTesting/Gem/Code/tool_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/tool_dependencies.cmake @@ -50,23 +50,8 @@ set(GEM_DEPENDENCIES Gem::Vegetation.Editor Gem::GraphModel.Editor Gem::LandscapeCanvas.Editor - Gem::Atom_RHI.Private Gem::EMotionFX.Editor - Gem::Atom_RPI.Builders - Gem::Atom_RPI.Editor - Gem::Atom_Feature_Common.Builders - Gem::Atom_Feature_Common.Editor Gem::ImGui.Editor - Gem::Atom_Bootstrap - Gem::Atom_Asset_Shader.Builders - Gem::Atom_Component_DebugCamera - Gem::AtomImGuiTools - Gem::AtomLyIntegration_CommonFeatures.Editor - Gem::EMotionFX_Atom.Editor - Gem::ImageProcessingAtom.Editor Gem::Atom_AtomBridge.Editor - Gem::ImguiAtom - Gem::AtomFont - Gem::AtomToolsFramework.Editor Gem::Blast.Editor ) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt index b684e445b3..30861a6feb 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt +++ b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt @@ -9,6 +9,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Source/Platform/${PAL_PLATFORM_NAME}) + ly_add_target( NAME Atom_AtomBridge.Static STATIC NAMESPACE Gem @@ -41,12 +43,25 @@ ly_add_target( Source PUBLIC Include + PLATFORM_INCLUDE_FILES + ${pal_dir}/additional_${PAL_PLATFORM_NAME_LOWERCASE}_runtime_deps.cmake COMPILE_DEFINITIONS PRIVATE ENABLE_ATOM_DEBUG_DISPLAY=1 BUILD_DEPENDENCIES PRIVATE Gem::Atom_AtomBridge.Static + RUNTIME_DEPENDENCIES + Gem::Atom_RHI.Private + Gem::Atom_RPI.Private + Gem::Atom_Feature_Common + Gem::Atom_Bootstrap + Gem::Atom_Component_DebugCamera + Gem::AtomImGuiTools + Gem::AtomLyIntegration_CommonFeatures + Gem::EMotionFX_Atom + Gem::ImguiAtom + Gem::AtomFont ) if(PAL_TRAIT_BUILD_HOST_TOOLS) @@ -60,6 +75,8 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Source PUBLIC Include + PLATFORM_INCLUDE_FILES + ${pal_dir}/additional_${PAL_PLATFORM_NAME_LOWERCASE}_tool_deps.cmake COMPILE_DEFINITIONS PRIVATE EDITOR @@ -68,5 +85,21 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) AZ::AssetBuilderSDK Gem::Atom_Utils.Static Gem::Atom_AtomBridge.Static + RUNTIME_DEPENDENCIES + Gem::Atom_RHI.Private + Gem::Atom_RPI.Builders + Gem::Atom_RPI.Editor + Gem::Atom_Feature_Common.Builders + Gem::Atom_Feature_Common.Editor + Gem::Atom_Bootstrap + Gem::Atom_Asset_Shader.Builders + Gem::Atom_Component_DebugCamera + Gem::AtomImGuiTools + Gem::AtomLyIntegration_CommonFeatures.Editor + Gem::EMotionFX_Atom.Editor + Gem::ImageProcessingAtom.Editor + Gem::ImguiAtom + Gem::AtomFont + Gem::AtomToolsFramework.Editor ) endif() diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_windows_runtime_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_windows_runtime_deps.cmake new file mode 100644 index 0000000000..31c0cab74b --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_windows_runtime_deps.cmake @@ -0,0 +1,14 @@ +# +# 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(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Vulkan.Private +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_windows_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_windows_tool_deps.cmake new file mode 100644 index 0000000000..99eec9a733 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_windows_tool_deps.cmake @@ -0,0 +1,13 @@ +# +# 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(LY_RUNTIME_DEPENDENCIES +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_windows_runtime_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_windows_runtime_deps.cmake new file mode 100644 index 0000000000..31c0cab74b --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_windows_runtime_deps.cmake @@ -0,0 +1,14 @@ +# +# 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(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Vulkan.Private +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_windows_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_windows_tool_deps.cmake new file mode 100644 index 0000000000..8fb58f5e56 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_windows_tool_deps.cmake @@ -0,0 +1,15 @@ +# +# 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(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Vulkan.Private + Gem::Atom_RHI_Vulkan.Builders +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_windows_runtime_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_windows_runtime_deps.cmake new file mode 100644 index 0000000000..a0aa67c703 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_windows_runtime_deps.cmake @@ -0,0 +1,14 @@ +# +# 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(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Metal.Private +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_windows_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_windows_tool_deps.cmake new file mode 100644 index 0000000000..0b601adf8d --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_windows_tool_deps.cmake @@ -0,0 +1,19 @@ +# +# 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(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Metal.Private + Gem::Atom_RHI_Metal.Builders + Gem::Atom_RHI_Vulkan.Builders + Gem::Atom_RHI_DX12.Builders + Gem::Atom_RHI_Null.Private + Gem::Atom_RHI_Null.Builders +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_runtime_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_runtime_deps.cmake new file mode 100644 index 0000000000..dfd0319c05 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_runtime_deps.cmake @@ -0,0 +1,16 @@ +# +# 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(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Vulkan.Private + Gem::Atom_RHI_DX12.Private + Gem::Atom_RHI_Null.Private +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake new file mode 100644 index 0000000000..e30a9737ac --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake @@ -0,0 +1,20 @@ +# +# 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(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Vulkan.Private + Gem::Atom_RHI_Vulkan.Builders + Gem::Atom_RHI_DX12.Private + Gem::Atom_RHI_DX12.Builders + Gem::Atom_RHI_Null.Private + Gem::Atom_RHI_Null.Builders + Gem::Atom_RHI_Metal.Builders +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_windows_runtime_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_windows_runtime_deps.cmake new file mode 100644 index 0000000000..a0aa67c703 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_windows_runtime_deps.cmake @@ -0,0 +1,14 @@ +# +# 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(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Metal.Private +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_windows_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_windows_tool_deps.cmake new file mode 100644 index 0000000000..99eec9a733 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_windows_tool_deps.cmake @@ -0,0 +1,13 @@ +# +# 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(LY_RUNTIME_DEPENDENCIES +) From 6a3e89202016cc21b0b489fdea2c85fbdd6a28ba Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Wed, 5 May 2021 15:42:57 -0500 Subject: [PATCH 007/100] Fixed up pal file names --- ...s_runtime_deps.cmake => additional_android_runtime_deps.cmake} | 0 ...windows_tool_deps.cmake => additional_android_tool_deps.cmake} | 0 ...ows_runtime_deps.cmake => additional_linux_runtime_deps.cmake} | 0 ...l_windows_tool_deps.cmake => additional_linux_tool_deps.cmake} | 0 ...ndows_runtime_deps.cmake => additional_mac_runtime_deps.cmake} | 0 ...nal_windows_tool_deps.cmake => additional_mac_tool_deps.cmake} | 0 ...ndows_runtime_deps.cmake => additional_ios_runtime_deps.cmake} | 0 ...nal_windows_tool_deps.cmake => additional_ios_tool_deps.cmake} | 0 8 files changed, 0 insertions(+), 0 deletions(-) rename Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/{additional_windows_runtime_deps.cmake => additional_android_runtime_deps.cmake} (100%) rename Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/{additional_windows_tool_deps.cmake => additional_android_tool_deps.cmake} (100%) rename Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/{additional_windows_runtime_deps.cmake => additional_linux_runtime_deps.cmake} (100%) rename Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/{additional_windows_tool_deps.cmake => additional_linux_tool_deps.cmake} (100%) rename Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/{additional_windows_runtime_deps.cmake => additional_mac_runtime_deps.cmake} (100%) rename Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/{additional_windows_tool_deps.cmake => additional_mac_tool_deps.cmake} (100%) rename Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/{additional_windows_runtime_deps.cmake => additional_ios_runtime_deps.cmake} (100%) rename Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/{additional_windows_tool_deps.cmake => additional_ios_tool_deps.cmake} (100%) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_windows_runtime_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_android_runtime_deps.cmake similarity index 100% rename from Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_windows_runtime_deps.cmake rename to Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_android_runtime_deps.cmake diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_windows_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_android_tool_deps.cmake similarity index 100% rename from Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_windows_tool_deps.cmake rename to Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_android_tool_deps.cmake diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_windows_runtime_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_runtime_deps.cmake similarity index 100% rename from Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_windows_runtime_deps.cmake rename to Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_runtime_deps.cmake diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_windows_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake similarity index 100% rename from Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_windows_tool_deps.cmake rename to Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_windows_runtime_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_runtime_deps.cmake similarity index 100% rename from Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_windows_runtime_deps.cmake rename to Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_runtime_deps.cmake diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_windows_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake similarity index 100% rename from Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_windows_tool_deps.cmake rename to Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_windows_runtime_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_ios_runtime_deps.cmake similarity index 100% rename from Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_windows_runtime_deps.cmake rename to Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_ios_runtime_deps.cmake diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_windows_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_ios_tool_deps.cmake similarity index 100% rename from Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_windows_tool_deps.cmake rename to Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_ios_tool_deps.cmake From e80de63d55586dfc6ddf0bbd74b5fdfcc8c2c446 Mon Sep 17 00:00:00 2001 From: guthadam Date: Wed, 5 May 2021 23:31:17 -0500 Subject: [PATCH 008/100] ATOM-15486 Saving material editor user settings https://jira.agscollab.com/browse/ATOM-15486 --- .../Atom/Document/MaterialDocumentSettings.h | 34 ++++++++ .../Atom/Document/MaterialEditorSettingsBus.h | 49 ----------- .../MaterialViewportNotificationBus.h | 1 - .../Atom/Viewport/MaterialViewportSettings.h | 41 +++++++++ .../Window/MaterialEditorWindowSettings.h | 37 ++++++++ .../Document/MaterialDocumentSettings.cpp | 51 +++++++++++ .../MaterialDocumentSystemComponent.cpp | 59 +++++++------ .../MaterialDocumentSystemComponent.h | 8 +- .../Document/MaterialEditorSettings.cpp | 73 ---------------- .../Source/Document/MaterialEditorSettings.h | 45 ---------- .../Code/Source/MaterialEditorApplication.cpp | 5 +- .../Viewport/MaterialViewportComponent.cpp | 42 +++++---- .../Viewport/MaterialViewportComponent.h | 13 +-- .../Viewport/MaterialViewportRenderer.cpp | 18 ++-- .../Viewport/MaterialViewportSettings.cpp | 72 +++++++++++++++ .../Source/Window/MaterialEditorWindow.cpp | 25 ++++-- .../Window/MaterialEditorWindowComponent.cpp | 19 ++-- .../Window/MaterialEditorWindowSettings.cpp | 62 +++++++++++++ .../Window/ToolBar/MaterialEditorToolBar.cpp | 51 ++++++----- .../ViewportSettingsInspector.cpp | 87 ++++--------------- .../ViewportSettingsInspector.h | 20 +---- .../Code/materialeditor_files.cmake | 2 - .../Code/materialeditordocument_files.cmake | 6 +- .../Code/materialeditorviewport_files.cmake | 2 + .../Code/materialeditorwindow_files.cmake | 2 + 25 files changed, 463 insertions(+), 361 deletions(-) create mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSettings.h delete mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialEditorSettingsBus.h create mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Viewport/MaterialViewportSettings.h create mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowSettings.h create mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSettings.cpp delete mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialEditorSettings.cpp delete mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialEditorSettings.h create mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportSettings.cpp create mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSettings.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSettings.h new file mode 100644 index 0000000000..37d6a8c2d8 --- /dev/null +++ b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSettings.h @@ -0,0 +1,34 @@ +/* +* 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 +#endif + +namespace MaterialEditor +{ + struct MaterialDocumentSettings + : public AZ::UserSettings + { + AZ_RTTI(MaterialDocumentSettings, "{FA4F4BF3-BF39-4753-AAF7-AF383B868881}", AZ::UserSettings); + AZ_CLASS_ALLOCATOR(MaterialDocumentSettings, AZ::SystemAllocator, 0); + + static void Reflect(AZ::ReflectContext* context); + + bool m_showReloadDocumentPrompt = true; + }; +} // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialEditorSettingsBus.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialEditorSettingsBus.h deleted file mode 100644 index 3ddfdf44d4..0000000000 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialEditorSettingsBus.h +++ /dev/null @@ -1,49 +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 - -namespace MaterialEditor -{ - class MaterialEditorSettingsRequests - : public AZ::EBusTraits - { - public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - virtual AZ::Outcome GetProperty(AZStd::string_view name) const = 0; - virtual AZ::Outcome GetStringProperty(AZStd::string_view name) const = 0; - virtual AZ::Outcome GetBoolProperty(AZStd::string_view name) const = 0; - - virtual void SetProperty(AZStd::string_view name, const AZStd::any& value) = 0; - virtual void SetStringProperty(AZStd::string_view name, AZStd::string_view stringValue) = 0; - virtual void SetBoolProperty(AZStd::string_view name, bool boolValue) = 0; - }; - using MaterialEditorSettingsRequestBus = AZ::EBus; - - class MaterialEditorSettingsNotifications - : public AZ::EBusTraits - { - public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - virtual void OnPropertyChanged(AZStd::string_view name, const AZStd::any& value) = 0; - }; - using MaterialEditorSettingsNotificationBus = AZ::EBus; - -} // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Viewport/MaterialViewportNotificationBus.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Viewport/MaterialViewportNotificationBus.h index 0727547b13..af85dcc1db 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Viewport/MaterialViewportNotificationBus.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Viewport/MaterialViewportNotificationBus.h @@ -13,7 +13,6 @@ #include #include -#include #include #include diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Viewport/MaterialViewportSettings.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Viewport/MaterialViewportSettings.h new file mode 100644 index 0000000000..7af6b307df --- /dev/null +++ b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Viewport/MaterialViewportSettings.h @@ -0,0 +1,41 @@ +/* +* 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 MaterialEditor +{ + struct MaterialViewportSettings + : public AZ::UserSettings + { + AZ_RTTI(MaterialViewportSettings, "{16150503-A314-4765-82A3-172670C9EA90}", AZ::UserSettings); + AZ_CLASS_ALLOCATOR(MaterialViewportSettings, AZ::SystemAllocator, 0); + + static void Reflect(AZ::ReflectContext* context); + + bool m_enableGrid = true; + bool m_enableShadowCatcher = true; + bool m_enableAlternateSkybox = false; + float m_fieldOfView = 90.0f; + AZ::Render::DisplayMapperOperationType m_displayMapperOperationType = AZ::Render::DisplayMapperOperationType::Aces; + AZStd::string m_selectedModelPresetName = "Shader Ball"; + AZStd::string m_selectedLightingPresetName = "Neutral Urban"; + }; +} // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowSettings.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowSettings.h new file mode 100644 index 0000000000..bf572b070a --- /dev/null +++ b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowSettings.h @@ -0,0 +1,37 @@ +/* +* 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 +#endif + +namespace MaterialEditor +{ + struct MaterialEditorWindowSettings + : public AZ::UserSettings + { + AZ_RTTI(MaterialEditorWindowSettings, "{BB9DEB77-B7BE-4DF5-9FDD-6D9F3136C4EA}", AZ::UserSettings); + AZ_CLASS_ALLOCATOR(MaterialEditorWindowSettings, AZ::SystemAllocator, 0); + + static void Reflect(AZ::ReflectContext* context); + + bool m_enableGrid = true; + bool m_enableShadowCatcher = true; + bool m_enableAlternateSkybox = false; + float m_fieldOfView = 90.0f; + }; +} // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSettings.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSettings.cpp new file mode 100644 index 0000000000..a64b6584c1 --- /dev/null +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSettings.cpp @@ -0,0 +1,51 @@ +/* +* 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 + +namespace MaterialEditor +{ + void MaterialDocumentSettings::Reflect(AZ::ReflectContext* context) + { + if (auto serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ->Field("showReloadDocumentPrompt", &MaterialDocumentSettings::m_showReloadDocumentPrompt) + ; + + if (auto editContext = serializeContext->GetEditContext()) + { + editContext->Class( + "MaterialDocumentSettings", "") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialDocumentSettings::m_showReloadDocumentPrompt, "Show Reload Document Prompt", "") + ; + } + } + + if (auto behaviorContext = azrtti_cast(context)) + { + behaviorContext->Class("MaterialDocumentSettings") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + ->Attribute(AZ::Script::Attributes::Category, "Editor") + ->Attribute(AZ::Script::Attributes::Module, "render") + ->Constructor() + ->Constructor() + ->Property("showReloadDocumentPrompt", BehaviorValueProperty(&MaterialDocumentSettings::m_showReloadDocumentPrompt)) + ; + } + } +} // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.cpp index dbb1d18e49..d0a904d522 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -40,12 +41,13 @@ AZ_POP_DISABLE_WARNING namespace MaterialEditor { MaterialDocumentSystemComponent::MaterialDocumentSystemComponent() - : m_settings(aznew MaterialEditorSettings) { } void MaterialDocumentSystemComponent::Reflect(AZ::ReflectContext* context) { + MaterialDocumentSettings::Reflect(context); + if (AZ::SerializeContext* serialize = azrtti_cast(context)) { serialize->Class() @@ -132,6 +134,7 @@ namespace MaterialEditor void MaterialDocumentSystemComponent::Activate() { m_documentMap.clear(); + m_settings = AZ::UserSettings::CreateFind(AZ::Crc32("MaterialDocumentSettings"), AZ::UserSettings::CT_GLOBAL); MaterialDocumentSystemRequestBus::Handler::BusConnect(); MaterialDocumentNotificationBus::Handler::BusConnect(); } @@ -188,22 +191,25 @@ namespace MaterialEditor AZStd::string documentPath; MaterialDocumentRequestBus::EventResult(documentPath, documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); - if (QMessageBox::question(QApplication::activeWindow(), + if (m_settings->m_showReloadDocumentPrompt && + (QMessageBox::question(QApplication::activeWindow(), QString("Material document was externally modified"), QString("Would you like to reopen the document:\n%1?").arg(documentPath.c_str()), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) + QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)) { - AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + continue; + } - bool openResult = false; - MaterialDocumentRequestBus::EventResult(openResult, documentId, &MaterialDocumentRequestBus::Events::Open, documentPath); - if (!openResult) - { - QMessageBox::critical( - QApplication::activeWindow(), QString("Material document could not be opened"), - QString("Failed to open: \n%1\n\n%2").arg(documentPath.c_str()).arg(traceRecorder.GetDump().c_str())); - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::CloseDocument, documentId); - } + AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + + bool openResult = false; + MaterialDocumentRequestBus::EventResult(openResult, documentId, &MaterialDocumentRequestBus::Events::Open, documentPath); + if (!openResult) + { + QMessageBox::critical( + QApplication::activeWindow(), QString("Material document could not be opened"), + QString("Failed to open: \n%1\n\n%2").arg(documentPath.c_str()).arg(traceRecorder.GetDump().c_str())); + MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::CloseDocument, documentId); } } @@ -212,22 +218,25 @@ namespace MaterialEditor AZStd::string documentPath; MaterialDocumentRequestBus::EventResult(documentPath, documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); - if (QMessageBox::question(QApplication::activeWindow(), + if (m_settings->m_showReloadDocumentPrompt && + (QMessageBox::question(QApplication::activeWindow(), QString("Material document dependencies have changed"), QString("Would you like to update the document with these changes:\n%1?").arg(documentPath.c_str()), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) + QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)) { - AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + continue; + } - bool openResult = false; - MaterialDocumentRequestBus::EventResult(openResult, documentId, &MaterialDocumentRequestBus::Events::Rebuild); - if (!openResult) - { - QMessageBox::critical( - QApplication::activeWindow(), QString("Material document could not be opened"), - QString("Failed to open: \n%1\n\n%2").arg(documentPath.c_str()).arg(traceRecorder.GetDump().c_str())); - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::CloseDocument, documentId); - } + AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + + bool openResult = false; + MaterialDocumentRequestBus::EventResult(openResult, documentId, &MaterialDocumentRequestBus::Events::Rebuild); + if (!openResult) + { + QMessageBox::critical( + QApplication::activeWindow(), QString("Material document could not be opened"), + QString("Failed to open: \n%1\n\n%2").arg(documentPath.c_str()).arg(traceRecorder.GetDump().c_str())); + MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::CloseDocument, documentId); } } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.h index 4b0ee424a7..617937ad1a 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.h @@ -18,10 +18,10 @@ #include #include +#include #include #include #include -#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include @@ -43,7 +43,7 @@ namespace MaterialEditor MaterialDocumentSystemComponent(); ~MaterialDocumentSystemComponent() = default; MaterialDocumentSystemComponent(const MaterialDocumentSystemComponent&) = delete; - MaterialDocumentSystemComponent& operator =(const MaterialDocumentSystemComponent&) = delete; + MaterialDocumentSystemComponent& operator=(const MaterialDocumentSystemComponent&) = delete; static void Reflect(AZ::ReflectContext* context); @@ -87,10 +87,10 @@ namespace MaterialEditor AZ::Uuid OpenDocumentImpl(AZStd::string_view sourcePath, bool checkIfAlreadyOpen); + AZStd::intrusive_ptr m_settings; AZStd::unordered_map> m_documentMap; AZStd::unordered_set m_documentIdsToRebuild; AZStd::unordered_set m_documentIdsToReopen; - AZStd::unique_ptr m_settings; const size_t m_maxMessageBoxLineCount = 15; }; -} +} // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialEditorSettings.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialEditorSettings.cpp deleted file mode 100644 index fc0ed84bfa..0000000000 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialEditorSettings.cpp +++ /dev/null @@ -1,73 +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 - -namespace MaterialEditor -{ - MaterialEditorSettings::MaterialEditorSettings() - { - MaterialEditorSettingsRequestBus::Handler::BusConnect(); - } - - MaterialEditorSettings::~MaterialEditorSettings() - { - MaterialEditorSettingsRequestBus::Handler::BusDisconnect(); - } - - AZ::Outcome MaterialEditorSettings::GetProperty(AZStd::string_view name) const - { - const auto it = m_propertyMap.find(name); - if (it != m_propertyMap.end()) - { - return AZ::Success(it->second); - } - AZ_Warning("MaterialEditorSettings", false, "Failed to find property [%s].", name.data()); - return AZ::Failure(); - } - - AZ::Outcome MaterialEditorSettings::GetStringProperty(AZStd::string_view name) const - { - AZ::Outcome outcome = GetProperty(name); - if (!outcome || !outcome.GetValue().is()) - { - return AZ::Failure(); - } - return AZ::Success(AZStd::any_cast(outcome.GetValue())); - } - - AZ::Outcome MaterialEditorSettings::GetBoolProperty(AZStd::string_view name) const - { - AZ::Outcome outcome = GetProperty(name); - if (!outcome || !outcome.GetValue().is()) - { - return AZ::Failure(); - } - return AZ::Success(AZStd::any_cast(outcome.GetValue())); - } - - void MaterialEditorSettings::SetProperty(AZStd::string_view name, const AZStd::any& value) - { - m_propertyMap[name] = value; - MaterialEditorSettingsNotificationBus::Broadcast(&MaterialEditorSettingsNotifications::OnPropertyChanged, name, value); - } - - void MaterialEditorSettings::SetStringProperty(AZStd::string_view name, AZStd::string_view stringValue) - { - SetProperty(name, AZStd::any(AZStd::string(stringValue))); - } - - void MaterialEditorSettings::SetBoolProperty(AZStd::string_view name, bool boolValue) - { - SetProperty(name, AZStd::any(boolValue)); - } -} diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialEditorSettings.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialEditorSettings.h deleted file mode 100644 index f3a948ed80..0000000000 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialEditorSettings.h +++ /dev/null @@ -1,45 +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 - -namespace MaterialEditor -{ - class MaterialEditorSettings - : public MaterialEditorSettingsRequestBus::Handler - { - public: - AZ_RTTI(MaterialEditorSettings, "{9C6B6E20-A28E-45DD-85BE-68CA35E9305E}"); - AZ_CLASS_ALLOCATOR(MaterialEditorSettings, AZ::SystemAllocator, 0); - - MaterialEditorSettings(); - ~MaterialEditorSettings(); - - AZ::Outcome GetProperty(AZStd::string_view name) const override; - AZ::Outcome GetStringProperty(AZStd::string_view name) const override; - AZ::Outcome GetBoolProperty(AZStd::string_view name) const override; - - void SetProperty(AZStd::string_view name, const AZStd::any& value) override; - void SetStringProperty(AZStd::string_view name, AZStd::string_view stringValue) override; - void SetBoolProperty(AZStd::string_view name, bool boolValue) override; - - private: - AZStd::unordered_map m_propertyMap; - }; - -} // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp index 1f32c2a66b..55710efb66 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp @@ -284,7 +284,7 @@ namespace MaterialEditor AZ_Assert(context, "No serialize context"); char resolvedPath[AZ_MAX_PATH_LEN] = ""; - AZ::IO::FileIOBase::GetInstance()->ResolvePath("@user@/EditorUserSettings.xml", resolvedPath, AZ_ARRAY_SIZE(resolvedPath)); + AZ::IO::FileIOBase::GetInstance()->ResolvePath("@user@/MaterialEditorUserSettings.xml", resolvedPath, AZ_ARRAY_SIZE(resolvedPath)); m_localUserSettings.Save(resolvedPath, context); } } @@ -546,6 +546,9 @@ namespace MaterialEditor void MaterialEditorApplication::Stop() { + MaterialEditor::MaterialEditorWindowFactoryRequestBus::Broadcast( + &MaterialEditor::MaterialEditorWindowFactoryRequestBus::Handler::DestroyMaterialEditorWindow); + UnloadSettings(); AzFramework::Application::Stop(); } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportComponent.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportComponent.cpp index abaf50804f..948a23d509 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportComponent.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportComponent.cpp @@ -24,6 +24,7 @@ #include #include +#include #include #include @@ -70,6 +71,8 @@ namespace MaterialEditor void MaterialViewportComponent::Reflect(AZ::ReflectContext* context) { + MaterialViewportSettings::Reflect(context); + if (AZ::SerializeContext* serialize = azrtti_cast(context)) { serialize->Class() @@ -160,6 +163,9 @@ namespace MaterialEditor void MaterialViewportComponent::Activate() { + m_viewportSettings = + AZ::UserSettings::CreateFind(AZ::Crc32("MaterialViewportSettings"), AZ::UserSettings::CT_GLOBAL); + m_lightingPresetPreviewImageDefault = QImage(180, 90, QImage::Format::Format_RGBA8888); m_lightingPresetPreviewImageDefault.fill(Qt::GlobalColor::black); @@ -192,13 +198,14 @@ namespace MaterialEditor MaterialViewportNotificationBus::Broadcast(&MaterialViewportNotificationBus::Events::OnBeginReloadContent); - const AZStd::string prevLightingPresetSelectionName = m_lightingPresetSelection ? m_lightingPresetSelection->m_displayName : ""; - const AZStd::string prevModelPresetSelectionName = m_modelPresetSelection ? m_modelPresetSelection->m_displayName : ""; + const AZStd::string selectedLightingPresetNameOld = m_viewportSettings->m_selectedLightingPresetName; m_lightingPresetVector.clear(); m_lightingPresetLastSavePathMap.clear(); m_lightingPresetSelection.reset(); + const AZStd::string selectedModelPresetNameOld = m_viewportSettings->m_selectedModelPresetName; + m_modelPresetVector.clear(); m_modelPresetLastSavePathMap.clear(); m_modelPresetSelection.reset(); @@ -263,8 +270,8 @@ namespace MaterialEditor // If there was a prior selection, this will keep the same configuration selected. // Otherwise, these strings are empty and the operation will be ignored. - SelectLightingPresetByName(prevLightingPresetSelectionName); - SelectModelPresetByName(prevModelPresetSelectionName); + SelectLightingPresetByName(selectedLightingPresetNameOld); + SelectModelPresetByName(selectedModelPresetNameOld); MaterialViewportNotificationBus::Broadcast(&MaterialViewportNotificationBus::Events::OnEndReloadContent); @@ -327,6 +334,7 @@ namespace MaterialEditor if (preset) { m_lightingPresetSelection = preset; + m_viewportSettings->m_selectedLightingPresetName = preset->m_displayName; MaterialViewportNotificationBus::Broadcast(&MaterialViewportNotificationBus::Events::OnLightingPresetSelected, m_lightingPresetSelection); } } @@ -422,6 +430,7 @@ namespace MaterialEditor if (preset) { m_modelPresetSelection = preset; + m_viewportSettings->m_selectedModelPresetName = preset->m_displayName; MaterialViewportNotificationBus::Broadcast(&MaterialViewportNotificationBus::Events::OnModelPresetSelected, m_modelPresetSelection); } } @@ -463,71 +472,66 @@ namespace MaterialEditor void MaterialViewportComponent::SetShadowCatcherEnabled(bool enable) { - m_shadowCatcherEnabled = enable; + m_viewportSettings->m_enableShadowCatcher = enable; MaterialViewportNotificationBus::Broadcast(&MaterialViewportNotificationBus::Events::OnShadowCatcherEnabledChanged, enable); } bool MaterialViewportComponent::GetShadowCatcherEnabled() const { - return m_shadowCatcherEnabled; + return m_viewportSettings->m_enableShadowCatcher; } void MaterialViewportComponent::SetGridEnabled(bool enable) { - m_gridEnabled = enable; + m_viewportSettings->m_enableGrid = enable; MaterialViewportNotificationBus::Broadcast(&MaterialViewportNotificationBus::Events::OnGridEnabledChanged, enable); } bool MaterialViewportComponent::GetGridEnabled() const { - return m_gridEnabled; + return m_viewportSettings->m_enableGrid; } void MaterialViewportComponent::SetAlternateSkyboxEnabled(bool enable) { - m_alternateSkyboxEnabled = enable; + m_viewportSettings->m_enableAlternateSkybox = enable; MaterialViewportNotificationBus::Broadcast(&MaterialViewportNotificationBus::Events::OnAlternateSkyboxEnabledChanged, enable); } bool MaterialViewportComponent::GetAlternateSkyboxEnabled() const { - return m_alternateSkyboxEnabled; + return m_viewportSettings->m_enableAlternateSkybox; } void MaterialViewportComponent::SetFieldOfView(float fieldOfView) { - m_fieldOfView = fieldOfView; + m_viewportSettings->m_fieldOfView = fieldOfView; MaterialViewportNotificationBus::Broadcast(&MaterialViewportNotificationBus::Events::OnFieldOfViewChanged, fieldOfView); } float MaterialViewportComponent::GetFieldOfView() const { - return m_fieldOfView; + return m_viewportSettings->m_fieldOfView; } void MaterialViewportComponent::SetDisplayMapperOperationType(AZ::Render::DisplayMapperOperationType operationType) { - m_displayMapperOperationType = operationType; + m_viewportSettings->m_displayMapperOperationType = operationType; MaterialViewportNotificationBus::Broadcast(&MaterialViewportNotificationBus::Events::OnDisplayMapperOperationTypeChanged, operationType); } AZ::Render::DisplayMapperOperationType MaterialViewportComponent::GetDisplayMapperOperationType() const { - return m_displayMapperOperationType; + return m_viewportSettings->m_displayMapperOperationType; } void MaterialViewportComponent::OnCatalogLoaded([[maybe_unused]] const char* catalogFile) { AZ::TickBus::QueueFunction([this]() { ReloadContent(); - - // Automatically select preferred default presets if they exist - // We will later data drive this with editor settings - SelectLightingPresetByName("Neutral Urban"); - SelectModelPresetByName("Shader Ball"); }); } } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportComponent.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportComponent.h index 8332cb862c..ad35a86cf2 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportComponent.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportComponent.h @@ -13,13 +13,12 @@ #pragma once #include - -#include -#include - #include #include #include +#include +#include +#include namespace MaterialEditor { @@ -111,10 +110,6 @@ namespace MaterialEditor mutable AZStd::map m_lightingPresetLastSavePathMap; mutable AZStd::map m_modelPresetLastSavePathMap; - bool m_shadowCatcherEnabled = true; - bool m_gridEnabled = true; - bool m_alternateSkyboxEnabled = false; - float m_fieldOfView = 90.0f; - AZ::Render::DisplayMapperOperationType m_displayMapperOperationType = AZ::Render::DisplayMapperOperationType::Aces; + AZStd::intrusive_ptr m_viewportSettings; }; } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportRenderer.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportRenderer.cpp index 5939a40db6..f009cc1f9b 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportRenderer.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportRenderer.cpp @@ -41,6 +41,7 @@ #include #include #include +#include #include #include @@ -92,6 +93,7 @@ namespace MaterialEditor auto sceneSystem = AzFramework::SceneSystemInterface::Get(); AZ_Assert(sceneSystem, "MaterialViewportRenderer was unable to get the scene system during construction."); AZStd::shared_ptr mainScene = sceneSystem->GetScene(AzFramework::Scene::MainSceneName); + // This should never happen unless scene creation has changed. AZ_Assert(mainScene, "Main scenes missing during system component initialization"); mainScene->SetSubsystem(m_scene); @@ -138,7 +140,6 @@ namespace MaterialEditor m_renderPipeline->SetDefaultViewFromEntity(m_cameraEntity->GetId()); // Configure tone mapper - AzFramework::EntityContextRequestBus::EventResult(m_postProcessEntity, entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "postProcessEntity"); AZ_Assert(m_postProcessEntity != nullptr, "Failed to create post process entity."); @@ -154,13 +155,11 @@ namespace MaterialEditor m_displayMapperFeatureProcessor = m_scene->GetFeatureProcessor(); // Init Skybox - m_skyboxFeatureProcessor = m_scene->GetFeatureProcessor(); m_skyboxFeatureProcessor->Enable(true); m_skyboxFeatureProcessor->SetSkyboxMode(AZ::Render::SkyBoxMode::Cubemap); // Create IBL - AzFramework::EntityContextRequestBus::EventResult(m_iblEntity, entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "IblEntity"); AZ_Assert(m_iblEntity != nullptr, "Failed to create ibl entity."); @@ -176,8 +175,8 @@ namespace MaterialEditor m_modelEntity->CreateComponent(AZ::Render::MaterialComponentTypeId); m_modelEntity->CreateComponent(azrtti_typeid()); m_modelEntity->Activate(); - // Create shadow catcher + // Create shadow catcher AzFramework::EntityContextRequestBus::EventResult(m_shadowCatcherEntity, entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "ViewportShadowCatcher"); AZ_Assert(m_shadowCatcherEntity != nullptr, "Failed to create shadow catcher entity."); m_shadowCatcherEntity->CreateComponent(AZ::Render::MeshComponentTypeId); @@ -208,7 +207,6 @@ namespace MaterialEditor } // Create grid - AzFramework::EntityContextRequestBus::EventResult(m_gridEntity, entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "ViewportGrid"); AZ_Assert(m_gridEntity != nullptr, "Failed to create grid entity."); @@ -235,6 +233,16 @@ namespace MaterialEditor MaterialViewportRequestBus::BroadcastResult(modelPreset, &MaterialViewportRequestBus::Events::GetModelPresetSelection); OnModelPresetSelected(modelPreset); + // Apply user settinngs restored since last run + AZStd::intrusive_ptr viewportSettings = + AZ::UserSettings::CreateFind(AZ::Crc32("MaterialViewportSettings"), AZ::UserSettings::CT_GLOBAL); + + OnGridEnabledChanged(viewportSettings->m_enableGrid); + OnShadowCatcherEnabledChanged(viewportSettings->m_enableShadowCatcher); + OnAlternateSkyboxEnabledChanged(viewportSettings->m_enableAlternateSkybox); + OnFieldOfViewChanged(viewportSettings->m_fieldOfView); + OnDisplayMapperOperationTypeChanged(viewportSettings->m_displayMapperOperationType); + MaterialDocumentNotificationBus::Handler::BusConnect(); MaterialViewportNotificationBus::Handler::BusConnect(); AZ::TickBus::Handler::BusConnect(); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportSettings.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportSettings.cpp new file mode 100644 index 0000000000..fd64f3073d --- /dev/null +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportSettings.cpp @@ -0,0 +1,72 @@ +/* +* 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 + +namespace MaterialEditor +{ + void MaterialViewportSettings::Reflect(AZ::ReflectContext* context) + { + if (auto serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ->Field("enableGrid", &MaterialViewportSettings::m_enableGrid) + ->Field("enableShadowCatcher", &MaterialViewportSettings::m_enableShadowCatcher) + ->Field("enableAlternateSkybox", &MaterialViewportSettings::m_enableAlternateSkybox) + ->Field("fieldOfView", &MaterialViewportSettings::m_fieldOfView) + ->Field("displayMapperOperationType", &MaterialViewportSettings::m_displayMapperOperationType) + ->Field("selectedModelPresetName", &MaterialViewportSettings::m_selectedModelPresetName) + ->Field("selectedLightingPresetName", &MaterialViewportSettings::m_selectedLightingPresetName) + ; + + if (auto editContext = serializeContext->GetEditContext()) + { + editContext->Class( + "MaterialViewportSettings", "") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialViewportSettings::m_enableGrid, "Enable Grid", "") + ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialViewportSettings::m_enableShadowCatcher, "Enable Shadow Catcher", "") + ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialViewportSettings::m_enableAlternateSkybox, "Enable Alternate Skybox", "") + ->DataElement(AZ::Edit::UIHandlers::Slider, &MaterialViewportSettings::m_fieldOfView, "Field Of View", "") + ->Attribute(AZ::Edit::Attributes::Min, 60.0f) + ->Attribute(AZ::Edit::Attributes::Max, 120.0f) + ->DataElement(AZ::Edit::UIHandlers::ComboBox, &MaterialViewportSettings::m_displayMapperOperationType, "Display Mapper Type", "") + ->EnumAttribute(AZ::Render::DisplayMapperOperationType::Aces, "Aces") + ->EnumAttribute(AZ::Render::DisplayMapperOperationType::AcesLut, "AcesLut") + ->EnumAttribute(AZ::Render::DisplayMapperOperationType::Passthrough, "Passthrough") + ->EnumAttribute(AZ::Render::DisplayMapperOperationType::GammaSRGB, "GammaSRGB") + ->EnumAttribute(AZ::Render::DisplayMapperOperationType::Reinhard, "Reinhard") + ; + } + } + + if (auto behaviorContext = azrtti_cast(context)) + { + behaviorContext->Class("MaterialViewportSettings") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + ->Attribute(AZ::Script::Attributes::Category, "Editor") + ->Attribute(AZ::Script::Attributes::Module, "render") + ->Constructor() + ->Constructor() + ->Property("enableGrid", BehaviorValueProperty(&MaterialViewportSettings::m_enableGrid)) + ->Property("enableShadowCatcher", BehaviorValueProperty(&MaterialViewportSettings::m_enableShadowCatcher)) + ->Property("enableAlternateSkybox", BehaviorValueProperty(&MaterialViewportSettings::m_enableAlternateSkybox)) + ->Property("fieldOfView", BehaviorValueProperty(&MaterialViewportSettings::m_fieldOfView)) + ->Property("displayMapperOperationType", BehaviorValueProperty(&MaterialViewportSettings::m_displayMapperOperationType)) + ; + } + } +} // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index 6e47de189c..12e75f8fcf 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -10,14 +10,15 @@ * */ -#include #include -#include -#include -#include -#include +#include #include #include +#include +#include +#include +#include +#include #include @@ -121,10 +122,24 @@ namespace MaterialEditor MaterialEditorWindowRequestBus::Handler::BusConnect(); MaterialDocumentNotificationBus::Handler::BusConnect(); OnDocumentOpened(AZ::Uuid::CreateNull()); + + auto windowState = AZ::UserSettings::Find( + AZ::Crc32("MaterialEditorWindowState"), AZ::UserSettings::CT_GLOBAL); + if (windowState) + { + windowState->RestoreGeometry(this); + } } MaterialEditorWindow::~MaterialEditorWindow() { + auto windowState = AZ::UserSettings::CreateFind( + AZ::Crc32("MaterialEditorWindowState"), AZ::UserSettings::CT_GLOBAL); + if (windowState) + { + windowState->CaptureGeometry(this); + } + MaterialDocumentNotificationBus::Handler::BusDisconnect(); MaterialEditorWindowRequestBus::Handler::BusDisconnect(); } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp index 820cee30f9..3d796a21ad 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp @@ -10,25 +10,24 @@ * */ -#include -#include +#include +#include #include - -#include +#include +#include #include #include +#include #include - -#include -#include -#include -#include +#include +#include +#include namespace MaterialEditor { void MaterialEditorWindowComponent::Reflect(AZ::ReflectContext* context) { - GeneralViewportSettings::Reflect(context); + MaterialEditorWindowSettings::Reflect(context); if (AZ::SerializeContext* serialize = azrtti_cast(context)) { diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp new file mode 100644 index 0000000000..a9c928df10 --- /dev/null +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp @@ -0,0 +1,62 @@ +/* +* 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 + +namespace MaterialEditor +{ + void MaterialEditorWindowSettings::Reflect(AZ::ReflectContext* context) + { + if (auto serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ->Field("enableGrid", &MaterialEditorWindowSettings::m_enableGrid) + ->Field("enableShadowCatcher", &MaterialEditorWindowSettings::m_enableShadowCatcher) + ->Field("enableAlternateSkybox", &MaterialEditorWindowSettings::m_enableAlternateSkybox) + ->Field("fieldOfView", &MaterialEditorWindowSettings::m_fieldOfView) + ; + + if (auto editContext = serializeContext->GetEditContext()) + { + editContext->Class( + "MaterialEditorWindowSettings", "") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialEditorWindowSettings::m_enableGrid, "Enable Grid", "") + ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialEditorWindowSettings::m_enableShadowCatcher, "Enable Shadow Catcher", "") + ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialEditorWindowSettings::m_enableAlternateSkybox, "Enable Alternate Skybox", "") + ->DataElement(AZ::Edit::UIHandlers::Slider, &MaterialEditorWindowSettings::m_fieldOfView, "Field Of View", "") + ->Attribute(AZ::Edit::Attributes::Min, 60.0f) + ->Attribute(AZ::Edit::Attributes::Max, 120.0f) + ; + } + } + + if (auto behaviorContext = azrtti_cast(context)) + { + behaviorContext->Class("MaterialEditorWindowSettings") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + ->Attribute(AZ::Script::Attributes::Category, "Editor") + ->Attribute(AZ::Script::Attributes::Module, "render") + ->Constructor() + ->Constructor() + ->Property("enableGrid", BehaviorValueProperty(&MaterialEditorWindowSettings::m_enableGrid)) + ->Property("enableShadowCatcher", BehaviorValueProperty(&MaterialEditorWindowSettings::m_enableShadowCatcher)) + ->Property("enableAlternateSkybox", BehaviorValueProperty(&MaterialEditorWindowSettings::m_enableAlternateSkybox)) + ->Property("fieldOfView", BehaviorValueProperty(&MaterialEditorWindowSettings::m_fieldOfView)) + ; + } + } +} // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ToolBar/MaterialEditorToolBar.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ToolBar/MaterialEditorToolBar.cpp index 2af73bf436..8da7c903a2 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ToolBar/MaterialEditorToolBar.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ToolBar/MaterialEditorToolBar.cpp @@ -10,13 +10,13 @@ * */ -#include #include #include +#include #include -#include -#include -#include +#include +#include +#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include @@ -33,15 +33,16 @@ namespace MaterialEditor { AzQtComponents::ToolBar::addMainToolBarStyle(this); + AZStd::intrusive_ptr viewportSettings = + AZ::UserSettings::CreateFind(AZ::Crc32("MaterialViewportSettings"), AZ::UserSettings::CT_GLOBAL); + // Add toggle grid button m_toggleGrid = addAction(QIcon(":/Icons/grid.svg"), "Toggle Grid"); m_toggleGrid->setCheckable(true); connect(m_toggleGrid, &QAction::triggered, [this]() { MaterialViewportRequestBus::Broadcast(&MaterialViewportRequestBus::Events::SetGridEnabled, m_toggleGrid->isChecked()); - }); - bool enableGrid = false; - MaterialViewportRequestBus::BroadcastResult(enableGrid, &MaterialViewportRequestBus::Events::GetGridEnabled); - m_toggleGrid->setChecked(enableGrid); + }); + m_toggleGrid->setChecked(viewportSettings->m_enableGrid); // Add toggle shadow catcher button m_toggleShadowCatcher = addAction(QIcon(":/Icons/shadow.svg"), "Toggle Shadow Catcher"); @@ -49,34 +50,32 @@ namespace MaterialEditor connect(m_toggleShadowCatcher, &QAction::triggered, [this]() { MaterialViewportRequestBus::Broadcast( &MaterialViewportRequestBus::Events::SetShadowCatcherEnabled, m_toggleShadowCatcher->isChecked()); - }); - bool enableShadowCatcher = false; - MaterialViewportRequestBus::BroadcastResult(enableShadowCatcher, &MaterialViewportRequestBus::Events::GetShadowCatcherEnabled); - m_toggleShadowCatcher->setChecked(enableShadowCatcher); + }); + m_toggleShadowCatcher->setChecked(viewportSettings->m_enableShadowCatcher); // Add mapping selection button - + QToolButton* toneMappingButton = new QToolButton(this); QMenu* toneMappingMenu = new QMenu(toneMappingButton); - m_operationNames = - { - { AZ::Render::DisplayMapperOperationType::Reinhard, "Reinhard" }, - { AZ::Render::DisplayMapperOperationType::GammaSRGB, "GammaSRGB" }, - { AZ::Render::DisplayMapperOperationType::Passthrough, "Passthrough" }, - { AZ::Render::DisplayMapperOperationType::AcesLut, "AcesLut" }, - { AZ::Render::DisplayMapperOperationType::Aces, "Aces" } - }; + m_operationNames = { + {AZ::Render::DisplayMapperOperationType::Reinhard, "Reinhard"}, + {AZ::Render::DisplayMapperOperationType::GammaSRGB, "GammaSRGB"}, + {AZ::Render::DisplayMapperOperationType::Passthrough, "Passthrough"}, + {AZ::Render::DisplayMapperOperationType::AcesLut, "AcesLut"}, + {AZ::Render::DisplayMapperOperationType::Aces, "Aces"}}; + for (auto operationNamePair : m_operationNames) { m_operationActions[operationNamePair.first] = toneMappingMenu->addAction(operationNamePair.second, [operationNamePair]() { MaterialViewportRequestBus::Broadcast( - &MaterialViewportRequestBus::Events::SetDisplayMapperOperationType, - operationNamePair.first); - }); + &MaterialViewportRequestBus::Events::SetDisplayMapperOperationType, operationNamePair.first); + }); m_operationActions[operationNamePair.first]->setCheckable(true); + m_operationActions[operationNamePair.first]->setChecked( + operationNamePair.first == viewportSettings->m_displayMapperOperationType); } - m_operationActions[AZ::Render::DisplayMapperOperationType::Aces]->setChecked(true); + toneMappingButton->setMenu(toneMappingMenu); toneMappingButton->setText("Tone Mapping"); toneMappingButton->setIcon(QIcon(":/Icons/toneMapping.svg")); @@ -122,4 +121,4 @@ namespace MaterialEditor } // namespace MaterialEditor -#include +#include diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.cpp index fd50ace918..22e752dddd 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.cpp @@ -26,61 +26,12 @@ namespace MaterialEditor { - void GeneralViewportSettings::Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1) - ->Field("enableGrid", &GeneralViewportSettings::m_enableGrid) - ->Field("enableShadowCatcher", &GeneralViewportSettings::m_enableShadowCatcher) - ->Field("enableAlternateSkybox", &GeneralViewportSettings::m_enableAlternateSkybox) - ->Field("fieldOfView", &GeneralViewportSettings::m_fieldOfView) - ->Field("displayMapperOperationType", &GeneralViewportSettings::m_displayMapperOperationType) - ; - - if (auto editContext = serializeContext->GetEditContext()) - { - editContext->Class( - "GeneralViewportSettings", "") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &GeneralViewportSettings::m_enableGrid, "Enable Grid", "") - ->DataElement(AZ::Edit::UIHandlers::Default, &GeneralViewportSettings::m_enableShadowCatcher, "Enable Shadow Catcher", "") - ->DataElement(AZ::Edit::UIHandlers::Default, &GeneralViewportSettings::m_enableAlternateSkybox, "Enable Alternate Skybox", "") - ->DataElement(AZ::Edit::UIHandlers::Slider, &GeneralViewportSettings::m_fieldOfView, "Field Of View", "") - ->Attribute(AZ::Edit::Attributes::Min, 60.0f) - ->Attribute(AZ::Edit::Attributes::Max, 120.0f) - ->DataElement(AZ::Edit::UIHandlers::ComboBox, &GeneralViewportSettings::m_displayMapperOperationType, "Display Mapper Type", "") - ->EnumAttribute(AZ::Render::DisplayMapperOperationType::Aces, "Aces") - ->EnumAttribute(AZ::Render::DisplayMapperOperationType::AcesLut, "AcesLut") - ->EnumAttribute(AZ::Render::DisplayMapperOperationType::Passthrough, "Passthrough") - ->EnumAttribute(AZ::Render::DisplayMapperOperationType::GammaSRGB, "GammaSRGB") - ->EnumAttribute(AZ::Render::DisplayMapperOperationType::Reinhard, "Reinhard") - ; - } - } - - if (auto behaviorContext = azrtti_cast(context)) - { - behaviorContext->Class("GeneralViewportSettings") - ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) - ->Attribute(AZ::Script::Attributes::Category, "Editor") - ->Attribute(AZ::Script::Attributes::Module, "render") - ->Constructor() - ->Constructor() - ->Property("enableGrid", BehaviorValueProperty(&GeneralViewportSettings::m_enableGrid)) - ->Property("enableShadowCatcher", BehaviorValueProperty(&GeneralViewportSettings::m_enableShadowCatcher)) - ->Property("enableAlternateSkybox", BehaviorValueProperty(&GeneralViewportSettings::m_enableAlternateSkybox)) - ->Property("fieldOfView", BehaviorValueProperty(&GeneralViewportSettings::m_fieldOfView)) - ->Property("displayMapperOperationType", BehaviorValueProperty(&GeneralViewportSettings::m_displayMapperOperationType)) - ; - } - } - ViewportSettingsInspector::ViewportSettingsInspector(QWidget* parent) : AtomToolsFramework::InspectorWidget(parent) { + m_viewportSettings = + AZ::UserSettings::CreateFind(AZ::Crc32("MaterialViewportSettings"), AZ::UserSettings::CT_GLOBAL); + MaterialViewportNotificationBus::Handler::BusConnect(); } @@ -109,7 +60,7 @@ namespace MaterialEditor AddGroup( groupNameId, groupDisplayName, groupDescription, - new AtomToolsFramework::InspectorPropertyGroupWidget(&m_generalSettings, nullptr, m_generalSettings.TYPEINFO_Uuid(), this)); + new AtomToolsFramework::InspectorPropertyGroupWidget(m_viewportSettings.get(), nullptr, m_viewportSettings->TYPEINFO_Uuid(), this)); } void ViewportSettingsInspector::AddModelGroup() @@ -300,13 +251,13 @@ namespace MaterialEditor m_lightingPreset.reset(); MaterialViewportRequestBus::BroadcastResult(m_lightingPreset, &MaterialViewportRequestBus::Events::GetLightingPresetSelection); - MaterialViewportRequestBus::BroadcastResult(m_generalSettings.m_enableGrid, &MaterialViewportRequestBus::Events::GetGridEnabled); + MaterialViewportRequestBus::BroadcastResult(m_viewportSettings->m_enableGrid, &MaterialViewportRequestBus::Events::GetGridEnabled); MaterialViewportRequestBus::BroadcastResult( - m_generalSettings.m_enableShadowCatcher, &MaterialViewportRequestBus::Events::GetShadowCatcherEnabled); + m_viewportSettings->m_enableShadowCatcher, &MaterialViewportRequestBus::Events::GetShadowCatcherEnabled); MaterialViewportRequestBus::BroadcastResult( - m_generalSettings.m_enableAlternateSkybox, &MaterialViewportRequestBus::Events::GetAlternateSkyboxEnabled); - MaterialViewportRequestBus::BroadcastResult(m_generalSettings.m_fieldOfView, &MaterialViewportRequestBus::Handler::GetFieldOfView); - MaterialViewportRequestBus::BroadcastResult(m_generalSettings.m_displayMapperOperationType, &MaterialViewportRequestBus::Handler::GetDisplayMapperOperationType); + m_viewportSettings->m_enableAlternateSkybox, &MaterialViewportRequestBus::Events::GetAlternateSkyboxEnabled); + MaterialViewportRequestBus::BroadcastResult(m_viewportSettings->m_fieldOfView, &MaterialViewportRequestBus::Handler::GetFieldOfView); + MaterialViewportRequestBus::BroadcastResult(m_viewportSettings->m_displayMapperOperationType, &MaterialViewportRequestBus::Handler::GetDisplayMapperOperationType); AtomToolsFramework::InspectorRequestBus::Handler::BusDisconnect(); AtomToolsFramework::InspectorWidget::Reset(); @@ -330,31 +281,31 @@ namespace MaterialEditor void ViewportSettingsInspector::OnShadowCatcherEnabledChanged(bool enable) { - m_generalSettings.m_enableShadowCatcher = enable; + m_viewportSettings->m_enableShadowCatcher = enable; RefreshGroup("general"); } void ViewportSettingsInspector::OnGridEnabledChanged(bool enable) { - m_generalSettings.m_enableGrid = enable; + m_viewportSettings->m_enableGrid = enable; RefreshGroup("general"); } void ViewportSettingsInspector::OnAlternateSkyboxEnabledChanged(bool enable) { - m_generalSettings.m_enableAlternateSkybox = enable; + m_viewportSettings->m_enableAlternateSkybox = enable; RefreshGroup("general"); } void ViewportSettingsInspector::OnFieldOfViewChanged(float fieldOfView) { - m_generalSettings.m_fieldOfView = fieldOfView; + m_viewportSettings->m_fieldOfView = fieldOfView; RefreshGroup("general"); } void ViewportSettingsInspector::OnDisplayMapperOperationTypeChanged(AZ::Render::DisplayMapperOperationType operationType) { - m_generalSettings.m_displayMapperOperationType = operationType; + m_viewportSettings->m_displayMapperOperationType = operationType; RefreshGroup("general"); } @@ -379,13 +330,13 @@ namespace MaterialEditor { MaterialViewportNotificationBus::Broadcast(&MaterialViewportNotificationBus::Events::OnLightingPresetChanged, m_lightingPreset); MaterialViewportNotificationBus::Broadcast(&MaterialViewportNotificationBus::Events::OnModelPresetChanged, m_modelPreset); - MaterialViewportRequestBus::Broadcast(&MaterialViewportRequestBus::Events::SetGridEnabled, m_generalSettings.m_enableGrid); + MaterialViewportRequestBus::Broadcast(&MaterialViewportRequestBus::Events::SetGridEnabled, m_viewportSettings->m_enableGrid); MaterialViewportRequestBus::Broadcast( - &MaterialViewportRequestBus::Events::SetShadowCatcherEnabled, m_generalSettings.m_enableShadowCatcher); + &MaterialViewportRequestBus::Events::SetShadowCatcherEnabled, m_viewportSettings->m_enableShadowCatcher); MaterialViewportRequestBus::Broadcast( - &MaterialViewportRequestBus::Events::SetAlternateSkyboxEnabled, m_generalSettings.m_enableAlternateSkybox); - MaterialViewportRequestBus::Broadcast(&MaterialViewportRequestBus::Handler::SetFieldOfView, m_generalSettings.m_fieldOfView); - MaterialViewportRequestBus::Broadcast(&MaterialViewportRequestBus::Handler::SetDisplayMapperOperationType, m_generalSettings.m_displayMapperOperationType); + &MaterialViewportRequestBus::Events::SetAlternateSkyboxEnabled, m_viewportSettings->m_enableAlternateSkybox); + MaterialViewportRequestBus::Broadcast(&MaterialViewportRequestBus::Handler::SetFieldOfView, m_viewportSettings->m_fieldOfView); + MaterialViewportRequestBus::Broadcast(&MaterialViewportRequestBus::Handler::SetDisplayMapperOperationType, m_viewportSettings->m_displayMapperOperationType); } AZStd::string ViewportSettingsInspector::GetDefaultUniqueSaveFilePath(const AZStd::string& baseName) const diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.h index c61acb2e4c..fdfdec1458 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.h @@ -14,28 +14,16 @@ #if !defined(Q_MOC_RUN) #include -#include #include #include -#include +#include +#include #include +#include #endif namespace MaterialEditor { - struct GeneralViewportSettings - { - AZ_TYPE_INFO(GeneralViewportSettings, "{16150503-A314-4765-82A3-172670C9EA90}"); - AZ_CLASS_ALLOCATOR(GeneralViewportSettings, AZ::SystemAllocator, 0); - static void Reflect(AZ::ReflectContext* context); - - bool m_enableGrid = true; - bool m_enableShadowCatcher = true; - bool m_enableAlternateSkybox = false; - float m_fieldOfView = 90.0f; - AZ::Render::DisplayMapperOperationType m_displayMapperOperationType = AZ::Render::DisplayMapperOperationType::Aces; - }; - //! Provides controls for viewing and editing a material document settings. //! The settings can be divided into cards, with each one showing a subset of properties. class ViewportSettingsInspector @@ -90,7 +78,7 @@ namespace MaterialEditor AZStd::string GetDefaultUniqueSaveFilePath(const AZStd::string& baseName) const; - GeneralViewportSettings m_generalSettings; + AZStd::intrusive_ptr m_viewportSettings; AZ::Render::ModelPresetPtr m_modelPreset; AZ::Render::LightingPresetPtr m_lightingPreset; }; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/materialeditor_files.cmake b/Gems/Atom/Tools/MaterialEditor/Code/materialeditor_files.cmake index 845ff70cd1..e85a028005 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/materialeditor_files.cmake +++ b/Gems/Atom/Tools/MaterialEditor/Code/materialeditor_files.cmake @@ -13,7 +13,5 @@ set(FILES Source/main.cpp Source/MaterialEditorApplication.cpp Source/MaterialEditorApplication.h - Include/Atom/Document/MaterialDocumentModule.h - Source/Document/MaterialDocumentModule.cpp tool_dependencies.cmake ) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/materialeditordocument_files.cmake b/Gems/Atom/Tools/MaterialEditor/Code/materialeditordocument_files.cmake index ff781e6664..cf951cf0b2 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/materialeditordocument_files.cmake +++ b/Gems/Atom/Tools/MaterialEditor/Code/materialeditordocument_files.cmake @@ -14,11 +14,11 @@ set(FILES Include/Atom/Document/MaterialDocumentSystemRequestBus.h Include/Atom/Document/MaterialDocumentNotificationBus.h Include/Atom/Document/MaterialDocumentRequestBus.h - Include/Atom/Document/MaterialEditorSettingsBus.h + Include/Atom/Document/MaterialDocumentSettings.h + Source/Document/MaterialDocumentModule.cpp Source/Document/MaterialDocumentSystemComponent.cpp Source/Document/MaterialDocumentSystemComponent.h Source/Document/MaterialDocument.cpp Source/Document/MaterialDocument.h - Source/Document/MaterialEditorSettings.cpp - Source/Document/MaterialEditorSettings.h + Source/Document/MaterialDocumentSettings.cpp ) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/materialeditorviewport_files.cmake b/Gems/Atom/Tools/MaterialEditor/Code/materialeditorviewport_files.cmake index e8a65c8084..6ad602e167 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/materialeditorviewport_files.cmake +++ b/Gems/Atom/Tools/MaterialEditor/Code/materialeditorviewport_files.cmake @@ -12,6 +12,7 @@ set(FILES Include/Atom/Viewport/InputController/MaterialEditorViewportInputControllerBus.h Include/Atom/Viewport/MaterialViewportModule.h + Include/Atom/Viewport/MaterialViewportSettings.h Include/Atom/Viewport/MaterialViewportRequestBus.h Include/Atom/Viewport/MaterialViewportNotificationBus.h Include/Atom/Viewport/PerformanceMetrics.h @@ -35,6 +36,7 @@ set(FILES Source/Viewport/InputController/RotateModelBehavior.cpp Source/Viewport/InputController/RotateModelBehavior.h Source/Viewport/MaterialViewportModule.cpp + Source/Viewport/MaterialViewportSettings.cpp Source/Viewport/MaterialViewportComponent.cpp Source/Viewport/MaterialViewportComponent.h Source/Viewport/MaterialViewportWidget.cpp diff --git a/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake b/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake index 1547dbf48f..52022e6e87 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake +++ b/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake @@ -11,6 +11,7 @@ set(FILES Include/Atom/Window/MaterialEditorWindowModule.h + Include/Atom/Window/MaterialEditorWindowSettings.h Include/Atom/Window/MaterialEditorWindowNotificationBus.h Include/Atom/Window/MaterialEditorWindowRequestBus.h Include/Atom/Window/MaterialEditorWindowFactoryRequestBus.h @@ -19,6 +20,7 @@ set(FILES Source/Window/MaterialEditorWindow.h Source/Window/MaterialEditorWindow.cpp Source/Window/MaterialEditorWindowModule.cpp + Source/Window/MaterialEditorWindowSettings.cpp Source/Window/MaterialBrowserWidget.h Source/Window/MaterialBrowserWidget.cpp Source/Window/MaterialBrowserWidget.ui From 85a25d3bc1ad282bb294e261a73529d4fc18c0da Mon Sep 17 00:00:00 2001 From: jckand-amzn Date: Fri, 7 May 2021 14:32:14 -0500 Subject: [PATCH 009/100] - Removing Debugger refreshes from DistanceBetweenFilter tests --- ...tweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py | 7 ------- ...istanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py | 6 ------ 2 files changed, 13 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py index 1ccfc43585..85a16056f5 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py @@ -82,15 +82,11 @@ class TestDistanceBetweenFilterComponentOverrides(EditorTestHelper): editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, 'Configuration|Area System Settings|Sector Point Density', 16) - # Add a Vegetation Debugger component to allow area refreshes - hydra.add_level_component("Vegetation Debugger") - # 5) Add a Vegetation Distance Between Filter, toggle overrides on both the component and descriptor, # and verify initial instance counts are accurate spawner_entity.add_component("Vegetation Distance Between Filter") spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Override Enabled", True) - general.run_console('veg_debugClearAllAreas') self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 2), 5.0) and \ self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 2), 5.0) and \ @@ -98,7 +94,6 @@ class TestDistanceBetweenFilterComponentOverrides(EditorTestHelper): # 6) Change Radius Min to 1.0, refresh, and verify instance counts are accurate spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Radius Min", 1.0) - general.run_console('veg_debugClearAllAreas') self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) and \ self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 1), 5.0) and \ @@ -106,7 +101,6 @@ class TestDistanceBetweenFilterComponentOverrides(EditorTestHelper): # 7) Change Radius Min to 2.0, refresh, and verify instance counts are accurate spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Radius Min", 2.0) - general.run_console('veg_debugClearAllAreas') self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) and \ self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 0), 5.0) and \ @@ -114,7 +108,6 @@ class TestDistanceBetweenFilterComponentOverrides(EditorTestHelper): # 8) Change Radius Min to 16.0, refresh, and verify instance counts are accurate, only a single instance should plant spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Radius Min", 16.0) - general.run_console('veg_debugClearAllAreas') num_expected_instances = 1 final_check_success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) self.test_success = final_check_success and self.test_success diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py index 09c5fd63cf..59fbca205f 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py @@ -80,9 +80,6 @@ class TestDistanceBetweenFilterComponent(EditorTestHelper): editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, 'Configuration|Area System Settings|Sector Point Density', 16) - # Add a Vegetation Debugger component to allow area refreshes - hydra.add_level_component("Vegetation Debugger") - # 5) Add a Vegetation Distance Between Filter and verify initial instance counts are accurate spawner_entity.add_component("Vegetation Distance Between Filter") self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ @@ -92,7 +89,6 @@ class TestDistanceBetweenFilterComponent(EditorTestHelper): # 6) Change Radius Min to 1.0, refresh, and verify instance counts are accurate spawner_entity.get_set_test(3, "Configuration|Radius Min", 1.0) - general.run_console('veg_debugClearAllAreas') self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) and \ self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 1), 5.0) and \ @@ -100,7 +96,6 @@ class TestDistanceBetweenFilterComponent(EditorTestHelper): # 7) Change Radius Min to 2.0, refresh, and verify instance counts are accurate spawner_entity.get_set_test(3, "Configuration|Radius Min", 2.0) - general.run_console('veg_debugClearAllAreas') self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) and \ self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 0), 5.0) and \ @@ -108,7 +103,6 @@ class TestDistanceBetweenFilterComponent(EditorTestHelper): # 8) Change Radius Min to 16.0, refresh, and verify instance counts are accurate spawner_entity.get_set_test(3, "Configuration|Radius Min", 16.0) - general.run_console('veg_debugClearAllAreas') num_expected_instances = 1 final_check_success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) self.test_success = final_check_success and self.test_success From eb8084d3f6c0e6973a8a250aeee9c231218c0691 Mon Sep 17 00:00:00 2001 From: srikappa Date: Fri, 7 May 2021 16:21:23 -0700 Subject: [PATCH 010/100] Initial draft for getting instantiation to work immediately after creation is undone --- .../PrefabEditorEntityOwnershipService.cpp | 4 +- .../Instance/InstanceToTemplatePropagator.cpp | 14 +++++- .../AzToolsFramework/Prefab/Link/Link.cpp | 3 ++ .../AzToolsFramework/Prefab/PrefabDomTypes.h | 1 + .../Prefab/PrefabPublicHandler.cpp | 47 +++++++++++++++---- .../Prefab/PrefabPublicHandler.h | 2 +- .../Prefab/PrefabSystemComponent.cpp | 6 +-- .../Prefab/PrefabSystemComponent.h | 2 +- .../Prefab/PrefabSystemComponentInterface.h | 2 +- .../AzToolsFramework/Prefab/PrefabUndo.cpp | 23 +++++---- .../AzToolsFramework/Prefab/PrefabUndo.h | 2 +- .../Prefab/PrefabUndoHelpers.cpp | 8 ++-- .../Prefab/PrefabUndoHelpers.h | 4 +- .../Tests/Prefab/PrefabUndoLinkTests.cpp | 4 +- 14 files changed, 88 insertions(+), 34 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp index 81233069a9..58aa245397 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp @@ -281,13 +281,15 @@ namespace AzToolsFramework containerEntity->AddComponent(aznew Prefab::EditorPrefabComponent()); HandleEntitiesAdded({containerEntity}); HandleEntitiesAdded(entities); - + + /* // Update the template of the instance since we modified the entities of the instance by calling HandleEntitiesAdded. Prefab::PrefabDom serializedInstance; if (Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(addedInstance, serializedInstance)) { m_prefabSystemComponent->UpdatePrefabTemplate(addedInstance.GetTemplateId(), serializedInstance); } + */ return addedInstance; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp index b1c5f64ef9..d298e1e2b2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp @@ -176,10 +176,15 @@ namespace AzToolsFramework { PrefabDom& templateDomReference = m_prefabSystemComponentInterface->FindTemplateDom(templateId); + PrefabDomUtils::PrintPrefabDomValue("patch is ", providedPatch); + PrefabDomUtils::PrintPrefabDomValue("template dom before is ", templateDomReference); + //apply patch to template AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::ApplyPatch(templateDomReference, templateDomReference.GetAllocator(), providedPatch, AZ::JsonMergeApproach::JsonPatch); + PrefabDomUtils::PrintPrefabDomValue("template dom after is ", templateDomReference); + //trigger propagation if (result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Success) { @@ -270,7 +275,7 @@ namespace AzToolsFramework return parentInstance; } - void InstanceToTemplatePropagator::AddPatchesToLink(PrefabDom& patches, Link& link) + void InstanceToTemplatePropagator::AddPatchesToLink(const PrefabDom& patches, Link& link) { PrefabDom& linkDom = link.GetLinkDom(); PrefabDomValueReference linkPatchesReference = @@ -279,7 +284,12 @@ namespace AzToolsFramework // This logic only covers addition of patches. If patches already exists, the given list of patches must be appended to them. if (!linkPatchesReference.has_value()) { - linkDom.AddMember(rapidjson::StringRef(PrefabDomUtils::PatchesName), patches, linkDom.GetAllocator()); + // If the original allocator the patches were created with gets destroyed, then the patches would become garbage in the + // linkDom. Since we cannot guarantee the lifecycle of the patch allocators, we are doing a copy of the patches here to + // associate them with the linkDom's allocator. This is a limitation with rapidjson. + PrefabDom patchesCopy; + patchesCopy.CopyFrom(patches, linkDom.GetAllocator()); + linkDom.AddMember(rapidjson::StringRef(PrefabDomUtils::PatchesName), patchesCopy, linkDom.GetAllocator()); } } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp index e0834ed53b..e421e55a11 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp @@ -181,6 +181,8 @@ namespace AzToolsFramework } else { + PrefabDomUtils::PrintPrefabDomValue("Patches are : ", m_linkDom); + PrefabDomUtils::PrintPrefabDomValue("Linked instance dom before is : ", linkedInstanceDom); AZ::JsonSerializationResult::ResultCode applyPatchResult = AZ::JsonSerialization::ApplyPatch( linkedInstanceDom, targetTemplatePrefabDom.GetAllocator(), @@ -193,6 +195,7 @@ namespace AzToolsFramework "Link::UpdateTarget - " "ApplyPatches failed for Prefab DOM from source Template '%u' and target Template '%u'.", m_sourceTemplateId, m_targetTemplateId); + PrefabDomUtils::PrintPrefabDomValue("Linked instance dom after is : ", linkedInstanceDom); return false; } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomTypes.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomTypes.h index e32f817227..e897630a91 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomTypes.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomTypes.h @@ -27,6 +27,7 @@ namespace AzToolsFramework using PrefabDomList = AZStd::vector; using PrefabDomReference = AZStd::optional>; + using PrefabDomConstReference = AZStd::optional>; using PrefabDomValueReference = AZStd::optional>; using PrefabDomValueConstReference = AZStd::optional>; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 475510c52f..80e1b558e7 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -122,6 +122,24 @@ namespace AzToolsFramework AZ::EntityId containerEntityId = instanceToCreate->get().GetContainerEntityId(); + // Change top level entities to be parented to the container entity + // Mark them as dirty so this change is correctly applied to the template + for (AZ::Entity* topLevelEntity : entities) + { + //m_prefabUndoCache.UpdateCache(topLevelEntity->GetId()); + // undoBatch.MarkEntityDirty(topLevelEntity->GetId()); + AZ::TransformBus::Event(topLevelEntity->GetId(), &AZ::TransformBus::Events::SetParent, containerEntityId); + //ToolsApplicationRequests::Bus::Broadcast( + // &ToolsApplicationRequests::Bus::Events::RemoveDirtyEntity, topLevelEntity->GetId()); + } + + // Update the template of the instance since we modified the entities of the instance by calling HandleEntitiesAdded. + Prefab::PrefabDom serializedInstance; + if (Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(instanceToCreate->get(), serializedInstance)) + { + m_prefabSystemComponentInterface->UpdatePrefabTemplate(instanceToCreate->get().GetTemplateId(), serializedInstance); + } + instanceToCreate->get().GetNestedInstances([&](AZStd::unique_ptr& nestedInstance) { AZ_Assert(nestedInstance, "Invalid nested instance found in the new prefab created."); EntityOptionalReference nestedInstanceContainerEntity = nestedInstance->GetContainerEntity(); @@ -129,7 +147,7 @@ namespace AzToolsFramework nestedInstanceContainerEntity, "Invalid container entity found for the nested instance used in prefab creation."); CreateLink( {&nestedInstanceContainerEntity->get()}, *nestedInstance, instanceToCreate->get().GetTemplateId(), - undoBatch.GetUndoBatch(), containerEntityId); + undoBatch.GetUndoBatch(), containerEntityId, false); }); CreateLink( @@ -141,10 +159,13 @@ namespace AzToolsFramework for (AZ::Entity* topLevelEntity : topLevelEntities) { m_prefabUndoCache.UpdateCache(topLevelEntity->GetId()); - undoBatch.MarkEntityDirty(topLevelEntity->GetId()); - AZ::TransformBus::Event(topLevelEntity->GetId(), &AZ::TransformBus::Events::SetParent, containerEntityId); + //undoBatch.MarkEntityDirty(topLevelEntity->GetId()); + //AZ::TransformBus::Event(topLevelEntity->GetId(), &AZ::TransformBus::Events::SetParent, containerEntityId); + ToolsApplicationRequests::Bus::Broadcast( + &ToolsApplicationRequests::Bus::Events::RemoveDirtyEntity, topLevelEntity->GetId()); } + // Select Container Entity { auto selectionUndo = aznew SelectionCommand({containerEntityId}, "Select Prefab Container Entity"); @@ -244,7 +265,7 @@ namespace AzToolsFramework void PrefabPublicHandler::CreateLink( const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId, - UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId) + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool IsUndoRedoSupportNeeded) { AZ::EntityId containerEntityId = sourceInstance.GetContainerEntityId(); AZ::Entity* containerEntity = GetEntityById(containerEntityId); @@ -270,9 +291,19 @@ namespace AzToolsFramework m_instanceToTemplateInterface->GeneratePatch(patch, containerEntityDomBefore, containerEntityDomAfter); m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(patch, containerEntityId); - LinkId linkId = PrefabUndoHelpers::CreateLink( - sourceInstance.GetTemplateId(), targetTemplateId, patch, sourceInstance.GetInstanceAlias(), - undoBatch); + LinkId linkId; + if (IsUndoRedoSupportNeeded) + { + linkId = PrefabUndoHelpers::CreateLink( + sourceInstance.GetTemplateId(), targetTemplateId, AZStd::move(patch), sourceInstance.GetInstanceAlias(), undoBatch); + } + else + { + linkId = m_prefabSystemComponentInterface->CreateLink( + targetTemplateId, sourceInstance.GetTemplateId(), sourceInstance.GetInstanceAlias(), AZStd::move(patch), + InvalidLinkId); + m_prefabSystemComponentInterface->PropagateTemplateChanges(targetTemplateId); + } sourceInstance.SetLinkId(linkId); @@ -305,7 +336,7 @@ namespace AzToolsFramework patchesCopyForUndoSupport.CopyFrom(nestedInstanceLinkPatches->get(), patchesCopyForUndoSupport.GetAllocator()); PrefabUndoHelpers::RemoveLink( sourceInstance->GetTemplateId(), targetTemplateId, sourceInstance->GetInstanceAlias(), sourceInstance->GetLinkId(), - patchesCopyForUndoSupport, undoBatch); + AZStd::move(patchesCopyForUndoSupport), undoBatch); } 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 5ade666a40..0e15fd9a15 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -80,7 +80,7 @@ namespace AzToolsFramework */ void CreateLink( const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId, - UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId); + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool IsUndoRedoSupportNeeded = true); /** * Removes the link between template of the sourceInstance and the template corresponding to targetTemplateId. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp index c6a95b01fe..0b447ef786 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp @@ -583,7 +583,7 @@ namespace AzToolsFramework const TemplateId& linkTargetId, const TemplateId& linkSourceId, const InstanceAlias& instanceAlias, - const PrefabDomReference linkPatch, + PrefabDom linkPatch, const LinkId& linkId) { if (linkTargetId == InvalidTemplateId) @@ -667,9 +667,9 @@ namespace AzToolsFramework rapidjson::StringRef(PrefabDomUtils::SourceName), rapidjson::StringRef(sourceTemplate.GetFilePath().c_str()), newLink.GetLinkDom().GetAllocator()); - if (linkPatch && linkPatch->get().IsArray() && !(linkPatch->get().Empty())) + if (linkPatch.IsArray() && !(linkPatch.Empty())) { - m_instanceToTemplatePropagator.AddPatchesToLink(linkPatch.value(), newLink); + m_instanceToTemplatePropagator.AddPatchesToLink(AZStd::move(linkPatch), newLink); } //update the target template dom to have the proper values for the source template dom diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h index 30d03ba2ef..b5f499296d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h @@ -156,7 +156,7 @@ namespace AzToolsFramework const TemplateId& linkTargetId, const TemplateId& linkSourceId, const InstanceAlias& instanceAlias, - const PrefabDomReference linkPatch, + PrefabDom linkPatch, const LinkId& linkId = InvalidLinkId) override; /** diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h index 6491d67401..347b48a648 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h @@ -44,7 +44,7 @@ namespace AzToolsFramework //creates a new Link virtual LinkId CreateLink(const TemplateId& linkTargetId, const TemplateId& linkSourceId, - const InstanceAlias& instanceAlias, const PrefabDomReference linkPatch, + const InstanceAlias& instanceAlias, PrefabDom linkPatch, const LinkId& linkId = InvalidLinkId) = 0; virtual void RemoveLink(const LinkId& linkId) = 0; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp index ad0cdc166a..e82e9da90a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp @@ -124,7 +124,7 @@ namespace AzToolsFramework const TemplateId& targetId, const TemplateId& sourceId, const InstanceAlias& instanceAlias, - PrefabDomReference linkPatches, + PrefabDom linkPatches, const LinkId linkId) { m_targetId = targetId; @@ -132,10 +132,7 @@ namespace AzToolsFramework m_instanceAlias = instanceAlias; m_linkId = linkId; - if (linkPatches.has_value()) - { - m_linkPatches = AZStd::move(linkPatches->get()); - } + m_linkPatches = AZStd::move(linkPatches); //if linkId is invalid, set as ADD if (m_linkId == InvalidLinkId) @@ -193,7 +190,9 @@ namespace AzToolsFramework void PrefabUndoInstanceLink::AddLink() { - m_linkId = m_prefabSystemComponentInterface->CreateLink(m_targetId, m_sourceId, m_instanceAlias, m_linkPatches, m_linkId); + PrefabDom linkPatchesCopy; + linkPatchesCopy.CopyFrom(m_linkPatches, linkPatchesCopy.GetAllocator()); + m_linkId = m_prefabSystemComponentInterface->CreateLink(m_targetId, m_sourceId, m_instanceAlias, AZStd::move(linkPatchesCopy), m_linkId); } void PrefabUndoInstanceLink::RemoveLink() @@ -228,9 +227,12 @@ namespace AzToolsFramework if (link.has_value()) { - m_linkDomPrevious = AZStd::move(link->get().GetLinkDom()); + m_linkDomPrevious.CopyFrom(link->get().GetLinkDom(), m_linkDomPrevious.GetAllocator()); } + PrefabDomUtils::PrintPrefabDomValue("m_linkDomPrevious is : ", m_linkDomPrevious); + PrefabDomUtils::PrintPrefabDomValue("link->get().GetLinkDom() is : ", link->get().GetLinkDom()); + //get source templateDom TemplateReference sourceTemplate = m_prefabSystemComponentInterface->FindTemplate(link->get().GetSourceTemplateId()); @@ -275,7 +277,7 @@ namespace AzToolsFramework if (patchesIter == m_linkDomNext.MemberEnd()) { m_linkDomNext.AddMember( - rapidjson::GenericStringRef(PrefabDomUtils::PatchesName), patchLinkCopy, m_linkDomNext.GetAllocator()); + rapidjson::GenericStringRef(PrefabDomUtils::PatchesName), AZStd::move(patchLinkCopy), m_linkDomNext.GetAllocator()); } else { @@ -303,9 +305,14 @@ namespace AzToolsFramework return; } + /* PrefabDom moveLink; moveLink.CopyFrom(linkDom, linkDom.GetAllocator()); link->get().GetLinkDom() = AZStd::move(moveLink); + */ + link->get().SetLinkDom(linkDom); + + PrefabDomUtils::PrintPrefabDomValue("dom after updating link is : ", link->get().GetLinkDom()); //propagate the link changes link->get().UpdateTarget(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h index 49bae4eda0..33d9e5ad33 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 linkPatches = PrefabDomReference(), + PrefabDom linkPatches = PrefabDom(), const LinkId linkId = InvalidLinkId); void Undo() override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp index 24eb71e055..5ba8d3c940 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp @@ -34,11 +34,11 @@ namespace AzToolsFramework } LinkId CreateLink( - TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDomReference patch, + TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDom patch, const InstanceAlias& instanceAlias, UndoSystem::URSequencePoint* undoBatch) { auto linkAddUndo = aznew PrefabUndoInstanceLink("Create Link"); - linkAddUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, patch, InvalidLinkId); + linkAddUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, AZStd::move(patch), InvalidLinkId); linkAddUndo->SetParent(undoBatch); linkAddUndo->Redo(); @@ -47,10 +47,10 @@ namespace AzToolsFramework void RemoveLink( TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias, LinkId linkId, - PrefabDomReference linkPatches, UndoSystem::URSequencePoint* undoBatch) + PrefabDom linkPatches, UndoSystem::URSequencePoint* undoBatch) { auto linkRemoveUndo = aznew PrefabUndoInstanceLink("Remove Link"); - linkRemoveUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, linkPatches, linkId); + linkRemoveUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, AZStd::move(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 6429df3b04..17cf7f52c1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h @@ -22,11 +22,11 @@ namespace AzToolsFramework const Instance& instance, AZStd::string_view undoMessage, const PrefabDom& instanceDomBeforeUpdate, UndoSystem::URSequencePoint* undoBatch); LinkId CreateLink( - TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDomReference patch, + TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDom patch, const InstanceAlias& instanceAlias, UndoSystem::URSequencePoint* undoBatch); void RemoveLink( TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias, LinkId linkId, - PrefabDomReference linkPatches, UndoSystem::URSequencePoint* undoBatch); + PrefabDom linkPatches, UndoSystem::URSequencePoint* undoBatch); } } // namespace Prefab } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUndoLinkTests.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUndoLinkTests.cpp index 2122b116d8..3d540a7a95 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUndoLinkTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUndoLinkTests.cpp @@ -120,7 +120,7 @@ namespace UnitTest //create an undo node to apply the patch and prep for undo PrefabUndoInstanceLink undoInstanceLinkNode("Undo Link Patch"); - undoInstanceLinkNode.Capture(rootTemplateId, nestedTemplateId, aliases[0], patch, InvalidLinkId); + undoInstanceLinkNode.Capture(rootTemplateId, nestedTemplateId, aliases[0], AZStd::move(patch), InvalidLinkId); undoInstanceLinkNode.Redo(); m_instanceUpdateExecutorInterface->UpdateTemplateInstancesInQueue(); @@ -196,7 +196,7 @@ namespace UnitTest //create an undo node to apply the patch and prep for undo PrefabUndoInstanceLink undoInstanceLinkNode("Undo Link Patch"); - undoInstanceLinkNode.Capture(rootTemplateId, nestedTemplateId, aliases[0], linkPatch, InvalidLinkId); + undoInstanceLinkNode.Capture(rootTemplateId, nestedTemplateId, aliases[0], AZStd::move(linkPatch), InvalidLinkId); undoInstanceLinkNode.Redo(); m_instanceUpdateExecutorInterface->UpdateTemplateInstancesInQueue(); From 1c04160966bf3d358f07192ec81cf2247d26e1e3 Mon Sep 17 00:00:00 2001 From: srikappa Date: Fri, 7 May 2021 16:23:14 -0700 Subject: [PATCH 011/100] Added a missing header --- .../Prefab/Instance/InstanceToTemplatePropagator.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.h index ca1f3a7c91..9a6aad8ac1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.h @@ -41,7 +41,7 @@ namespace AzToolsFramework void ApplyPatchesToInstance(const AZ::EntityId& entityId, PrefabDom& patches, const Instance& instanceToAddPatches) override; - void AddPatchesToLink(PrefabDom& patches, Link& link); + void AddPatchesToLink(const PrefabDom& patches, Link& link); private: From e9165ed91116d98b507e050e99902a1510e59fb7 Mon Sep 17 00:00:00 2001 From: guthadam Date: Fri, 7 May 2021 20:16:05 -0500 Subject: [PATCH 012/100] Added save state keys to most of the RPEs in the material editor and component to save expand/collapse state Saving main window fancy docking state so all of the dock widgets save/restore visibly and positioning Added window decoration wrapper inside material editor main window for saving/restoring window position, size, state Added object names to several QT widgets so that their state could be captured and restored --- .../Inspector/InspectorPropertyGroupWidget.h | 1 + .../InspectorPropertyGroupWidget.cpp | 2 + .../Window/MaterialEditorWindowSettings.h | 5 +- .../Source/Window/MaterialEditorWindow.cpp | 113 +++++++++++------- .../Window/MaterialEditorWindowComponent.cpp | 1 - .../Window/MaterialEditorWindowSettings.cpp | 17 +-- .../MaterialInspector/MaterialInspector.cpp | 18 ++- .../MaterialInspector/MaterialInspector.h | 1 + .../ViewportSettingsInspector.cpp | 10 +- .../EditorMaterialComponentInspector.cpp | 12 +- 10 files changed, 109 insertions(+), 71 deletions(-) diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorPropertyGroupWidget.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorPropertyGroupWidget.h index 71ca975f58..60eae524a5 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorPropertyGroupWidget.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorPropertyGroupWidget.h @@ -44,6 +44,7 @@ namespace AtomToolsFramework const AZ::Uuid& instanceClassId, AzToolsFramework::IPropertyEditorNotify* instanceNotificationHandler = {}, QWidget* parent = {}, + const AZ::u32 saveStateKey = {}, const AzToolsFramework::InstanceDataHierarchy::ValueComparisonFunction& valueComparisonFunction = {}); void Refresh() override; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorPropertyGroupWidget.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorPropertyGroupWidget.cpp index c4d78d1acb..b850b4a488 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorPropertyGroupWidget.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorPropertyGroupWidget.cpp @@ -22,6 +22,7 @@ namespace AtomToolsFramework const AZ::Uuid& instanceClassId, AzToolsFramework::IPropertyEditorNotify* instanceNotificationHandler, QWidget* parent, + const AZ::u32 saveStateKey, const AzToolsFramework::InstanceDataHierarchy::ValueComparisonFunction& valueComparisonFunction) : InspectorGroupWidget(parent) { @@ -37,6 +38,7 @@ namespace AtomToolsFramework m_propertyEditor->SetHideRootProperties(true); m_propertyEditor->SetAutoResizeLabels(true); m_propertyEditor->SetValueComparisonFunction(valueComparisonFunction); + m_propertyEditor->SetSavedStateKey(saveStateKey); m_propertyEditor->Setup(context, instanceNotificationHandler, false); m_propertyEditor->AddInstance(instance, instanceClassId, nullptr, instanceToCompare); m_propertyEditor->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowSettings.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowSettings.h index bf572b070a..b28d4d662b 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowSettings.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowSettings.h @@ -29,9 +29,6 @@ namespace MaterialEditor static void Reflect(AZ::ReflectContext* context); - bool m_enableGrid = true; - bool m_enableShadowCatcher = true; - bool m_enableAlternateSkybox = false; - float m_fieldOfView = 90.0f; + AZStd::vector m_mainWindowState; }; } // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index 12e75f8fcf..e62dae2986 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -10,46 +10,50 @@ * */ +#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 -#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT +#include +#include #include -#include +#include #include -#include #include +#include +#include AZ_POP_DISABLE_WARNING namespace MaterialEditor @@ -57,6 +61,15 @@ namespace MaterialEditor MaterialEditorWindow::MaterialEditorWindow(QWidget* parent /* = 0 */) : AzQtComponents::DockMainWindow(parent) { + resize(1280, 1024); + + // Among other things, we need the window wrapper to save the main window size, position, and state + auto mainWindowWrapper = + new AzQtComponents::WindowDecorationWrapper(AzQtComponents::WindowDecorationWrapper::OptionAutoTitleBarButtons); + mainWindowWrapper->setGuest(this); + mainWindowWrapper->enableSaveRestoreGeometry("amazon", "MaterialEditor", "mainWindowGeometry"); + + // set the style sheet for RPE highlighting and other styling AzQtComponents::StyleManager::setStyleSheet(this, QStringLiteral(":/MaterialEditor.qss")); QApplication::setWindowIcon(QIcon(":/Icons/materialtype.svg")); @@ -75,6 +88,7 @@ namespace MaterialEditor m_advancedDockManager = new AzQtComponents::FancyDocking(this); + setObjectName("MaterialEditorWindow"); setDockNestingEnabled(true); setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); @@ -82,17 +96,21 @@ namespace MaterialEditor setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); m_menuBar = new QMenuBar(this); + m_menuBar->setObjectName("MenuBar"); setMenuBar(m_menuBar); m_toolBar = new MaterialEditorToolBar(this); + m_toolBar->setObjectName("ToolBar"); addToolBar(m_toolBar); m_centralWidget = new QWidget(this); m_tabWidget = new AzQtComponents::TabWidget(m_centralWidget); + m_tabWidget->setObjectName("TabWidget"); m_tabWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); m_tabWidget->setContentsMargins(0, 0, 0, 0); m_materialViewport = new MaterialViewportWidget(m_centralWidget); + m_materialViewport->setObjectName("Viewport"); m_materialViewport->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); QVBoxLayout* vl = new QVBoxLayout(m_centralWidget); @@ -104,7 +122,8 @@ namespace MaterialEditor setCentralWidget(m_centralWidget); m_statusBar = new StatusBarWidget(this); - this->statusBar()->addPermanentWidget(m_statusBar, 1); + m_statusBar->setObjectName("StatusBar"); + statusBar()->addPermanentWidget(m_statusBar, 1); SetupMenu(); SetupTabs(); @@ -119,27 +138,26 @@ namespace MaterialEditor SetDockWidgetVisible("Performance Monitor", false); SetDockWidgetVisible("Python Terminal", false); - MaterialEditorWindowRequestBus::Handler::BusConnect(); - MaterialDocumentNotificationBus::Handler::BusConnect(); - OnDocumentOpened(AZ::Uuid::CreateNull()); + // Restore geometry and show the window + mainWindowWrapper->showFromSettings(); + + // Restore additional state for docked windows + auto windowSettings = AZ::UserSettings::CreateFind( + AZ::Crc32("MaterialEditorwindowSettings"), AZ::UserSettings::CT_GLOBAL); - auto windowState = AZ::UserSettings::Find( - AZ::Crc32("MaterialEditorWindowState"), AZ::UserSettings::CT_GLOBAL); - if (windowState) + if (!windowSettings->m_mainWindowState.empty()) { - windowState->RestoreGeometry(this); + QByteArray windowState(windowSettings->m_mainWindowState.data(), windowSettings->m_mainWindowState.size()); + m_advancedDockManager->restoreState(windowState); } + + MaterialEditorWindowRequestBus::Handler::BusConnect(); + MaterialDocumentNotificationBus::Handler::BusConnect(); + OnDocumentOpened(AZ::Uuid::CreateNull()); } MaterialEditorWindow::~MaterialEditorWindow() { - auto windowState = AZ::UserSettings::CreateFind( - AZ::Crc32("MaterialEditorWindowState"), AZ::UserSettings::CT_GLOBAL); - if (windowState) - { - windowState->CaptureGeometry(this); - } - MaterialDocumentNotificationBus::Handler::BusDisconnect(); MaterialEditorWindowRequestBus::Handler::BusDisconnect(); } @@ -159,8 +177,9 @@ namespace MaterialEditor } auto dockWidget = new AzQtComponents::StyledDockWidget(name.c_str()); - dockWidget->setObjectName(name.c_str()); + dockWidget->setObjectName(QString("%1_DockWidget").arg(name.c_str())); dockWidget->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable); + widget->setObjectName(name.c_str()); widget->setParent(dockWidget); widget->setMinimumSize(QSize(300, 300)); dockWidget->setWidget(widget); @@ -218,15 +237,16 @@ namespace MaterialEditor QSize requestedWindowSize = size() + offset; resize(requestedWindowSize); - AZ_Assert(m_materialViewport->size() == requestedViewportSize, + AZ_Assert( + m_materialViewport->size() == requestedViewportSize, "Resizing the window did not give the expected viewport size. Requested %d x %d but got %d x %d.", - requestedViewportSize.width(), requestedViewportSize.height(), - m_materialViewport->size().width(), m_materialViewport->size().height()); + requestedViewportSize.width(), requestedViewportSize.height(), m_materialViewport->size().width(), + m_materialViewport->size().height()); QSize newDeviceSize = m_materialViewport->size(); - AZ_Warning("Material Editor", newDeviceSize.width() == width && newDeviceSize.height() == height, - "Resizing the window did not give the expected frame size. Requested %d x %d but got %d x %d.", - width, height, + AZ_Warning( + "Material Editor", newDeviceSize.width() == width && newDeviceSize.height() == height, + "Resizing the window did not give the expected frame size. Requested %d x %d but got %d x %d.", width, height, newDeviceSize.width(), newDeviceSize.height()); } @@ -250,6 +270,13 @@ namespace MaterialEditor return; } + // Capture docking state before shutdown + auto windowSettings = AZ::UserSettings::CreateFind( + AZ::Crc32("MaterialEditorwindowSettings"), AZ::UserSettings::CT_GLOBAL); + + QByteArray windowState = m_advancedDockManager->saveState(); + windowSettings->m_mainWindowState.assign(windowState.begin(), windowState.end()); + MaterialEditorWindowNotificationBus::Broadcast(&MaterialEditorWindowNotifications::OnMaterialEditorWindowClosing); } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp index 3d796a21ad..b0e8533ba4 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp @@ -101,7 +101,6 @@ namespace MaterialEditor m_materialEditorBrowserInteractions.reset(aznew MaterialEditorBrowserInteractions); m_window.reset(aznew MaterialEditorWindow); - m_window->show(); } void MaterialEditorWindowComponent::DestroyMaterialEditorWindow() diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp index a9c928df10..5ea23de8c6 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp @@ -22,11 +22,8 @@ namespace MaterialEditor { serializeContext->Class() ->Version(1) - ->Field("enableGrid", &MaterialEditorWindowSettings::m_enableGrid) - ->Field("enableShadowCatcher", &MaterialEditorWindowSettings::m_enableShadowCatcher) - ->Field("enableAlternateSkybox", &MaterialEditorWindowSettings::m_enableAlternateSkybox) - ->Field("fieldOfView", &MaterialEditorWindowSettings::m_fieldOfView) - ; + ->Field("mainWindowState", &MaterialEditorWindowSettings::m_mainWindowState) + ; if (auto editContext = serializeContext->GetEditContext()) { @@ -34,12 +31,6 @@ namespace MaterialEditor "MaterialEditorWindowSettings", "") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialEditorWindowSettings::m_enableGrid, "Enable Grid", "") - ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialEditorWindowSettings::m_enableShadowCatcher, "Enable Shadow Catcher", "") - ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialEditorWindowSettings::m_enableAlternateSkybox, "Enable Alternate Skybox", "") - ->DataElement(AZ::Edit::UIHandlers::Slider, &MaterialEditorWindowSettings::m_fieldOfView, "Field Of View", "") - ->Attribute(AZ::Edit::Attributes::Min, 60.0f) - ->Attribute(AZ::Edit::Attributes::Max, 120.0f) ; } } @@ -52,10 +43,6 @@ namespace MaterialEditor ->Attribute(AZ::Script::Attributes::Module, "render") ->Constructor() ->Constructor() - ->Property("enableGrid", BehaviorValueProperty(&MaterialEditorWindowSettings::m_enableGrid)) - ->Property("enableShadowCatcher", BehaviorValueProperty(&MaterialEditorWindowSettings::m_enableShadowCatcher)) - ->Property("enableAlternateSkybox", BehaviorValueProperty(&MaterialEditorWindowSettings::m_enableAlternateSkybox)) - ->Property("fieldOfView", BehaviorValueProperty(&MaterialEditorWindowSettings::m_fieldOfView)) ; } } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp index b066c3c7dd..dffbd43702 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp @@ -39,6 +39,7 @@ namespace MaterialEditor void MaterialInspector::Reset() { + m_documentPath.clear(); m_documentId = AZ::Uuid::CreateNull(); m_groups = {}; @@ -55,6 +56,8 @@ namespace MaterialEditor bool isOpen = false; MaterialDocumentRequestBus::EventResult(isOpen, m_documentId, &MaterialDocumentRequestBus::Events::IsOpen); + MaterialDocumentRequestBus::EventResult(m_documentPath, m_documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); + if (!m_documentId.IsNull() && isOpen) { // Create the top group for displaying details about the material @@ -89,7 +92,10 @@ namespace MaterialEditor group.m_properties.push_back(property); // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties - auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget(&group, &group, group.TYPEINFO_Uuid(), this, this, + const AZ::Crc32 saveStateKey( + AZStd::string::format("MaterialInspector::PropertyGroup::%s::%s", m_documentPath.c_str(), groupDisplayName.c_str())); + auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( + &group, &group, group.TYPEINFO_Uuid(), this, this, saveStateKey, [this](const AzToolsFramework::InstanceDataNode* source, const AzToolsFramework::InstanceDataNode* target) { AZ_UNUSED(source); const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(target); @@ -121,7 +127,10 @@ namespace MaterialEditor } // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties - auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget(&group, &group, group.TYPEINFO_Uuid(), this, this, + const AZ::Crc32 saveStateKey( + AZStd::string::format("MaterialInspector::PropertyGroup::%s::%s", m_documentPath.c_str(), groupDisplayName.c_str())); + auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( + &group, &group, group.TYPEINFO_Uuid(), this, this, saveStateKey, [this](const AzToolsFramework::InstanceDataNode* source, const AzToolsFramework::InstanceDataNode* target) { AZ_UNUSED(source); const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(target); @@ -156,7 +165,10 @@ namespace MaterialEditor } // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties - auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget(&group, &group, group.TYPEINFO_Uuid(), this, this, + const AZ::Crc32 saveStateKey( + AZStd::string::format("MaterialInspector::PropertyGroup::%s::%s", m_documentPath.c_str(), groupDisplayName.c_str())); + auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( + &group, &group, group.TYPEINFO_Uuid(), this, this, saveStateKey, [this](const AzToolsFramework::InstanceDataNode* source, const AzToolsFramework::InstanceDataNode* target) { AZ_UNUSED(source); const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(target); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h index efe979e5ea..a7a4dddbaa 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h @@ -64,6 +64,7 @@ namespace MaterialEditor const AtomToolsFramework::DynamicProperty* m_activeProperty = nullptr; AZ::Uuid m_documentId = AZ::Uuid::CreateNull(); + AZStd::string m_documentPath; AZStd::unordered_map m_groups; }; } // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.cpp index 22e752dddd..384644f79c 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.cpp @@ -58,9 +58,11 @@ namespace MaterialEditor const AZStd::string groupDisplayName = "General"; const AZStd::string groupDescription = "General"; + const AZ::Crc32 saveStateKey(AZStd::string::format("ViewportSettingsInspector::GeneralGroup")); AddGroup( groupNameId, groupDisplayName, groupDescription, - new AtomToolsFramework::InspectorPropertyGroupWidget(m_viewportSettings.get(), nullptr, m_viewportSettings->TYPEINFO_Uuid(), this)); + new AtomToolsFramework::InspectorPropertyGroupWidget( + m_viewportSettings.get(), nullptr, m_viewportSettings->TYPEINFO_Uuid(), this, this, saveStateKey)); } void ViewportSettingsInspector::AddModelGroup() @@ -92,8 +94,9 @@ namespace MaterialEditor if (m_modelPreset) { + const AZ::Crc32 saveStateKey(AZStd::string::format("ViewportSettingsInspector::ModelGroup")); auto inspectorWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( - m_modelPreset.get(), nullptr, m_modelPreset.get()->TYPEINFO_Uuid(), this, groupWidget); + m_modelPreset.get(), nullptr, m_modelPreset.get()->TYPEINFO_Uuid(), this, groupWidget, saveStateKey); groupWidget->layout()->addWidget(inspectorWidget); } @@ -179,8 +182,9 @@ namespace MaterialEditor if (m_lightingPreset) { + const AZ::Crc32 saveStateKey(AZStd::string::format("ViewportSettingsInspector::LightingGroup")); auto inspectorWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( - m_lightingPreset.get(), nullptr, m_lightingPreset.get()->TYPEINFO_Uuid(), this, groupWidget); + m_lightingPreset.get(), nullptr, m_lightingPreset.get()->TYPEINFO_Uuid(), this, groupWidget, saveStateKey); groupWidget->layout()->addWidget(inspectorWidget); } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp index 03533e142f..1ae0610169 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp @@ -213,7 +213,11 @@ namespace AZ } // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties - auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget(&group, &group, group.TYPEINFO_Uuid(), this, this, + const AZ::Crc32 saveStateKey(AZStd::string::format( + "MaterialPropertyInspector::PropertyGroup::%s::%s", m_materialAssetId.ToString().c_str(), + groupDisplayName.c_str())); + auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( + &group, &group, group.TYPEINFO_Uuid(), this, this, saveStateKey, [this](const AzToolsFramework::InstanceDataNode* source, const AzToolsFramework::InstanceDataNode* target) { AZ_UNUSED(source); const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(target); @@ -262,7 +266,11 @@ namespace AZ } // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties - auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget(&group, &group, group.TYPEINFO_Uuid(), this, this, + const AZ::Crc32 saveStateKey(AZStd::string::format( + "MaterialPropertyInspector::PropertyGroup::%s::%s", m_materialAssetId.ToString().c_str(), + groupDisplayName.c_str())); + auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( + &group, &group, group.TYPEINFO_Uuid(), this, this, saveStateKey, [this](const AzToolsFramework::InstanceDataNode* source, const AzToolsFramework::InstanceDataNode* target) { AZ_UNUSED(source); const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(target); From 1dda6dabe4db1f1b166b3fe0e656f15915efc2d9 Mon Sep 17 00:00:00 2001 From: guthadam Date: Sat, 8 May 2021 00:57:16 -0500 Subject: [PATCH 013/100] Added support for expanding/collapsing material inspector groups by name Saving/restoring material inspector group expansion state --- .../Inspector/InspectorGroupHeaderWidget.h | 4 +- .../Inspector/InspectorRequestBus.h | 9 ++ .../Inspector/InspectorWidget.h | 15 ++- .../Inspector/InspectorGroupHeaderWidget.cpp | 17 +++- .../Code/Source/Inspector/InspectorWidget.cpp | 98 ++++++++++++++----- .../Window/MaterialEditorWindowSettings.h | 1 + .../Source/Window/MaterialEditorWindow.cpp | 4 +- .../Window/MaterialEditorWindowSettings.cpp | 1 + .../MaterialInspector/MaterialInspector.cpp | 68 ++++++++----- .../MaterialInspector/MaterialInspector.h | 10 ++ .../EditorMaterialComponentInspector.cpp | 4 +- 11 files changed, 167 insertions(+), 64 deletions(-) diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorGroupHeaderWidget.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorGroupHeaderWidget.h index bba299187b..931f88d0eb 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorGroupHeaderWidget.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorGroupHeaderWidget.h @@ -29,11 +29,13 @@ namespace AtomToolsFramework AZ_CLASS_ALLOCATOR(InspectorGroupHeaderWidget, AZ::SystemAllocator, 0); explicit InspectorGroupHeaderWidget(QWidget* parent = nullptr); - void SetExpanded(bool expanded); + void SetExpanded(bool expand); bool IsExpanded() const; Q_SIGNALS: void clicked(QMouseEvent* event); + void expanded(); + void collapsed(); protected: void mousePressEvent(QMouseEvent* event) override; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorRequestBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorRequestBus.h index 81b512faf2..e76837137a 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorRequestBus.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorRequestBus.h @@ -56,6 +56,15 @@ namespace AtomToolsFramework //! Calls Rebuild for all InspectorGroupWidget, allowing for destructive UI changes virtual void RebuildAll() = 0; + //! Expands a specific group + virtual void ExpandGroup(const AZStd::string& groupNameId) = 0; + + //! Collapses a specific group + virtual void CollapseGroup(const AZStd::string& groupNameId) = 0; + + //! Checks the expansion state of a specific group + virtual bool IsGroupExpanded(const AZStd::string& groupNameId) const = 0; + //! Expands all groups and headers virtual void ExpandAll() = 0; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorWidget.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorWidget.h index b0932b3b04..5fb0b731d6 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorWidget.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Inspector/InspectorWidget.h @@ -63,15 +63,22 @@ namespace AtomToolsFramework void RefreshAll() override; void RebuildAll() override; + void ExpandGroup(const AZStd::string& groupNameId) override; + void CollapseGroup(const AZStd::string& groupNameId) override; + bool IsGroupExpanded(const AZStd::string& groupNameId) const override; + void ExpandAll() override; void CollapseAll() override; - private: - void OnHeaderClicked(QMouseEvent* event, InspectorGroupHeaderWidget* groupHeader, QWidget* groupWidget); + protected: + virtual bool ShouldGroupAutoExpanded(const AZStd::string& groupNameId) const; + virtual void OnGroupExpanded(const AZStd::string& groupNameId); + virtual void OnGroupCollapsed(const AZStd::string& groupNameId); + virtual void OnHeaderClicked(const AZStd::string& groupNameId, QMouseEvent* event); + private: QVBoxLayout* m_layout = nullptr; QScopedPointer m_ui; - AZStd::vector m_headers; - AZStd::vector m_groups; + AZStd::unordered_map> m_groups; }; } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorGroupHeaderWidget.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorGroupHeaderWidget.cpp index 41cc1e4a50..666f8f6c93 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorGroupHeaderWidget.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorGroupHeaderWidget.cpp @@ -33,10 +33,21 @@ namespace AtomToolsFramework setMargin(0); } - void InspectorGroupHeaderWidget::SetExpanded(bool expanded) + void InspectorGroupHeaderWidget::SetExpanded(bool expand) { - m_expanded = expanded; - update(); + if (m_expanded != expand) + { + m_expanded = expand; + if (m_expanded) + { + emit expanded(); + } + else + { + emit collapsed(); + } + update(); + } } bool InspectorGroupHeaderWidget::IsExpanded() const diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorWidget.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorWidget.cpp index ec5f9893bd..0259120d9b 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorWidget.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Inspector/InspectorWidget.cpp @@ -39,7 +39,6 @@ namespace AtomToolsFramework m_layout = new QVBoxLayout(m_ui->m_propertyContent); m_layout->setContentsMargins(0, 0, 0, 0); m_layout->setSpacing(0); - m_headers.clear(); m_groups.clear(); } @@ -70,16 +69,27 @@ namespace AtomToolsFramework groupHeader->setText(groupDisplayName.c_str()); groupHeader->setToolTip(groupDescription.c_str()); m_layout->addWidget(groupHeader); - m_headers.push_back(groupHeader); groupWidget->setObjectName(groupNameId.c_str()); groupWidget->setParent(m_ui->m_propertyContent); m_layout->addWidget(groupWidget); - m_groups.push_back(groupWidget); - connect(groupHeader, &InspectorGroupHeaderWidget::clicked, this, [this, groupHeader, groupWidget](QMouseEvent* event) { - OnHeaderClicked(event, groupHeader, groupWidget); + m_groups[groupNameId] = AZStd::make_pair(groupHeader, groupWidget); + + connect(groupHeader, &InspectorGroupHeaderWidget::clicked, this, [this, groupNameId](QMouseEvent* event) { + OnHeaderClicked(groupNameId, event); }); + connect(groupHeader, &InspectorGroupHeaderWidget::expanded, this, [this, groupNameId]() { OnGroupExpanded(groupNameId); }); + connect(groupHeader, &InspectorGroupHeaderWidget::collapsed, this, [this, groupNameId]() { OnGroupCollapsed(groupNameId); }); + + if (ShouldGroupAutoExpanded(groupNameId)) + { + ExpandGroup(groupNameId); + } + else + { + CollapseGroup(groupNameId); + } } void InspectorWidget::RefreshGroup(const AZStd::string& groupNameId) @@ -114,50 +124,86 @@ namespace AtomToolsFramework } } - void InspectorWidget::ExpandAll() + void InspectorWidget::ExpandGroup(const AZStd::string& groupNameId) { - for (auto headerWidget : m_headers) + auto groupItr = m_groups.find(groupNameId); + if (groupItr != m_groups.end()) { - headerWidget->SetExpanded(true); + groupItr->second.first->SetExpanded(true); + groupItr->second.second->setVisible(true); } - for (auto groupWidget : m_groups) + } + + void InspectorWidget::CollapseGroup(const AZStd::string& groupNameId) + { + auto groupItr = m_groups.find(groupNameId); + if (groupItr != m_groups.end()) { - groupWidget->setVisible(true); + groupItr->second.first->SetExpanded(false); + groupItr->second.second->setVisible(false); } } - void InspectorWidget::CollapseAll() + bool InspectorWidget::IsGroupExpanded(const AZStd::string& groupNameId) const + { + auto groupItr = m_groups.find(groupNameId); + return groupItr != m_groups.end() ? groupItr->second.first->IsExpanded() : false; + } + + void InspectorWidget::ExpandAll() { - for (auto headerWidget : m_headers) + for (auto& groupPair : m_groups) { - headerWidget->SetExpanded(false); + groupPair.second.first->SetExpanded(true); + groupPair.second.second->setVisible(true); } - for (auto groupWidget : m_groups) + } + + void InspectorWidget::CollapseAll() + { + for (auto& groupPair : m_groups) { - groupWidget->setVisible(false); + groupPair.second.first->SetExpanded(false); + groupPair.second.second->setVisible(false); } } - void InspectorWidget::OnHeaderClicked(QMouseEvent* event, InspectorGroupHeaderWidget* groupHeader, QWidget* groupWidget) + bool InspectorWidget::ShouldGroupAutoExpanded(const AZStd::string& groupNameId) const + { + AZ_UNUSED(groupNameId); + return true; + } + + void InspectorWidget::OnGroupExpanded(const AZStd::string& groupNameId) + { + AZ_UNUSED(groupNameId); + } + + void InspectorWidget::OnGroupCollapsed(const AZStd::string& groupNameId) + { + AZ_UNUSED(groupNameId); + } + + void InspectorWidget::OnHeaderClicked(const AZStd::string& groupNameId, QMouseEvent* event) { if (event->button() == Qt::MouseButton::LeftButton) { - groupHeader->SetExpanded(!groupHeader->IsExpanded()); - groupWidget->setVisible(groupHeader->IsExpanded()); + if (!IsGroupExpanded(groupNameId)) + { + ExpandGroup(groupNameId); + } + else + { + CollapseGroup(groupNameId); + } return; } if (event->button() == Qt::MouseButton::RightButton) { QMenu menu; - menu.addAction("Expand", [groupHeader, groupWidget]() { - groupHeader->SetExpanded(true); - groupWidget->setVisible(true); - })->setEnabled(!groupHeader->IsExpanded()); - menu.addAction("Collapse", [groupHeader, groupWidget]() { - groupHeader->SetExpanded(false); - groupWidget->setVisible(false); - })->setEnabled(groupHeader->IsExpanded()); + menu.addAction("Expand", [this, groupNameId]() { ExpandGroup(groupNameId); })->setEnabled(!IsGroupExpanded(groupNameId)); + menu.addAction("Collapse", [this, groupNameId]() { CollapseGroup(groupNameId); })->setEnabled(IsGroupExpanded(groupNameId)); menu.addAction("Expand All", [this]() { ExpandAll(); }); menu.addAction("Collapse All", [this]() { CollapseAll(); }); menu.exec(event->globalPos()); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowSettings.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowSettings.h index b28d4d662b..9ff03038f7 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowSettings.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowSettings.h @@ -30,5 +30,6 @@ namespace MaterialEditor static void Reflect(AZ::ReflectContext* context); AZStd::vector m_mainWindowState; + AZStd::unordered_set m_inspectorCollapsedGroups; }; } // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index e62dae2986..075a58c532 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -143,7 +143,7 @@ namespace MaterialEditor // Restore additional state for docked windows auto windowSettings = AZ::UserSettings::CreateFind( - AZ::Crc32("MaterialEditorwindowSettings"), AZ::UserSettings::CT_GLOBAL); + AZ::Crc32("MaterialEditorWindowSettings"), AZ::UserSettings::CT_GLOBAL); if (!windowSettings->m_mainWindowState.empty()) { @@ -272,7 +272,7 @@ namespace MaterialEditor // Capture docking state before shutdown auto windowSettings = AZ::UserSettings::CreateFind( - AZ::Crc32("MaterialEditorwindowSettings"), AZ::UserSettings::CT_GLOBAL); + AZ::Crc32("MaterialEditorWindowSettings"), AZ::UserSettings::CT_GLOBAL); QByteArray windowState = m_advancedDockManager->saveState(); windowSettings->m_mainWindowState.assign(windowState.begin(), windowState.end()); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp index 5ea23de8c6..da04e2ea20 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowSettings.cpp @@ -23,6 +23,7 @@ namespace MaterialEditor serializeContext->Class() ->Version(1) ->Field("mainWindowState", &MaterialEditorWindowSettings::m_mainWindowState) + ->Field("inspectorCollapsedGroups", &MaterialEditorWindowSettings::m_inspectorCollapsedGroups) ; if (auto editContext = serializeContext->GetEditContext()) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp index dffbd43702..2c334ad3b7 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp @@ -21,13 +21,17 @@ #include #include -#include +#include +#include namespace MaterialEditor { MaterialInspector::MaterialInspector(QWidget* parent) : AtomToolsFramework::InspectorWidget(parent) { + m_windowSettings = AZ::UserSettings::CreateFind( + AZ::Crc32("MaterialEditorWindowSettings"), AZ::UserSettings::CT_GLOBAL); + MaterialDocumentNotificationBus::Handler::BusConnect(); } @@ -47,6 +51,22 @@ namespace MaterialEditor AtomToolsFramework::InspectorWidget::Reset(); } + bool MaterialInspector::ShouldGroupAutoExpanded(const AZStd::string& groupNameId) const + { + auto stateItr = m_windowSettings->m_inspectorCollapsedGroups.find(GetGroupSaveStateKey(groupNameId)); + return stateItr == m_windowSettings->m_inspectorCollapsedGroups.end(); + } + + void MaterialInspector::OnGroupExpanded(const AZStd::string& groupNameId) + { + m_windowSettings->m_inspectorCollapsedGroups.erase(GetGroupSaveStateKey(groupNameId)); + } + + void MaterialInspector::OnGroupCollapsed(const AZStd::string& groupNameId) + { + m_windowSettings->m_inspectorCollapsedGroups.insert(GetGroupSaveStateKey(groupNameId)); + } + void MaterialInspector::OnDocumentOpened(const AZ::Uuid& documentId) { AddGroupsBegin(); @@ -73,6 +93,20 @@ namespace MaterialEditor AddGroupsEnd(); } + AZ::Crc32 MaterialInspector::GetGroupSaveStateKey(const AZStd::string& groupNameId) const + { + return AZ::Crc32( + AZStd::string::format("MaterialInspector::PropertyGroup::%s::%s", m_documentPath.c_str(), groupNameId.c_str())); + } + + bool MaterialInspector::CompareInstanceNodeProperties( + const AzToolsFramework::InstanceDataNode* source, const AzToolsFramework::InstanceDataNode* target) const + { + AZ_UNUSED(source); + const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(target); + return property && AtomToolsFramework::ArePropertyValuesEqual(property->GetValue(), property->GetConfig().m_parentValue); + } + void MaterialInspector::AddDetailsGroup() { const AZ::RPI::MaterialTypeSourceData* materialTypeSourceData = nullptr; @@ -92,15 +126,9 @@ namespace MaterialEditor group.m_properties.push_back(property); // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties - const AZ::Crc32 saveStateKey( - AZStd::string::format("MaterialInspector::PropertyGroup::%s::%s", m_documentPath.c_str(), groupDisplayName.c_str())); auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( - &group, &group, group.TYPEINFO_Uuid(), this, this, saveStateKey, - [this](const AzToolsFramework::InstanceDataNode* source, const AzToolsFramework::InstanceDataNode* target) { - AZ_UNUSED(source); - const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(target); - return property && AtomToolsFramework::ArePropertyValuesEqual(property->GetValue(), property->GetConfig().m_parentValue); - }); + &group, &group, group.TYPEINFO_Uuid(), this, this, GetGroupSaveStateKey(groupNameId), + [this](const auto source, const auto target) { return CompareInstanceNodeProperties(source, target); }); AddGroup(groupNameId, groupDisplayName, groupDescription, propertyGroupWidget); } @@ -127,15 +155,9 @@ namespace MaterialEditor } // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties - const AZ::Crc32 saveStateKey( - AZStd::string::format("MaterialInspector::PropertyGroup::%s::%s", m_documentPath.c_str(), groupDisplayName.c_str())); auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( - &group, &group, group.TYPEINFO_Uuid(), this, this, saveStateKey, - [this](const AzToolsFramework::InstanceDataNode* source, const AzToolsFramework::InstanceDataNode* target) { - AZ_UNUSED(source); - const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(target); - return property && AtomToolsFramework::ArePropertyValuesEqual(property->GetValue(), property->GetConfig().m_parentValue); - }); + &group, &group, group.TYPEINFO_Uuid(), this, this, GetGroupSaveStateKey(groupNameId), + [this](const auto source, const auto target) { return CompareInstanceNodeProperties(source, target); }); AddGroup(groupNameId, groupDisplayName, groupDescription, propertyGroupWidget); } @@ -165,15 +187,9 @@ namespace MaterialEditor } // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties - const AZ::Crc32 saveStateKey( - AZStd::string::format("MaterialInspector::PropertyGroup::%s::%s", m_documentPath.c_str(), groupDisplayName.c_str())); auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( - &group, &group, group.TYPEINFO_Uuid(), this, this, saveStateKey, - [this](const AzToolsFramework::InstanceDataNode* source, const AzToolsFramework::InstanceDataNode* target) { - AZ_UNUSED(source); - const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(target); - return property && AtomToolsFramework::ArePropertyValuesEqual(property->GetValue(), property->GetConfig().m_parentValue); - }); + &group, &group, group.TYPEINFO_Uuid(), this, this, GetGroupSaveStateKey(groupNameId), + [this](const auto source, const auto target) { return CompareInstanceNodeProperties(source, target); }); AddGroup(groupNameId, groupDisplayName, groupDescription, propertyGroupWidget); } } @@ -270,4 +286,4 @@ namespace MaterialEditor } } // namespace MaterialEditor -#include +#include diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h index a7a4dddbaa..b2900b979c 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h @@ -41,7 +41,16 @@ namespace MaterialEditor // AtomToolsFramework::InspectorRequestBus::Handler overrides... void Reset() override; + protected: + bool ShouldGroupAutoExpanded(const AZStd::string& groupNameId) const override; + void OnGroupExpanded(const AZStd::string& groupNameId) override; + void OnGroupCollapsed(const AZStd::string& groupNameId) override; + private: + AZ::Crc32 GetGroupSaveStateKey(const AZStd::string& groupNameId) const; + bool CompareInstanceNodeProperties( + const AzToolsFramework::InstanceDataNode* source, const AzToolsFramework::InstanceDataNode* target) const; + void AddDetailsGroup(); void AddUvNamesGroup(); void AddPropertiesGroup(); @@ -66,5 +75,6 @@ namespace MaterialEditor AZ::Uuid m_documentId = AZ::Uuid::CreateNull(); AZStd::string m_documentPath; AZStd::unordered_map m_groups; + AZStd::intrusive_ptr m_windowSettings; }; } // namespace MaterialEditor diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp index 1ae0610169..7f54e386fc 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp @@ -215,7 +215,7 @@ namespace AZ // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties const AZ::Crc32 saveStateKey(AZStd::string::format( "MaterialPropertyInspector::PropertyGroup::%s::%s", m_materialAssetId.ToString().c_str(), - groupDisplayName.c_str())); + groupNameId.c_str())); auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( &group, &group, group.TYPEINFO_Uuid(), this, this, saveStateKey, [this](const AzToolsFramework::InstanceDataNode* source, const AzToolsFramework::InstanceDataNode* target) { @@ -268,7 +268,7 @@ namespace AZ // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties const AZ::Crc32 saveStateKey(AZStd::string::format( "MaterialPropertyInspector::PropertyGroup::%s::%s", m_materialAssetId.ToString().c_str(), - groupDisplayName.c_str())); + groupNameId.c_str())); auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( &group, &group, group.TYPEINFO_Uuid(), this, this, saveStateKey, [this](const AzToolsFramework::InstanceDataNode* source, const AzToolsFramework::InstanceDataNode* target) { From 1e860e7c82cb60948cc0b865314c183148a19d8c Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Sat, 8 May 2021 19:56:40 -0700 Subject: [PATCH 014/100] Change BindlessPrototype to use an unbounded array --- .../ShaderResourceGroups/BindlessPrototypeSrg.azsli | 7 +++---- .../Atom/RPI.Public/Shader/ShaderResourceGroup.h | 3 +++ .../Source/RPI.Public/Shader/ShaderResourceGroup.cpp | 10 ++++++++++ 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/Gems/Atom/RPI/Assets/ShaderLib/Atom/RPI/ShaderResourceGroups/BindlessPrototypeSrg.azsli b/Gems/Atom/RPI/Assets/ShaderLib/Atom/RPI/ShaderResourceGroups/BindlessPrototypeSrg.azsli index c955c5d2f8..7304af9e1e 100644 --- a/Gems/Atom/RPI/Assets/ShaderLib/Atom/RPI/ShaderResourceGroups/BindlessPrototypeSrg.azsli +++ b/Gems/Atom/RPI/Assets/ShaderLib/Atom/RPI/ShaderResourceGroups/BindlessPrototypeSrg.azsli @@ -31,10 +31,6 @@ ShaderResourceGroupSemantic FloatBufferSemanticId ShaderResourceGroup ImageSrg : FrequencyPerScene { - // Array of textures - // NOTE: The size of the texture array has to match the number of textures in the example - Texture2D m_textureArray[8]; - Sampler m_sampler { MaxAnisotropy = 16; @@ -42,6 +38,9 @@ ShaderResourceGroup ImageSrg : FrequencyPerScene AddressV = Wrap; AddressW = Wrap; }; + + // Array of textures + Texture2D m_textureArray[]; } ShaderResourceGroup FloatBufferSrg : FloatBufferSemanticId diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Shader/ShaderResourceGroup.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Shader/ShaderResourceGroup.h index 8c53ed2eb2..6d99d287f3 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Shader/ShaderResourceGroup.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Shader/ShaderResourceGroup.h @@ -75,6 +75,9 @@ namespace AZ RHI::ShaderInputSamplerIndex FindShaderInputSamplerIndex(const Name& name) const; RHI::ShaderInputConstantIndex FindShaderInputConstantIndex(const Name& name) const; + RHI::ShaderInputBufferUnboundedArrayIndex FindShaderInputBufferUnboundedArrayIndex(const Name& name) const; + RHI::ShaderInputImageUnboundedArrayIndex FindShaderInputImageUnboundedArrayIndex(const Name& name) const; + /// Returns the parent shader resource group asset. const Data::Asset& GetAsset() const; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/ShaderResourceGroup.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/ShaderResourceGroup.cpp index 28ba48c370..77ea0b9494 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/ShaderResourceGroup.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/ShaderResourceGroup.cpp @@ -118,6 +118,16 @@ namespace AZ return m_layout->FindShaderInputConstantIndex(name); } + RHI::ShaderInputBufferUnboundedArrayIndex ShaderResourceGroup::FindShaderInputBufferUnboundedArrayIndex(const Name& name) const + { + return m_layout->FindShaderInputBufferUnboundedArrayIndex(name); + } + + RHI::ShaderInputImageUnboundedArrayIndex ShaderResourceGroup::FindShaderInputImageUnboundedArrayIndex(const Name& name) const + { + return m_layout->FindShaderInputImageUnboundedArrayIndex(name); + } + const Data::Asset& ShaderResourceGroup::GetAsset() const { return m_asset; From 543784339045b2b8b1ea53fe7312c8cdfd0e0dab Mon Sep 17 00:00:00 2001 From: guthadam Date: Sun, 9 May 2021 12:34:55 -0500 Subject: [PATCH 015/100] Created material editor settings dialog Activated settings menu option Moved viewport camera controller initialization before viewport settings restoration --- .../Atom/Document/MaterialDocumentSettings.h | 1 + .../Document/MaterialDocumentSettings.cpp | 3 + .../Viewport/MaterialViewportRenderer.cpp | 4 +- .../CreateMaterialDialog.cpp | 9 ++- .../Source/Window/MaterialEditorWindow.cpp | 13 ++-- .../Code/Source/Window/MaterialEditorWindow.h | 2 +- .../Window/SettingsDialog/SettingsDialog.cpp | 43 +++++++++++ .../Window/SettingsDialog/SettingsDialog.h | 27 +++++++ .../Window/SettingsDialog/SettingsWidget.cpp | 72 +++++++++++++++++++ .../Window/SettingsDialog/SettingsWidget.h | 54 ++++++++++++++ .../ViewportSettingsInspector.cpp | 6 +- .../ViewportSettingsInspector.h | 2 +- .../Code/materialeditorwindow_files.cmake | 4 ++ 13 files changed, 226 insertions(+), 14 deletions(-) create mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsDialog.cpp create mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsDialog.h create mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsWidget.cpp create mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsWidget.h diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSettings.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSettings.h index 37d6a8c2d8..86c913d271 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSettings.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Document/MaterialDocumentSettings.h @@ -30,5 +30,6 @@ namespace MaterialEditor static void Reflect(AZ::ReflectContext* context); bool m_showReloadDocumentPrompt = true; + AZStd::string m_defaultMaterialTypeName = "StandardPBR"; }; } // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSettings.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSettings.cpp index a64b6584c1..0dab7ea9f6 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSettings.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSettings.cpp @@ -23,6 +23,7 @@ namespace MaterialEditor serializeContext->Class() ->Version(1) ->Field("showReloadDocumentPrompt", &MaterialDocumentSettings::m_showReloadDocumentPrompt) + ->Field("defaultMaterialTypeName", &MaterialDocumentSettings::m_defaultMaterialTypeName) ; if (auto editContext = serializeContext->GetEditContext()) @@ -32,6 +33,7 @@ namespace MaterialEditor ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialDocumentSettings::m_showReloadDocumentPrompt, "Show Reload Document Prompt", "") + ->DataElement(AZ::Edit::UIHandlers::Default, &MaterialDocumentSettings::m_defaultMaterialTypeName, "Default Material Type Name", "") ; } } @@ -45,6 +47,7 @@ namespace MaterialEditor ->Constructor() ->Constructor() ->Property("showReloadDocumentPrompt", BehaviorValueProperty(&MaterialDocumentSettings::m_showReloadDocumentPrompt)) + ->Property("defaultMaterialTypeName", BehaviorValueProperty(&MaterialDocumentSettings::m_defaultMaterialTypeName)) ; } } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportRenderer.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportRenderer.cpp index f009cc1f9b..c7265e0039 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportRenderer.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportRenderer.cpp @@ -233,6 +233,8 @@ namespace MaterialEditor MaterialViewportRequestBus::BroadcastResult(modelPreset, &MaterialViewportRequestBus::Events::GetModelPresetSelection); OnModelPresetSelected(modelPreset); + m_viewportController->Init(m_cameraEntity->GetId(), m_modelEntity->GetId(), m_iblEntity->GetId()); + // Apply user settinngs restored since last run AZStd::intrusive_ptr viewportSettings = AZ::UserSettings::CreateFind(AZ::Crc32("MaterialViewportSettings"), AZ::UserSettings::CT_GLOBAL); @@ -248,8 +250,6 @@ namespace MaterialEditor AZ::TickBus::Handler::BusConnect(); AZ::TransformNotificationBus::MultiHandler::BusConnect(m_cameraEntity->GetId()); AzFramework::WindowSystemRequestBus::Handler::BusConnect(); - - m_viewportController->Init(m_cameraEntity->GetId(), m_modelEntity->GetId(), m_iblEntity->GetId()); } MaterialViewportRenderer::~MaterialViewportRenderer() diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/CreateMaterialDialog/CreateMaterialDialog.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/CreateMaterialDialog/CreateMaterialDialog.cpp index 6c30540392..6a4bb8c0f4 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/CreateMaterialDialog/CreateMaterialDialog.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/CreateMaterialDialog/CreateMaterialDialog.cpp @@ -21,6 +21,8 @@ #include #include +#include + #include namespace MaterialEditor @@ -69,8 +71,11 @@ namespace MaterialEditor QObject::connect(m_ui->m_materialTypeComboBox, static_cast(&QComboBox::currentIndexChanged), this, [this]() { UpdateMaterialTypeSelection(); }); QObject::connect(m_ui->m_materialTypeComboBox, &QComboBox::currentTextChanged, this, [this]() { UpdateMaterialTypeSelection(); }); - // Select StandardPBR by default but we will later data drive this with editor settings - const int index = m_ui->m_materialTypeComboBox->findText("StandardPBR"); + // Select the default material type from settings + auto settings = + AZ::UserSettings::CreateFind(AZ::Crc32("MaterialDocumentSettings"), AZ::UserSettings::CT_GLOBAL); + + const int index = m_ui->m_materialTypeComboBox->findText(settings->m_defaultMaterialTypeName.c_str()); if (index >= 0) { m_ui->m_materialTypeComboBox->setCurrentIndex(index); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index 075a58c532..d0470c476f 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -39,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -314,7 +315,7 @@ namespace MaterialEditor m_actionUndo->setEnabled(canUndo); m_actionRedo->setEnabled(canRedo); - m_actionPreferences->setEnabled(false); + m_actionSettings->setEnabled(true); m_actionAssetBrowser->setEnabled(true); m_actionInspector->setEnabled(true); @@ -507,9 +508,11 @@ namespace MaterialEditor m_menuEdit->addSeparator(); - m_actionPreferences = m_menuEdit->addAction("&Preferences...", [this]() { + m_actionSettings = m_menuEdit->addAction("&Settings...", [this]() { + SettingsDialog dialog(this); + dialog.exec(); }, QKeySequence::Preferences); - m_actionPreferences->setEnabled(false); + m_actionSettings->setEnabled(true); m_menuView = m_menuBar->addMenu("&View"); @@ -554,8 +557,8 @@ namespace MaterialEditor m_menuHelp = m_menuBar->addMenu("&Help"); m_actionHelp = m_menuHelp->addAction("&Help...", [this]() { - HelpDialog dlg(this); - dlg.exec(); + HelpDialog dialog(this); + dialog.exec(); }); m_actionAbout = m_menuHelp->addAction("&About...", [this]() { diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h index 778e11275f..aa95e5ad8c 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h @@ -119,7 +119,7 @@ namespace MaterialEditor QMenu* m_menuEdit = {}; QAction* m_actionUndo = {}; QAction* m_actionRedo = {}; - QAction* m_actionPreferences = {}; + QAction* m_actionSettings = {}; QMenu* m_menuView = {}; QAction* m_actionAssetBrowser = {}; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsDialog.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsDialog.cpp new file mode 100644 index 0000000000..75bc78db12 --- /dev/null +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsDialog.cpp @@ -0,0 +1,43 @@ +/* + * 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 + +namespace MaterialEditor +{ + SettingsDialog::SettingsDialog(QWidget* parent) + : QDialog(parent) + { + setWindowTitle("Material Editor Settings"); + setFixedSize(600, 300); + setLayout(new QVBoxLayout(this)); + + auto settingsWidget = new SettingsWidget(this); + settingsWidget->Populate(); + layout()->addWidget(settingsWidget); + + // Create the bottom row of the dialog with action buttons + auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok, this); + layout()->addWidget(buttonBox); + + QObject::connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + QObject::connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + + setModal(true); + } +} // namespace MaterialEditor + +//#include diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsDialog.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsDialog.h new file mode 100644 index 0000000000..a5ad35c4a3 --- /dev/null +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsDialog.h @@ -0,0 +1,27 @@ +/* + * 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 MaterialEditor +{ + class SettingsDialog + : public QDialog + { + Q_OBJECT + public: + SettingsDialog(QWidget* parent = nullptr); + ~SettingsDialog() = default; + }; +} // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsWidget.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsWidget.cpp new file mode 100644 index 0000000000..2cb07b6770 --- /dev/null +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsWidget.cpp @@ -0,0 +1,72 @@ +/* +* 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 + +namespace MaterialEditor +{ + SettingsWidget::SettingsWidget(QWidget* parent) + : AtomToolsFramework::InspectorWidget(parent) + { + m_documentSettings = + AZ::UserSettings::CreateFind(AZ::Crc32("MaterialDocumentSettings"), AZ::UserSettings::CT_GLOBAL); + } + + SettingsWidget::~SettingsWidget() + { + AtomToolsFramework::InspectorRequestBus::Handler::BusDisconnect(); + } + + void SettingsWidget::Populate() + { + AddGroupsBegin(); + AddDocumentGroup(); + AddGroupsEnd(); + } + + void SettingsWidget::AddDocumentGroup() + { + const AZStd::string groupNameId = "documentSettings"; + const AZStd::string groupDisplayName = "Document Settings"; + const AZStd::string groupDescription = "Document Settings"; + + const AZ::Crc32 saveStateKey(AZStd::string::format("SettingsWidget::DocumentGroup")); + AddGroup( + groupNameId, groupDisplayName, groupDescription, + new AtomToolsFramework::InspectorPropertyGroupWidget( + m_documentSettings.get(), nullptr, m_documentSettings->TYPEINFO_Uuid(), this, this, saveStateKey)); + } + + void SettingsWidget::Reset() + { + AtomToolsFramework::InspectorRequestBus::Handler::BusDisconnect(); + AtomToolsFramework::InspectorWidget::Reset(); + } + + void SettingsWidget::BeforePropertyModified(AzToolsFramework::InstanceDataNode* pNode) + { + AZ_UNUSED(pNode); + } + + void SettingsWidget::AfterPropertyModified(AzToolsFramework::InstanceDataNode* pNode) + { + AZ_UNUSED(pNode); + } + + void SettingsWidget::SetPropertyEditingComplete(AzToolsFramework::InstanceDataNode* pNode) + { + AZ_UNUSED(pNode); + } +} // namespace MaterialEditor + +//#include diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsWidget.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsWidget.h new file mode 100644 index 0000000000..33d831f3d1 --- /dev/null +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/SettingsDialog/SettingsWidget.h @@ -0,0 +1,54 @@ +/* +* 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 +#endif + +namespace MaterialEditor +{ + //! Provides controls for viewing and editing settings. + class SettingsWidget + : public AtomToolsFramework::InspectorWidget + , private AzToolsFramework::IPropertyEditorNotify + { + Q_OBJECT + public: + AZ_CLASS_ALLOCATOR(SettingsWidget, AZ::SystemAllocator, 0); + + explicit SettingsWidget(QWidget* parent = nullptr); + ~SettingsWidget() override; + + void Populate(); + + private: + void AddDocumentGroup(); + + // AtomToolsFramework::InspectorRequestBus::Handler overrides... + void Reset() override; + + // AzToolsFramework::IPropertyEditorNotify overrides... + void BeforePropertyModified(AzToolsFramework::InstanceDataNode* pNode) override; + void AfterPropertyModified(AzToolsFramework::InstanceDataNode* pNode) override; + void SetPropertyEditingActive([[maybe_unused]] AzToolsFramework::InstanceDataNode* pNode) override {} + void SetPropertyEditingComplete(AzToolsFramework::InstanceDataNode* pNode) override; + void SealUndoStack() override {} + void RequestPropertyContextMenu(AzToolsFramework::InstanceDataNode*, const QPoint&) override {} + void PropertySelectionChanged(AzToolsFramework::InstanceDataNode*, bool) override {} + + AZStd::intrusive_ptr m_documentSettings; + }; +} // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.cpp index 384644f79c..49bd31ee31 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.cpp @@ -43,7 +43,7 @@ namespace MaterialEditor AtomToolsFramework::InspectorRequestBus::Handler::BusDisconnect(); } - void ViewportSettingsInspector::Popuate() + void ViewportSettingsInspector::Populate() { AddGroupsBegin(); AddGeneralGroup(); @@ -271,7 +271,7 @@ namespace MaterialEditor { if (m_lightingPreset != preset) { - Popuate(); + Populate(); } } @@ -279,7 +279,7 @@ namespace MaterialEditor { if (m_modelPreset != preset) { - Popuate(); + Populate(); } } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.h index fdfdec1458..ac9927e069 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.h @@ -39,7 +39,7 @@ namespace MaterialEditor ~ViewportSettingsInspector() override; private: - void Popuate(); + void Populate(); void AddGeneralGroup(); void AddModelGroup(); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake b/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake index 52022e6e87..7a1aa8c735 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake +++ b/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake @@ -28,6 +28,10 @@ set(FILES Source/Window/MaterialEditor.qss Source/Window/MaterialEditorWindowComponent.h Source/Window/MaterialEditorWindowComponent.cpp + Source/Window/SettingsDialog/SettingsDialog.cpp + Source/Window/SettingsDialog/SettingsDialog.h + Source/Window/SettingsDialog/SettingsWidget.cpp + Source/Window/SettingsDialog/SettingsWidget.h Source/Window/CreateMaterialDialog/CreateMaterialDialog.cpp Source/Window/CreateMaterialDialog/CreateMaterialDialog.h Source/Window/CreateMaterialDialog/CreateMaterialDialog.ui From 9725c9beab757fbaeea629257b16ff24b10290f0 Mon Sep 17 00:00:00 2001 From: guthadam Date: Mon, 10 May 2021 12:05:15 -0500 Subject: [PATCH 016/100] Recording/restoring viewport settings group expansion --- .../MaterialInspector/MaterialInspector.cpp | 75 +++++++++------ .../MaterialInspector/MaterialInspector.h | 1 + .../ViewportSettingsInspector.cpp | 94 ++++++++++++------- .../ViewportSettingsInspector.h | 9 +- 4 files changed, 113 insertions(+), 66 deletions(-) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp index 2c334ad3b7..55e098962a 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp @@ -1,14 +1,14 @@ /* -* 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. -* -*/ + * 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 @@ -21,7 +21,6 @@ #include #include -#include #include namespace MaterialEditor @@ -95,8 +94,7 @@ namespace MaterialEditor AZ::Crc32 MaterialInspector::GetGroupSaveStateKey(const AZStd::string& groupNameId) const { - return AZ::Crc32( - AZStd::string::format("MaterialInspector::PropertyGroup::%s::%s", m_documentPath.c_str(), groupNameId.c_str())); + return AZ::Crc32(AZStd::string::format("MaterialInspector::PropertyGroup::%s::%s", m_documentPath.c_str(), groupNameId.c_str())); } bool MaterialInspector::CompareInstanceNodeProperties( @@ -110,7 +108,8 @@ namespace MaterialEditor void MaterialInspector::AddDetailsGroup() { const AZ::RPI::MaterialTypeSourceData* materialTypeSourceData = nullptr; - MaterialDocumentRequestBus::EventResult(materialTypeSourceData, m_documentId, &MaterialDocumentRequestBus::Events::GetMaterialTypeSourceData); + MaterialDocumentRequestBus::EventResult( + materialTypeSourceData, m_documentId, &MaterialDocumentRequestBus::Events::GetMaterialTypeSourceData); const AZStd::string groupNameId = "details"; const AZStd::string groupDisplayName = "Details"; @@ -118,11 +117,13 @@ namespace MaterialEditor auto& group = m_groups[groupNameId]; AtomToolsFramework::DynamicProperty property; - MaterialDocumentRequestBus::EventResult(property, m_documentId, &MaterialDocumentRequestBus::Events::GetProperty, AZ::Name("details.materialType")); + MaterialDocumentRequestBus::EventResult( + property, m_documentId, &MaterialDocumentRequestBus::Events::GetProperty, AZ::Name("details.materialType")); group.m_properties.push_back(property); property = {}; - MaterialDocumentRequestBus::EventResult(property, m_documentId, &MaterialDocumentRequestBus::Events::GetProperty, AZ::Name("details.parentMaterial")); + MaterialDocumentRequestBus::EventResult( + property, m_documentId, &MaterialDocumentRequestBus::Events::GetProperty, AZ::Name("details.parentMaterial")); group.m_properties.push_back(property); // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties @@ -148,7 +149,9 @@ namespace MaterialEditor for (const auto& uvNamePair : uvNameMap) { AtomToolsFramework::DynamicProperty property; - MaterialDocumentRequestBus::EventResult(property, m_documentId, &MaterialDocumentRequestBus::Events::GetProperty, AZ::RPI::MaterialPropertyId(groupNameId, uvNamePair.m_shaderInput.ToString()).GetFullName()); + MaterialDocumentRequestBus::EventResult( + property, m_documentId, &MaterialDocumentRequestBus::Events::GetProperty, + AZ::RPI::MaterialPropertyId(groupNameId, uvNamePair.m_shaderInput.ToString()).GetFullName()); group.m_properties.push_back(property); property.SetValue(property.GetConfig().m_parentValue); @@ -164,13 +167,15 @@ namespace MaterialEditor void MaterialInspector::AddPropertiesGroup() { const AZ::RPI::MaterialTypeSourceData* materialTypeSourceData = nullptr; - MaterialDocumentRequestBus::EventResult(materialTypeSourceData, m_documentId, &MaterialDocumentRequestBus::Events::GetMaterialTypeSourceData); + MaterialDocumentRequestBus::EventResult( + materialTypeSourceData, m_documentId, &MaterialDocumentRequestBus::Events::GetMaterialTypeSourceData); for (const auto& groupDefinition : materialTypeSourceData->GetGroupDefinitionsInDisplayOrder()) { const AZStd::string& groupNameId = groupDefinition.m_nameId; const AZStd::string& groupDisplayName = !groupDefinition.m_displayName.empty() ? groupDefinition.m_displayName : groupNameId; - const AZStd::string& groupDescription = !groupDefinition.m_description.empty() ? groupDefinition.m_description : groupDisplayName; + const AZStd::string& groupDescription = + !groupDefinition.m_description.empty() ? groupDefinition.m_description : groupDisplayName; auto& group = m_groups[groupNameId]; const auto& propertyLayout = materialTypeSourceData->m_propertyLayout; @@ -181,7 +186,9 @@ namespace MaterialEditor for (const auto& propertyDefinition : propertyListItr->second) { AtomToolsFramework::DynamicProperty property; - MaterialDocumentRequestBus::EventResult(property, m_documentId, &MaterialDocumentRequestBus::Events::GetProperty, AZ::RPI::MaterialPropertyId(groupNameId, propertyDefinition.m_nameId).GetFullName()); + MaterialDocumentRequestBus::EventResult( + property, m_documentId, &MaterialDocumentRequestBus::Events::GetProperty, + AZ::RPI::MaterialPropertyId(groupNameId, propertyDefinition.m_nameId).GetFullName()); group.m_properties.push_back(property); } } @@ -205,7 +212,8 @@ namespace MaterialEditor if (!AtomToolsFramework::ArePropertyValuesEqual(reflectedProperty.GetValue(), property.GetValue())) { reflectedProperty.SetValue(property.GetValue()); - AtomToolsFramework::InspectorRequestBus::Event(documentId, &AtomToolsFramework::InspectorRequestBus::Events::RefreshGroup, groupPair.first); + AtomToolsFramework::InspectorRequestBus::Event( + documentId, &AtomToolsFramework::InspectorRequestBus::Events::RefreshGroup, groupPair.first); } return; } @@ -213,7 +221,8 @@ namespace MaterialEditor } } - void MaterialInspector::OnDocumentPropertyConfigModified(const AZ::Uuid& documentId, const AtomToolsFramework::DynamicProperty& property) + void MaterialInspector::OnDocumentPropertyConfigModified( + const AZ::Uuid& documentId, const AtomToolsFramework::DynamicProperty& property) { for (auto& groupPair : m_groups) { @@ -225,12 +234,14 @@ namespace MaterialEditor if (reflectedProperty.GetVisibility() != property.GetVisibility()) { reflectedProperty.SetConfig(property.GetConfig()); - AtomToolsFramework::InspectorRequestBus::Event(documentId, &AtomToolsFramework::InspectorRequestBus::Events::RebuildGroup, groupPair.first); + AtomToolsFramework::InspectorRequestBus::Event( + documentId, &AtomToolsFramework::InspectorRequestBus::Events::RebuildGroup, groupPair.first); } else { reflectedProperty.SetConfig(property.GetConfig()); - AtomToolsFramework::InspectorRequestBus::Event(documentId, &AtomToolsFramework::InspectorRequestBus::Events::RefreshGroup, groupPair.first); + AtomToolsFramework::InspectorRequestBus::Event( + documentId, &AtomToolsFramework::InspectorRequestBus::Events::RefreshGroup, groupPair.first); } return; } @@ -242,7 +253,8 @@ namespace MaterialEditor { // For some reason the reflected property editor notifications are not symmetrical // This function is called continuously anytime a property changes until the edit has completed - // Because of that, we have to track whether or not we are continuing to edit the same property to know when editing has started and ended + // Because of that, we have to track whether or not we are continuing to edit the same property to know when editing has started and + // ended const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(pNode); if (property) { @@ -261,23 +273,24 @@ namespace MaterialEditor { if (m_activeProperty == property) { - MaterialDocumentRequestBus::Event(m_documentId, &MaterialDocumentRequestBus::Events::SetPropertyValue, - property->GetId(), property->GetValue()); + MaterialDocumentRequestBus::Event( + m_documentId, &MaterialDocumentRequestBus::Events::SetPropertyValue, property->GetId(), property->GetValue()); } } } void MaterialInspector::SetPropertyEditingComplete(AzToolsFramework::InstanceDataNode* pNode) { - // As above, there are symmetrical functions on the notification interface for when editing begins and ends and has been completed but they are not being called following that pattern. - // when this function executes the changes to the property are ready to be committed or reverted + // As above, there are symmetrical functions on the notification interface for when editing begins and ends and has been completed + // but they are not being called following that pattern. when this function executes the changes to the property are ready to be + // committed or reverted const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(pNode); if (property) { if (m_activeProperty == property) { - MaterialDocumentRequestBus::Event(m_documentId, &MaterialDocumentRequestBus::Events::SetPropertyValue, - property->GetId(), property->GetValue()); + MaterialDocumentRequestBus::Event( + m_documentId, &MaterialDocumentRequestBus::Events::SetPropertyValue, property->GetId(), property->GetValue()); MaterialDocumentRequestBus::Event(m_documentId, &MaterialDocumentRequestBus::Events::EndEdit); m_activeProperty = nullptr; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h index b2900b979c..f53e93a2f9 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h @@ -20,6 +20,7 @@ #include #include +#include #endif namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.cpp index 49bd31ee31..ebce4849e0 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.cpp @@ -1,27 +1,27 @@ /* -* 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. -* -*/ + * 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 namespace MaterialEditor @@ -32,6 +32,9 @@ namespace MaterialEditor m_viewportSettings = AZ::UserSettings::CreateFind(AZ::Crc32("MaterialViewportSettings"), AZ::UserSettings::CT_GLOBAL); + m_windowSettings = AZ::UserSettings::CreateFind( + AZ::Crc32("MaterialEditorWindowSettings"), AZ::UserSettings::CT_GLOBAL); + MaterialViewportNotificationBus::Handler::BusConnect(); } @@ -54,22 +57,21 @@ namespace MaterialEditor void ViewportSettingsInspector::AddGeneralGroup() { - const AZStd::string groupNameId = "general"; - const AZStd::string groupDisplayName = "General"; - const AZStd::string groupDescription = "General"; + const AZStd::string groupNameId = "generalSettings"; + const AZStd::string groupDisplayName = "General Settings"; + const AZStd::string groupDescription = "General Settings"; - const AZ::Crc32 saveStateKey(AZStd::string::format("ViewportSettingsInspector::GeneralGroup")); AddGroup( groupNameId, groupDisplayName, groupDescription, new AtomToolsFramework::InspectorPropertyGroupWidget( - m_viewportSettings.get(), nullptr, m_viewportSettings->TYPEINFO_Uuid(), this, this, saveStateKey)); + m_viewportSettings.get(), nullptr, m_viewportSettings->TYPEINFO_Uuid(), this, this, GetGroupSaveStateKey(groupNameId))); } void ViewportSettingsInspector::AddModelGroup() { - const AZStd::string groupNameId = "model"; - const AZStd::string groupDisplayName = "Model"; - const AZStd::string groupDescription = "Model"; + const AZStd::string groupNameId = "modelSettings"; + const AZStd::string groupDisplayName = "Model Settings"; + const AZStd::string groupDescription = "Model Settings"; auto groupWidget = new QWidget(this); auto buttonGroupWidget = new QWidget(groupWidget); @@ -94,9 +96,8 @@ namespace MaterialEditor if (m_modelPreset) { - const AZ::Crc32 saveStateKey(AZStd::string::format("ViewportSettingsInspector::ModelGroup")); auto inspectorWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( - m_modelPreset.get(), nullptr, m_modelPreset.get()->TYPEINFO_Uuid(), this, groupWidget, saveStateKey); + m_modelPreset.get(), nullptr, m_modelPreset.get()->TYPEINFO_Uuid(), this, groupWidget, GetGroupSaveStateKey(groupNameId)); groupWidget->layout()->addWidget(inspectorWidget); } @@ -155,9 +156,9 @@ namespace MaterialEditor void ViewportSettingsInspector::AddLightingGroup() { - const AZStd::string groupNameId = "lighting"; - const AZStd::string groupDisplayName = "Lighting"; - const AZStd::string groupDescription = "Lighting"; + const AZStd::string groupNameId = "lightingSettings"; + const AZStd::string groupDisplayName = "Lighting Settings"; + const AZStd::string groupDescription = "Lighting Settings"; auto groupWidget = new QWidget(this); auto buttonGroupWidget = new QWidget(groupWidget); @@ -182,9 +183,9 @@ namespace MaterialEditor if (m_lightingPreset) { - const AZ::Crc32 saveStateKey(AZStd::string::format("ViewportSettingsInspector::LightingGroup")); auto inspectorWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( - m_lightingPreset.get(), nullptr, m_lightingPreset.get()->TYPEINFO_Uuid(), this, groupWidget, saveStateKey); + m_lightingPreset.get(), nullptr, m_lightingPreset.get()->TYPEINFO_Uuid(), this, groupWidget, + GetGroupSaveStateKey(groupNameId)); groupWidget->layout()->addWidget(inspectorWidget); } @@ -202,8 +203,7 @@ namespace MaterialEditor AZ::Render::LightingPresetPtr preset; MaterialViewportRequestBus::BroadcastResult( preset, &MaterialViewportRequestBus::Events::AddLightingPreset, AZ::Render::LightingPreset()); - MaterialViewportRequestBus::Broadcast( - &MaterialViewportRequestBus::Events::SaveLightingPreset, preset, savePath); + MaterialViewportRequestBus::Broadcast(&MaterialViewportRequestBus::Events::SaveLightingPreset, preset, savePath); MaterialViewportRequestBus::Broadcast(&MaterialViewportRequestBus::Events::SelectLightingPreset, preset); } } @@ -227,7 +227,8 @@ namespace MaterialEditor MaterialViewportRequestBus::BroadcastResult(preset, &MaterialViewportRequestBus::Events::GetLightingPresetSelection); AZStd::string defaultPath; - MaterialViewportRequestBus::BroadcastResult(defaultPath, &MaterialViewportRequestBus::Events::GetLightingPresetLastSavePath, preset); + MaterialViewportRequestBus::BroadcastResult( + defaultPath, &MaterialViewportRequestBus::Events::GetLightingPresetLastSavePath, preset); if (defaultPath.empty()) { @@ -260,8 +261,10 @@ namespace MaterialEditor m_viewportSettings->m_enableShadowCatcher, &MaterialViewportRequestBus::Events::GetShadowCatcherEnabled); MaterialViewportRequestBus::BroadcastResult( m_viewportSettings->m_enableAlternateSkybox, &MaterialViewportRequestBus::Events::GetAlternateSkyboxEnabled); - MaterialViewportRequestBus::BroadcastResult(m_viewportSettings->m_fieldOfView, &MaterialViewportRequestBus::Handler::GetFieldOfView); - MaterialViewportRequestBus::BroadcastResult(m_viewportSettings->m_displayMapperOperationType, &MaterialViewportRequestBus::Handler::GetDisplayMapperOperationType); + MaterialViewportRequestBus::BroadcastResult( + m_viewportSettings->m_fieldOfView, &MaterialViewportRequestBus::Handler::GetFieldOfView); + MaterialViewportRequestBus::BroadcastResult( + m_viewportSettings->m_displayMapperOperationType, &MaterialViewportRequestBus::Handler::GetDisplayMapperOperationType); AtomToolsFramework::InspectorRequestBus::Handler::BusDisconnect(); AtomToolsFramework::InspectorWidget::Reset(); @@ -340,7 +343,8 @@ namespace MaterialEditor MaterialViewportRequestBus::Broadcast( &MaterialViewportRequestBus::Events::SetAlternateSkyboxEnabled, m_viewportSettings->m_enableAlternateSkybox); MaterialViewportRequestBus::Broadcast(&MaterialViewportRequestBus::Handler::SetFieldOfView, m_viewportSettings->m_fieldOfView); - MaterialViewportRequestBus::Broadcast(&MaterialViewportRequestBus::Handler::SetDisplayMapperOperationType, m_viewportSettings->m_displayMapperOperationType); + MaterialViewportRequestBus::Broadcast( + &MaterialViewportRequestBus::Handler::SetDisplayMapperOperationType, m_viewportSettings->m_displayMapperOperationType); } AZStd::string ViewportSettingsInspector::GetDefaultUniqueSaveFilePath(const AZStd::string& baseName) const @@ -353,6 +357,28 @@ namespace MaterialEditor savePath = AtomToolsFramework::GetUniqueFileInfo(savePath.c_str()).absoluteFilePath().toUtf8().constData(); return savePath; } + + AZ::Crc32 ViewportSettingsInspector::GetGroupSaveStateKey(const AZStd::string& groupNameId) const + { + return AZ::Crc32(AZStd::string::format("ViewportSettingsInspector::PropertyGroup::%s", groupNameId.c_str())); + } + + bool ViewportSettingsInspector::ShouldGroupAutoExpanded(const AZStd::string& groupNameId) const + { + auto stateItr = m_windowSettings->m_inspectorCollapsedGroups.find(GetGroupSaveStateKey(groupNameId)); + return stateItr == m_windowSettings->m_inspectorCollapsedGroups.end(); + } + + void ViewportSettingsInspector::OnGroupExpanded(const AZStd::string& groupNameId) + { + m_windowSettings->m_inspectorCollapsedGroups.erase(GetGroupSaveStateKey(groupNameId)); + } + + void ViewportSettingsInspector::OnGroupCollapsed(const AZStd::string& groupNameId) + { + m_windowSettings->m_inspectorCollapsedGroups.insert(GetGroupSaveStateKey(groupNameId)); + } + } // namespace MaterialEditor #include diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.h index ac9927e069..23bad988f0 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.h @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #endif @@ -78,8 +79,14 @@ namespace MaterialEditor AZStd::string GetDefaultUniqueSaveFilePath(const AZStd::string& baseName) const; - AZStd::intrusive_ptr m_viewportSettings; + AZ::Crc32 GetGroupSaveStateKey(const AZStd::string& groupNameId) const; + bool ShouldGroupAutoExpanded(const AZStd::string& groupNameId) const override; + void OnGroupExpanded(const AZStd::string& groupNameId) override; + void OnGroupCollapsed(const AZStd::string& groupNameId) override; + AZ::Render::ModelPresetPtr m_modelPreset; AZ::Render::LightingPresetPtr m_lightingPreset; + AZStd::intrusive_ptr m_viewportSettings; + AZStd::intrusive_ptr m_windowSettings; }; } // namespace MaterialEditor From 0da6e450a68ad2a20a8962a42ed52a58f34d2885 Mon Sep 17 00:00:00 2001 From: srikappa Date: Mon, 10 May 2021 11:43:32 -0700 Subject: [PATCH 017/100] Improved comments --- .../PrefabEditorEntityOwnershipService.cpp | 10 ------- .../Instance/InstanceToTemplatePropagator.cpp | 13 ++++----- .../AzToolsFramework/Prefab/Link/Link.cpp | 3 --- .../Prefab/PrefabPublicHandler.cpp | 27 +++++++++---------- .../Prefab/PrefabPublicHandler.h | 1 + 5 files changed, 19 insertions(+), 35 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp index 58aa245397..59e50fdf65 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp @@ -281,16 +281,6 @@ namespace AzToolsFramework containerEntity->AddComponent(aznew Prefab::EditorPrefabComponent()); HandleEntitiesAdded({containerEntity}); HandleEntitiesAdded(entities); - - /* - // Update the template of the instance since we modified the entities of the instance by calling HandleEntitiesAdded. - Prefab::PrefabDom serializedInstance; - if (Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(addedInstance, serializedInstance)) - { - m_prefabSystemComponent->UpdatePrefabTemplate(addedInstance.GetTemplateId(), serializedInstance); - } - */ - return addedInstance; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp index d298e1e2b2..6f812df89b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp @@ -176,15 +176,10 @@ namespace AzToolsFramework { PrefabDom& templateDomReference = m_prefabSystemComponentInterface->FindTemplateDom(templateId); - PrefabDomUtils::PrintPrefabDomValue("patch is ", providedPatch); - PrefabDomUtils::PrintPrefabDomValue("template dom before is ", templateDomReference); - //apply patch to template AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::ApplyPatch(templateDomReference, templateDomReference.GetAllocator(), providedPatch, AZ::JsonMergeApproach::JsonPatch); - PrefabDomUtils::PrintPrefabDomValue("template dom after is ", templateDomReference); - //trigger propagation if (result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Success) { @@ -284,9 +279,11 @@ namespace AzToolsFramework // This logic only covers addition of patches. If patches already exists, the given list of patches must be appended to them. if (!linkPatchesReference.has_value()) { - // If the original allocator the patches were created with gets destroyed, then the patches would become garbage in the - // linkDom. Since we cannot guarantee the lifecycle of the patch allocators, we are doing a copy of the patches here to - // associate them with the linkDom's allocator. This is a limitation with rapidjson. + /* + If the original allocator the patches were created with gets destroyed, then the patches would become garbage in the + linkDom. Since we cannot guarantee the lifecycle of the patch allocators, we are doing a copy of the patches here to + associate them with the linkDom's allocator. This is a limitation with rapidjson. + */ PrefabDom patchesCopy; patchesCopy.CopyFrom(patches, linkDom.GetAllocator()); linkDom.AddMember(rapidjson::StringRef(PrefabDomUtils::PatchesName), patchesCopy, linkDom.GetAllocator()); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp index e421e55a11..e0834ed53b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp @@ -181,8 +181,6 @@ namespace AzToolsFramework } else { - PrefabDomUtils::PrintPrefabDomValue("Patches are : ", m_linkDom); - PrefabDomUtils::PrintPrefabDomValue("Linked instance dom before is : ", linkedInstanceDom); AZ::JsonSerializationResult::ResultCode applyPatchResult = AZ::JsonSerialization::ApplyPatch( linkedInstanceDom, targetTemplatePrefabDom.GetAllocator(), @@ -195,7 +193,6 @@ namespace AzToolsFramework "Link::UpdateTarget - " "ApplyPatches failed for Prefab DOM from source Template '%u' and target Template '%u'.", m_sourceTemplateId, m_targetTemplateId); - PrefabDomUtils::PrintPrefabDomValue("Linked instance dom after is : ", linkedInstanceDom); return false; } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 80e1b558e7..9959ae18fa 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -122,18 +122,14 @@ namespace AzToolsFramework AZ::EntityId containerEntityId = instanceToCreate->get().GetContainerEntityId(); - // Change top level entities to be parented to the container entity - // Mark them as dirty so this change is correctly applied to the template + // Parent the entities to the container entity. Parenting the container entities of the instances passed to createPrefab + // will be done during the creation of links below. for (AZ::Entity* topLevelEntity : entities) { - //m_prefabUndoCache.UpdateCache(topLevelEntity->GetId()); - // undoBatch.MarkEntityDirty(topLevelEntity->GetId()); AZ::TransformBus::Event(topLevelEntity->GetId(), &AZ::TransformBus::Events::SetParent, containerEntityId); - //ToolsApplicationRequests::Bus::Broadcast( - // &ToolsApplicationRequests::Bus::Events::RemoveDirtyEntity, topLevelEntity->GetId()); } - // Update the template of the instance since we modified the entities of the instance by calling HandleEntitiesAdded. + // Update the template of the instance since the entities are modified since the template creation. Prefab::PrefabDom serializedInstance; if (Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(instanceToCreate->get(), serializedInstance)) { @@ -145,27 +141,28 @@ namespace AzToolsFramework EntityOptionalReference nestedInstanceContainerEntity = nestedInstance->GetContainerEntity(); AZ_Assert( nestedInstanceContainerEntity, "Invalid container entity found for the nested instance used in prefab creation."); + + // These link creations shouldn't be undone because that would put the template in a non-usable state if a user + // chooses to instantiate the template after undoing the creation. CreateLink( {&nestedInstanceContainerEntity->get()}, *nestedInstance, instanceToCreate->get().GetTemplateId(), undoBatch.GetUndoBatch(), containerEntityId, false); }); CreateLink( - topLevelEntities, instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch(), - commonRootEntityId); + topLevelEntities, instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(), + undoBatch.GetUndoBatch(), commonRootEntityId); - // Change top level entities to be parented to the container entity - // Mark them as dirty so this change is correctly applied to the template for (AZ::Entity* topLevelEntity : topLevelEntities) { m_prefabUndoCache.UpdateCache(topLevelEntity->GetId()); - //undoBatch.MarkEntityDirty(topLevelEntity->GetId()); - //AZ::TransformBus::Event(topLevelEntity->GetId(), &AZ::TransformBus::Events::SetParent, containerEntityId); + + // Parenting entities would mark entities as dirty. But we want to unmark the top level entities as dirty because + // if we don't, the template created would be updated and cause issues with undo operation followed by instantiation. ToolsApplicationRequests::Bus::Broadcast( &ToolsApplicationRequests::Bus::Events::RemoveDirtyEntity, topLevelEntity->GetId()); } - // Select Container Entity { auto selectionUndo = aznew SelectionCommand({containerEntityId}, "Select Prefab Container Entity"); @@ -442,6 +439,8 @@ namespace AzToolsFramework PrefabDom patch; m_instanceToTemplateInterface->GeneratePatch(patch, beforeState, afterState); + PrefabDomUtils::PrintPrefabDomValue(entity->GetName(), patch); + if (patch.IsArray() && !patch.Empty() && beforeState.IsObject()) { if (IsInstanceContainerEntity(entityId) && !IsLevelInstanceContainerEntity(entityId)) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 0e15fd9a15..771f73a815 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -77,6 +77,7 @@ namespace AzToolsFramework * \param targetInstance The id of the target template. * \param undoBatch The undo batch to set as parent for this create link action. * \param commonRootEntityId The id of the entity that the source instance should be parented under. + * \param IsUndoRedoSupportNeeded The flag indicating whether the link should be created with undo/redo support or not. */ void CreateLink( const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId, From b04bfc459ff57c10ab21a4668c63586fcb67148a Mon Sep 17 00:00:00 2001 From: sconel Date: Mon, 10 May 2021 11:46:58 -0700 Subject: [PATCH 018/100] Asset Preload fix for json serialization and prefab game mode --- .../Registry/editorpreferences.setreg | 3 +- .../AzCore/AzCore/Asset/AssetCommon.h | 18 ++++---- .../AzCore/Asset/AssetJsonSerializer.cpp | 33 ++++++++++++- .../AzCore/Asset/AssetManagerComponent.cpp | 9 +++- .../AzCore/Serialization/SerializeContext.h | 2 - .../AzCore/AzCore/azcore_files.cmake | 2 + .../PrefabEditorEntityOwnershipService.cpp | 46 ++++++++++++++++++- .../Prefab/PrefabDomUtils.cpp | 45 ++++++++++++++++++ .../AzToolsFramework/Prefab/PrefabDomUtils.h | 11 +++++ .../Spawnable/PrefabCatchmentProcessor.cpp | 5 +- .../Prefab/Spawnable/ProcesedObjectStore.cpp | 10 ++++ .../Prefab/Spawnable/ProcesedObjectStore.h | 5 ++ .../Prefab/Spawnable/SpawnableUtils.cpp | 7 +-- .../Prefab/Spawnable/SpawnableUtils.h | 2 +- 14 files changed, 178 insertions(+), 20 deletions(-) diff --git a/AutomatedTesting/Registry/editorpreferences.setreg b/AutomatedTesting/Registry/editorpreferences.setreg index b338d6acad..d7afc9e0ae 100644 --- a/AutomatedTesting/Registry/editorpreferences.setreg +++ b/AutomatedTesting/Registry/editorpreferences.setreg @@ -1,7 +1,8 @@ { "Amazon": { "Preferences": { - "EnablePrefabSystem": false + "EnablePrefabSystem": true, + "EnablePrefabSystemWipFeatures": true } } } \ No newline at end of file diff --git a/Code/Framework/AzCore/AzCore/Asset/AssetCommon.h b/Code/Framework/AzCore/AzCore/Asset/AssetCommon.h index c8a245af68..c5cdbbf331 100644 --- a/Code/Framework/AzCore/AzCore/Asset/AssetCommon.h +++ b/Code/Framework/AzCore/AzCore/Asset/AssetCommon.h @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -216,16 +217,14 @@ namespace AZ /** * Setting for each reference (Asset) to control loading of referenced assets during serialization. */ - enum class AssetLoadBehavior : u8 - { - PreLoad = 0, ///< Serializer will "Pre load" dependencies, asset containers may load in parallel but will not signal AssetReady - QueueLoad = 1, ///< Serializer will queue an asynchronous load of the referenced asset and return the object to the user. User code should use the \ref AZ::Data::AssetBus to monitor for when it's ready. - NoLoad = 2, ///< Serializer will load reference information, but asset loading will be left to the user. User code should call Asset::QueueLoad and use the \ref AZ::Data::AssetBus to monitor for when it's ready. - ///< AssetContainers will skip NoLoad dependencies - + AZ_ENUM_WITH_UNDERLYING_TYPE(AssetLoadBehavior, u8, + (PreLoad, 0), ///< Serializer will "Pre load" dependencies, asset containers may load in parallel but will not signal AssetReady + (QueueLoad, 1), ///< Serializer will queue an asynchronous load of the referenced asset and return the object to the user. User code should use the \ref AZ::Data::AssetBus to monitor for when it's ready. + (NoLoad, 2), ///< Serializer will load reference information, but asset loading will be left to the user. User code should call Asset::QueueLoad and use the \ref AZ::Data::AssetBus to monitor for when it's ready. + ///< AssetContainers will skip NoLoad dependencies Count, - Default = QueueLoad, - }; + (Default, QueueLoad) + ); struct AssetFilterInfo { @@ -1222,6 +1221,7 @@ namespace AZ } // namespace ProductDependencyInfo } // namespace Data + AZ_TYPE_INFO_SPECIALIZE(Data::AssetLoadBehavior, "{DAF9ECED-FEF3-4D7A-A220-8CFD6A5E6DA1}"); AZ_TYPE_INFO_TEMPLATE_WITH_NAME(AZ::Data::Asset, "Asset", "{C891BF19-B60C-45E2-BFD0-027D15DDC939}", AZ_TYPE_INFO_CLASS); } // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp b/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp index 767dadedf8..6968b51025 100644 --- a/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp +++ b/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include #include @@ -70,6 +71,17 @@ namespace AZ } } + { + const AZ::Data::AssetLoadBehavior autoLoadBehavior = instance->GetAutoLoadBehavior(); + const AZ::Data::AssetLoadBehavior defaultAutoLoadBehavior = defaultInstance ? + defaultInstance->GetAutoLoadBehavior() : AZ::Data::AssetLoadBehavior::Default; + + result.Combine( + ContinueStoringToJsonObjectField(outputValue, "loadBehavior", + &autoLoadBehavior, &defaultAutoLoadBehavior, + azrtti_typeid(), context)); + } + { ScopedContextPath subPathHint(context, "m_assetHint"); const AZStd::string* hint = &instance->GetHint(); @@ -100,6 +112,20 @@ namespace AZ AssetId id; JSR::ResultCode result(JSR::Tasks::ReadField); + SerializedAssetTracker** assetIdTracker = + context.GetMetadata().Find(); + + { + Data::AssetLoadBehavior loadBehavior = instance->GetAutoLoadBehavior(); + + result.Combine( + ContinueLoadingFromJsonObjectField(&loadBehavior, + azrtti_typeid(), + inputValue, "loadBehavior", context)); + + instance->SetAutoLoadBehavior(loadBehavior); + } + auto it = inputValue.FindMember("assetId"); if (it != inputValue.MemberEnd()) { @@ -107,7 +133,7 @@ namespace AZ result = ContinueLoading(&id, azrtti_typeid(), it->value, context); if (!id.m_guid.IsNull()) { - *instance = AssetManager::Instance().FindOrCreateAsset(id, instance->GetType(), AssetLoadBehavior::NoLoad); + *instance = AssetManager::Instance().FindOrCreateAsset(id, instance->GetType(), instance->GetAutoLoadBehavior()); result.Combine(context.Report(result, "Successfully created Asset with id.")); @@ -142,6 +168,11 @@ namespace AZ "The asset hint is missing for Asset, so it will be left empty.")); } + if (assetIdTracker && *assetIdTracker) + { + (*assetIdTracker)->AddAsset(*instance); + } + bool success = result.GetOutcome() <= JSR::Outcomes::PartialSkip; bool defaulted = result.GetOutcome() == JSR::Outcomes::DefaultsUsed || result.GetOutcome() == JSR::Outcomes::PartialDefaults; AZStd::string_view message = diff --git a/Code/Framework/AzCore/AzCore/Asset/AssetManagerComponent.cpp b/Code/Framework/AzCore/AzCore/Asset/AssetManagerComponent.cpp index d861614309..1075c6a931 100644 --- a/Code/Framework/AzCore/AzCore/Asset/AssetManagerComponent.cpp +++ b/Code/Framework/AzCore/AzCore/Asset/AssetManagerComponent.cpp @@ -13,7 +13,7 @@ #include #include #include -#include +#include #include #include #include @@ -24,6 +24,11 @@ namespace AZ { + namespace Data + { + AZ_ENUM_DEFINE_REFLECT_UTILITIES(AssetLoadBehavior); + } + //========================================================================= // AssetDatabaseComponent // [6/25/2012] @@ -99,6 +104,8 @@ namespace AZ if (SerializeContext* serializeContext = azrtti_cast(context)) { + AZ::Data::AssetLoadBehaviorReflect(*serializeContext); + serializeContext->RegisterGenericType>(); serializeContext->Class() diff --git a/Code/Framework/AzCore/AzCore/Serialization/SerializeContext.h b/Code/Framework/AzCore/AzCore/Serialization/SerializeContext.h index e5bc76cd19..6806232337 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/SerializeContext.h +++ b/Code/Framework/AzCore/AzCore/Serialization/SerializeContext.h @@ -14,8 +14,6 @@ #include -#include - #include #include diff --git a/Code/Framework/AzCore/AzCore/azcore_files.cmake b/Code/Framework/AzCore/AzCore/azcore_files.cmake index 5357ed66a6..c6ad90200b 100644 --- a/Code/Framework/AzCore/AzCore/azcore_files.cmake +++ b/Code/Framework/AzCore/AzCore/azcore_files.cmake @@ -35,6 +35,8 @@ set(FILES Asset/AssetSerializer.h Asset/AssetTypeInfoBus.h Asset/AssetInternal/WeakAsset.h + Asset/SerializedAssetTracker.cpp + Asset/SerializedAssetTracker.h Casting/lossy_cast.h Casting/numeric_cast.h Component/Component.cpp diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp index 81233069a9..a4e9d207be 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -342,6 +343,45 @@ namespace AzToolsFramework m_validateEntitiesCallback = AZStd::move(validateEntitiesCallback); } + void LoadReferencedAssets(AZStd::vector>& referencedAssets) + { + for (AZ::Data::Asset& asset : referencedAssets) + { + if (!asset.GetId().IsValid()) + { + continue; + } + + const AZ::Data::AssetLoadBehavior loadBehavior = asset.GetAutoLoadBehavior(); + + if (loadBehavior == AZ::Data::AssetLoadBehavior::NoLoad) + { + continue; + } + + AZ::Data::AssetId assetId = asset.GetId(); + AZ::Data::AssetType assetType = asset.GetType(); + const bool blockingLoad = loadBehavior == AZ::Data::AssetLoadBehavior::PreLoad; + + asset = AZ::Data::AssetManager::Instance().GetAsset(assetId, assetType, loadBehavior); + + if (!asset.GetId().IsValid()) + { + continue; + } + + if (blockingLoad) + { + asset.BlockUntilLoadComplete(); + + if (asset.IsError()) + { + continue; + } + } + } + } + void PrefabEditorEntityOwnershipService::StartPlayInEditor() { // This is a workaround until the replacement for GameEntityContext is done @@ -381,13 +421,15 @@ namespace AzToolsFramework rootSpawnableIndex = m_playInEditorData.m_assets.size(); } + LoadReferencedAssets(product.GetReferencedAssets()); + AZ::Data::AssetInfo info; info.m_assetId = product.GetAsset().GetId(); info.m_assetType = product.GetAssetType(); info.m_relativePath = product.GetId(); AZ::Data::AssetCatalogRequestBus::Broadcast( - &AZ::Data::AssetCatalogRequestBus::Events::RegisterAsset, product.GetAsset().GetId(), info); + &AZ::Data::AssetCatalogRequestBus::Events::RegisterAsset, info.m_assetId, info); m_playInEditorData.m_assets.emplace_back(product.ReleaseAsset().release(), AZ::Data::AssetLoadBehavior::Default); } @@ -398,6 +440,8 @@ namespace AzToolsFramework m_playInEditorData.m_entities.SpawnAllEntities(); } + AZ::Data::AssetManager::Instance().DispatchEvents(); + // This is a workaround until the replacement for GameEntityContext is done AzFramework::GameEntityContextEventBus::Broadcast( &AzFramework::GameEntityContextEventBus::Events::OnGameEntitiesStarted); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp index d53aeaa241..ae1737f907 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp @@ -11,8 +11,10 @@ */ #include +#include #include #include + #include #include #include @@ -115,6 +117,49 @@ namespace AzToolsFramework return true; } + bool LoadInstanceFromPrefabDom( + Instance& instance, const PrefabDom& prefabDom, AZStd::vector>& loadedAssets, LoadInstanceFlags flags) + { + // When entities are rebuilt they are first destroyed. As a result any assets they were exclusively holding on to will + // be released and reloaded once the entities are built up again. By suspending asset release temporarily the asset reload + // is avoided. + AZ::Data::AssetManager::Instance().SuspendAssetRelease(); + + InstanceEntityIdMapper entityIdMapper; + entityIdMapper.SetLoadingInstance(instance); + if ((flags & LoadInstanceFlags::AssignRandomEntityId) == LoadInstanceFlags::AssignRandomEntityId) + { + entityIdMapper.SetEntityIdGenerationApproach(InstanceEntityIdMapper::EntityIdGenerationApproach::Random); + } + + AZ::Data::SerializedAssetTracker assetTracker; + + AZ::JsonDeserializerSettings settings; + // The InstanceEntityIdMapper is registered twice because it's used in several places during deserialization where one is + // specific for the InstanceEntityIdMapper and once for the generic JsonEntityIdMapper. Because the Json Serializer's meta + // data has strict typing and doesn't look for inheritance both have to be explicitly added so they're found both locations. + settings.m_metadata.Add(static_cast(&entityIdMapper)); + settings.m_metadata.Add(&entityIdMapper); + settings.m_metadata.Add(&assetTracker); + + AZ::JsonSerializationResult::ResultCode result = + AZ::JsonSerialization::Load(instance, prefabDom, settings); + + AZ::Data::AssetManager::Instance().ResumeAssetRelease(); + + if (result.GetProcessing() == AZ::JsonSerializationResult::Processing::Halted) + { + AZ_Error("Prefab", false, + "Failed to de-serialize Prefab Instance from Prefab DOM. " + "Unable to proceed."); + + return false; + } + + loadedAssets = assetTracker.GetTrackedAssets(); + return true; + } + bool LoadInstanceFromPrefabDom( Instance& instance, Instance::EntityList& newlyAddedEntities, const PrefabDom& prefabDom, LoadInstanceFlags flags) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h index c4b988e36f..1f000c2f70 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h @@ -13,6 +13,7 @@ #pragma once #include +#include #include #include @@ -67,6 +68,16 @@ namespace AzToolsFramework bool LoadInstanceFromPrefabDom( Instance& instance, const PrefabDom& prefabDom, LoadInstanceFlags flags = LoadInstanceFlags::None); + /** + * Loads a valid Prefab Instance from a Prefab Dom. Useful for generating Instances. + * @param instance The Instance to load. + * @param prefabDom the prefabDom that will be used to load the Instance data. + * @param shouldClearContainers whether to clear containers in Instance while loading. + * @return bool on whether the operation succeeded. + */ + bool LoadInstanceFromPrefabDom( + Instance& instance, const PrefabDom& prefabDom, AZStd::vector>& loadedAssets, LoadInstanceFlags flags = LoadInstanceFlags::None); + /** * Loads a valid Prefab Instance from a Prefab Dom. Useful for generating Instances. * @param instance The Instance to load. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp index 5d8f1f35e3..9ae795dbf1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp @@ -20,6 +20,8 @@ #include #include +#include + namespace AzToolsFramework::Prefab::PrefabConversionUtils { void PrefabCatchmentProcessor::Process(PrefabProcessorContext& context) @@ -63,7 +65,8 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils AZStd::move(uniqueName), context.GetSourceUuid(), AZStd::move(serializer)); AZ_Assert(spawnable, "Failed to create a new spawnable."); - bool result = SpawnableUtils::CreateSpawnable(*spawnable, prefab); + Prefab::PrefabDomUtils::PrintPrefabDomValue("Prefab used for spawnable", prefab); + bool result = SpawnableUtils::CreateSpawnable(*spawnable, prefab, object.GetReferencedAssets()); if (result) { AzFramework::Spawnable::EntityList& entities = spawnable->GetEntities(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/ProcesedObjectStore.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/ProcesedObjectStore.cpp index ee45c258ff..78d1332a71 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/ProcesedObjectStore.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/ProcesedObjectStore.cpp @@ -56,6 +56,16 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils return *m_asset; } + AZStd::vector>& ProcessedObjectStore::GetReferencedAssets() + { + return m_referencedAssets; + } + + const AZStd::vector>& ProcessedObjectStore::GetReferencedAssets() const + { + return m_referencedAssets; + } + AZStd::unique_ptr ProcessedObjectStore::ReleaseAsset() { return AZStd::move(m_asset); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/ProcesedObjectStore.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/ProcesedObjectStore.h index a24d1f24c5..48e0007516 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/ProcesedObjectStore.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/ProcesedObjectStore.h @@ -48,6 +48,10 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils AZ::Data::AssetData& GetAsset(); AZStd::unique_ptr ReleaseAsset(); + AZStd::vector>& GetReferencedAssets(); + const AZStd::vector>& GetReferencedAssets() const; + + const AZStd::string& GetId() const; private: @@ -55,6 +59,7 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils SerializerFunction m_assetSerializer; AZStd::unique_ptr m_asset; + AZStd::vector> m_referencedAssets; AZStd::string m_uniqueId; }; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp index 713a5d8205..085758cda9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp @@ -28,16 +28,17 @@ namespace AzToolsFramework::Prefab::SpawnableUtils AzFramework::Spawnable CreateSpawnable(const PrefabDom& prefabDom) { AzFramework::Spawnable spawnable; - [[maybe_unused]] bool result = CreateSpawnable(spawnable, prefabDom); + AZStd::vector> referencedAssets; + [[maybe_unused]] bool result = CreateSpawnable(spawnable, prefabDom, referencedAssets); AZ_Assert(result, "Failed to Load Prefab Instance from given Prefab DOM while Spawnable creation."); return spawnable; } - bool CreateSpawnable(AzFramework::Spawnable& spawnable, const PrefabDom& prefabDom) + bool CreateSpawnable(AzFramework::Spawnable& spawnable, const PrefabDom& prefabDom, AZStd::vector>& referencedAssets) { Instance instance; - if (Prefab::PrefabDomUtils::LoadInstanceFromPrefabDom(instance, prefabDom, + if (Prefab::PrefabDomUtils::LoadInstanceFromPrefabDom(instance, prefabDom, referencedAssets, Prefab::PrefabDomUtils::LoadInstanceFlags::AssignRandomEntityId)) // Always assign random entity ids because the spawnable is // going to be used to create clones of the entities. { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.h index 74cbbcb1e4..c30e5ea77a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.h @@ -18,7 +18,7 @@ namespace AzToolsFramework::Prefab::SpawnableUtils { AzFramework::Spawnable CreateSpawnable(const PrefabDom& prefabDom); - bool CreateSpawnable(AzFramework::Spawnable& spawnable, const PrefabDom& prefabDom); + bool CreateSpawnable(AzFramework::Spawnable& spawnable, const PrefabDom& prefabDom, AZStd::vector>& referencedAssets); void SortEntitiesByTransformHierarchy(AzFramework::Spawnable& spawnable); } // namespace AzToolsFramework::Prefab::SpawnableUtils From 49941036276264c3248b42cf2fdba9fe8469f386 Mon Sep 17 00:00:00 2001 From: srikappa Date: Mon, 10 May 2021 11:58:54 -0700 Subject: [PATCH 019/100] Add const ref function parameters as needed --- .../Prefab/PrefabSystemComponent.cpp | 6 +++--- .../Prefab/PrefabSystemComponent.h | 2 +- .../Prefab/PrefabSystemComponentInterface.h | 6 +++--- .../AzToolsFramework/Prefab/PrefabUndo.cpp | 14 +------------- 4 files changed, 8 insertions(+), 20 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp index 0b447ef786..985d2333bc 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp @@ -583,7 +583,7 @@ namespace AzToolsFramework const TemplateId& linkTargetId, const TemplateId& linkSourceId, const InstanceAlias& instanceAlias, - PrefabDom linkPatch, + const PrefabDomConstReference linkPatches, const LinkId& linkId) { if (linkTargetId == InvalidTemplateId) @@ -667,9 +667,9 @@ namespace AzToolsFramework rapidjson::StringRef(PrefabDomUtils::SourceName), rapidjson::StringRef(sourceTemplate.GetFilePath().c_str()), newLink.GetLinkDom().GetAllocator()); - if (linkPatch.IsArray() && !(linkPatch.Empty())) + if (linkPatches && linkPatches->get().IsArray() && !(linkPatches->get().Empty())) { - m_instanceToTemplatePropagator.AddPatchesToLink(AZStd::move(linkPatch), newLink); + m_instanceToTemplatePropagator.AddPatchesToLink(linkPatches.value(), newLink); } //update the target template dom to have the proper values for the source template dom diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h index b5f499296d..0a9a450f64 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h @@ -156,7 +156,7 @@ namespace AzToolsFramework const TemplateId& linkTargetId, const TemplateId& linkSourceId, const InstanceAlias& instanceAlias, - PrefabDom linkPatch, + const PrefabDomConstReference linkPatches, const LinkId& linkId = InvalidLinkId) override; /** diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h index 347b48a648..f47941254a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h @@ -43,9 +43,9 @@ namespace AzToolsFramework PrefabDomValue::MemberIterator& instanceIterator, InstanceOptionalReference instance) = 0; //creates a new Link - virtual LinkId CreateLink(const TemplateId& linkTargetId, const TemplateId& linkSourceId, - const InstanceAlias& instanceAlias, PrefabDom linkPatch, - const LinkId& linkId = InvalidLinkId) = 0; + virtual LinkId CreateLink( + const TemplateId& linkTargetId, const TemplateId& linkSourceId, const InstanceAlias& instanceAlias, + const PrefabDomConstReference linkPatches, const LinkId& linkId = InvalidLinkId) = 0; virtual void RemoveLink(const LinkId& linkId) = 0; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp index e82e9da90a..aadcdcdea0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp @@ -190,9 +190,7 @@ namespace AzToolsFramework void PrefabUndoInstanceLink::AddLink() { - PrefabDom linkPatchesCopy; - linkPatchesCopy.CopyFrom(m_linkPatches, linkPatchesCopy.GetAllocator()); - m_linkId = m_prefabSystemComponentInterface->CreateLink(m_targetId, m_sourceId, m_instanceAlias, AZStd::move(linkPatchesCopy), m_linkId); + m_linkId = m_prefabSystemComponentInterface->CreateLink(m_targetId, m_sourceId, m_instanceAlias, m_linkPatches, m_linkId); } void PrefabUndoInstanceLink::RemoveLink() @@ -230,9 +228,6 @@ namespace AzToolsFramework m_linkDomPrevious.CopyFrom(link->get().GetLinkDom(), m_linkDomPrevious.GetAllocator()); } - PrefabDomUtils::PrintPrefabDomValue("m_linkDomPrevious is : ", m_linkDomPrevious); - PrefabDomUtils::PrintPrefabDomValue("link->get().GetLinkDom() is : ", link->get().GetLinkDom()); - //get source templateDom TemplateReference sourceTemplate = m_prefabSystemComponentInterface->FindTemplate(link->get().GetSourceTemplateId()); @@ -305,15 +300,8 @@ namespace AzToolsFramework return; } - /* - PrefabDom moveLink; - moveLink.CopyFrom(linkDom, linkDom.GetAllocator()); - link->get().GetLinkDom() = AZStd::move(moveLink); - */ link->get().SetLinkDom(linkDom); - PrefabDomUtils::PrintPrefabDomValue("dom after updating link is : ", link->get().GetLinkDom()); - //propagate the link changes link->get().UpdateTarget(); m_prefabSystemComponentInterface->PropagateTemplateChanges(link->get().GetTargetTemplateId()); From 2e9ae76596c87ff5b3f7d2b62a4892922090a2ca Mon Sep 17 00:00:00 2001 From: sconel Date: Mon, 10 May 2021 12:11:53 -0700 Subject: [PATCH 020/100] Removed print statement, adding in new files that were missed --- .../Registry/editorpreferences.setreg | 3 +- .../AzCore/Asset/SerializedAssetTracker.cpp | 29 ++++++++++++++++ .../AzCore/Asset/SerializedAssetTracker.h | 33 +++++++++++++++++++ .../Prefab/PrefabDomUtils.cpp | 4 +-- .../AzToolsFramework/Prefab/PrefabDomUtils.h | 3 +- .../Spawnable/PrefabCatchmentProcessor.cpp | 3 -- 6 files changed, 67 insertions(+), 8 deletions(-) create mode 100644 Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.cpp create mode 100644 Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.h diff --git a/AutomatedTesting/Registry/editorpreferences.setreg b/AutomatedTesting/Registry/editorpreferences.setreg index d7afc9e0ae..b338d6acad 100644 --- a/AutomatedTesting/Registry/editorpreferences.setreg +++ b/AutomatedTesting/Registry/editorpreferences.setreg @@ -1,8 +1,7 @@ { "Amazon": { "Preferences": { - "EnablePrefabSystem": true, - "EnablePrefabSystemWipFeatures": true + "EnablePrefabSystem": false } } } \ No newline at end of file diff --git a/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.cpp b/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.cpp new file mode 100644 index 0000000000..b3fad2431f --- /dev/null +++ b/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.cpp @@ -0,0 +1,29 @@ +/* +* 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 + +namespace AZ +{ + namespace Data + { + void SerializedAssetTracker::AddAsset(Asset& asset) + { + m_serializedAssets.emplace_back(asset); + } + + const AZStd::vector>& SerializedAssetTracker::GetTrackedAssets() const + { + return m_serializedAssets; + } + } +} diff --git a/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.h b/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.h new file mode 100644 index 0000000000..e1b0af72e1 --- /dev/null +++ b/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.h @@ -0,0 +1,33 @@ +/* +* 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 +namespace AZ +{ + namespace Data + { + class SerializedAssetTracker + { + public: + AZ_RTTI(SerializedAssetTracker, "{1E067091-8C0A-44B1-A455-6E97663F6963}"); + + void AddAsset(Asset& asset); + const AZStd::vector>& GetTrackedAssets() const; + + private: + AZStd::vector> m_serializedAssets; + }; + } +} diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp index ae1737f907..9163b681de 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp @@ -118,7 +118,7 @@ namespace AzToolsFramework } bool LoadInstanceFromPrefabDom( - Instance& instance, const PrefabDom& prefabDom, AZStd::vector>& loadedAssets, LoadInstanceFlags flags) + Instance& instance, const PrefabDom& prefabDom, AZStd::vector>& referencedAssets, LoadInstanceFlags flags) { // When entities are rebuilt they are first destroyed. As a result any assets they were exclusively holding on to will // be released and reloaded once the entities are built up again. By suspending asset release temporarily the asset reload @@ -156,7 +156,7 @@ namespace AzToolsFramework return false; } - loadedAssets = assetTracker.GetTrackedAssets(); + referencedAssets = AZStd::move(assetTracker.GetTrackedAssets()); return true; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h index 1f000c2f70..c0992abda9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h @@ -76,7 +76,8 @@ namespace AzToolsFramework * @return bool on whether the operation succeeded. */ bool LoadInstanceFromPrefabDom( - Instance& instance, const PrefabDom& prefabDom, AZStd::vector>& loadedAssets, LoadInstanceFlags flags = LoadInstanceFlags::None); + Instance& instance, const PrefabDom& prefabDom, AZStd::vector>& referencedAssets, + LoadInstanceFlags flags = LoadInstanceFlags::None); /** * Loads a valid Prefab Instance from a Prefab Dom. Useful for generating Instances. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp index 9ae795dbf1..a89b364471 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp @@ -20,8 +20,6 @@ #include #include -#include - namespace AzToolsFramework::Prefab::PrefabConversionUtils { void PrefabCatchmentProcessor::Process(PrefabProcessorContext& context) @@ -65,7 +63,6 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils AZStd::move(uniqueName), context.GetSourceUuid(), AZStd::move(serializer)); AZ_Assert(spawnable, "Failed to create a new spawnable."); - Prefab::PrefabDomUtils::PrintPrefabDomValue("Prefab used for spawnable", prefab); bool result = SpawnableUtils::CreateSpawnable(*spawnable, prefab, object.GetReferencedAssets()); if (result) { From b57dd02d90139ce33928d2d5cba1d569c8b8e7dd Mon Sep 17 00:00:00 2001 From: srikappa Date: Mon, 10 May 2021 12:28:33 -0700 Subject: [PATCH 021/100] Removed a debug print command --- .../AzToolsFramework/Prefab/PrefabPublicHandler.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 9959ae18fa..4d1a657245 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -297,7 +297,7 @@ namespace AzToolsFramework else { linkId = m_prefabSystemComponentInterface->CreateLink( - targetTemplateId, sourceInstance.GetTemplateId(), sourceInstance.GetInstanceAlias(), AZStd::move(patch), + targetTemplateId, sourceInstance.GetTemplateId(), sourceInstance.GetInstanceAlias(), patch, InvalidLinkId); m_prefabSystemComponentInterface->PropagateTemplateChanges(targetTemplateId); } @@ -439,8 +439,6 @@ namespace AzToolsFramework PrefabDom patch; m_instanceToTemplateInterface->GeneratePatch(patch, beforeState, afterState); - PrefabDomUtils::PrintPrefabDomValue(entity->GetName(), patch); - if (patch.IsArray() && !patch.Empty() && beforeState.IsObject()) { if (IsInstanceContainerEntity(entityId) && !IsLevelInstanceContainerEntity(entityId)) From 1e232294d564f0fa80190549ee77850807b1b9d1 Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Mon, 10 May 2021 14:36:32 -0500 Subject: [PATCH 022/100] Added Null RHI to all targets --- Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt index 30861a6feb..33873e0dfa 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt +++ b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt @@ -54,6 +54,7 @@ ly_add_target( RUNTIME_DEPENDENCIES Gem::Atom_RHI.Private Gem::Atom_RPI.Private + Gem::Atom_RHI_Null.Private Gem::Atom_Feature_Common Gem::Atom_Bootstrap Gem::Atom_Component_DebugCamera @@ -89,6 +90,8 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::Atom_RHI.Private Gem::Atom_RPI.Builders Gem::Atom_RPI.Editor + Gem::Atom_RHI_Null.Private + Gem::Atom_RHI_Null.Builders Gem::Atom_Feature_Common.Builders Gem::Atom_Feature_Common.Editor Gem::Atom_Bootstrap From 4c0fdf78bcfe5918d4ac69a93db44d5f401b3e58 Mon Sep 17 00:00:00 2001 From: sconel Date: Mon, 10 May 2021 12:56:54 -0700 Subject: [PATCH 023/100] Added error messaging, cleaned up LoadReferencedAssets --- .../Entity/PrefabEditorEntityOwnershipService.cpp | 7 ++++++- .../Entity/PrefabEditorEntityOwnershipService.h | 2 ++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp index a4e9d207be..0206875418 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp @@ -343,12 +343,13 @@ namespace AzToolsFramework m_validateEntitiesCallback = AZStd::move(validateEntitiesCallback); } - void LoadReferencedAssets(AZStd::vector>& referencedAssets) + void PrefabEditorEntityOwnershipService::LoadReferencedAssets(AZStd::vector>& referencedAssets) { for (AZ::Data::Asset& asset : referencedAssets) { if (!asset.GetId().IsValid()) { + AZ_Error("Prefab", false, "Invalid asset found referenced in scene while entering game mode"); continue; } @@ -367,6 +368,7 @@ namespace AzToolsFramework if (!asset.GetId().IsValid()) { + AZ_Error("Prefab", false, "Invalid asset found referenced in scene while entering game mode"); continue; } @@ -376,6 +378,9 @@ namespace AzToolsFramework if (asset.IsError()) { + AZ_Error("Prefab", false, "Asset with id %s failed to preload while entering game mode", + asset.GetId().ToString().c_str()); + continue; } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h index 9c483e61c5..48e07df091 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.h @@ -199,6 +199,8 @@ namespace AzToolsFramework void OnEntityRemoved(AZ::EntityId entityId); + void LoadReferencedAssets(AZStd::vector>& referencedAssets); + OnEntitiesAddedCallback m_entitiesAddedCallback; OnEntitiesRemovedCallback m_entitiesRemovedCallback; ValidateEntitiesCallback m_validateEntitiesCallback; From 17ccf904801e1d0480670f6ef79277c03748d6b4 Mon Sep 17 00:00:00 2001 From: sconel Date: Mon, 10 May 2021 12:59:16 -0700 Subject: [PATCH 024/100] Updated function header comment --- .../AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h index c0992abda9..6778c236ee 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h @@ -71,6 +71,7 @@ namespace AzToolsFramework /** * Loads a valid Prefab Instance from a Prefab Dom. Useful for generating Instances. * @param instance The Instance to load. + * @param referencedAssets AZ::Assets discovered during json load are added to this list * @param prefabDom the prefabDom that will be used to load the Instance data. * @param shouldClearContainers whether to clear containers in Instance while loading. * @return bool on whether the operation succeeded. From 9255e4c1917c91396e678f8d3b9e54df842aeaab Mon Sep 17 00:00:00 2001 From: sconel Date: Mon, 10 May 2021 13:05:29 -0700 Subject: [PATCH 025/100] Added non const getter to SerializedAssetTracker --- .../Framework/AzCore/AzCore/Asset/SerializedAssetTracker.cpp | 5 +++++ Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.h | 1 + 2 files changed, 6 insertions(+) diff --git a/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.cpp b/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.cpp index b3fad2431f..bdd89683f6 100644 --- a/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.cpp +++ b/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.cpp @@ -25,5 +25,10 @@ namespace AZ { return m_serializedAssets; } + + AZStd::vector>& SerializedAssetTracker::GetTrackedAssets() + { + return m_serializedAssets; + } } } diff --git a/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.h b/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.h index e1b0af72e1..ad80a077fe 100644 --- a/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.h +++ b/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.h @@ -24,6 +24,7 @@ namespace AZ AZ_RTTI(SerializedAssetTracker, "{1E067091-8C0A-44B1-A455-6E97663F6963}"); void AddAsset(Asset& asset); + AZStd::vector>& GetTrackedAssets(); const AZStd::vector>& GetTrackedAssets() const; private: From 3b55d56593095bedc622c4d72102efeffe9d6ff8 Mon Sep 17 00:00:00 2001 From: jckand-amzn Date: Mon, 10 May 2021 15:10:32 -0500 Subject: [PATCH 026/100] Updating test asset for DistanceBetweenFilter tests --- AutomatedTesting/Slices/1m_Cube.slice | 49 +++++++++++---------------- 1 file changed, 19 insertions(+), 30 deletions(-) diff --git a/AutomatedTesting/Slices/1m_Cube.slice b/AutomatedTesting/Slices/1m_Cube.slice index 5ace34bd10..b31869c7fa 100644 --- a/AutomatedTesting/Slices/1m_Cube.slice +++ b/AutomatedTesting/Slices/1m_Cube.slice @@ -39,6 +39,7 @@ + @@ -61,7 +62,7 @@ - + @@ -122,38 +123,26 @@ - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - + From a768c28b31339dfaf01844dc92054bd9f631b8f7 Mon Sep 17 00:00:00 2001 From: jckand-amzn Date: Mon, 10 May 2021 15:11:28 -0500 Subject: [PATCH 027/100] Adding Qtest as a dependency of Editor automated tests --- AutomatedTesting/Gem/PythonTests/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 3124f1048a..11ee414b36 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -366,6 +366,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ Legacy::Editor AZ::AssetProcessor AutomatedTesting.Assets + 3rdParty::Qt::Test COMPONENT Editor ) From f7ea02afdcd554eac29a0d3b6101071bbeccd24d Mon Sep 17 00:00:00 2001 From: sconel Date: Mon, 10 May 2021 13:21:13 -0700 Subject: [PATCH 028/100] Fix for NetworkingProcessor using CreateSpawnable without ReferencedAssets arg --- .../AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp | 6 ++++++ .../AzToolsFramework/Prefab/Spawnable/SpawnableUtils.h | 1 + 2 files changed, 7 insertions(+) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp index 085758cda9..716c3098d9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.cpp @@ -35,6 +35,12 @@ namespace AzToolsFramework::Prefab::SpawnableUtils return spawnable; } + bool CreateSpawnable(AzFramework::Spawnable& spawnable, const PrefabDom& prefabDom) + { + AZStd::vector> referencedAssets; + return CreateSpawnable(spawnable, prefabDom, referencedAssets); + } + bool CreateSpawnable(AzFramework::Spawnable& spawnable, const PrefabDom& prefabDom, AZStd::vector>& referencedAssets) { Instance instance; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.h index c30e5ea77a..3b5ea488cb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/SpawnableUtils.h @@ -18,6 +18,7 @@ namespace AzToolsFramework::Prefab::SpawnableUtils { AzFramework::Spawnable CreateSpawnable(const PrefabDom& prefabDom); + bool CreateSpawnable(AzFramework::Spawnable& spawnable, const PrefabDom& prefabDom); bool CreateSpawnable(AzFramework::Spawnable& spawnable, const PrefabDom& prefabDom, AZStd::vector>& referencedAssets); void SortEntitiesByTransformHierarchy(AzFramework::Spawnable& spawnable); From e37b3989bedc1b4c3beec5bdd8268a9ff38fb624 Mon Sep 17 00:00:00 2001 From: pruiksma Date: Mon, 10 May 2021 15:31:33 -0500 Subject: [PATCH 029/100] ATOM-15515 Fixing nullptr reference in OnShapeChanged() when visibility is turned back on for shapeless punctual light types. --- .../Code/Source/CoreLights/LightDelegateBase.inl | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateBase.inl b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateBase.inl index 406df42547..c255f02400 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateBase.inl +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateBase.inl @@ -101,6 +101,7 @@ namespace AZ template void LightDelegateBase::OnShapeChanged(ShapeChangeReasons changeReason) { + AZ_Assert(m_shapeBus, "OnShapeChanged called without a shape bus present."); if (changeReason == ShapeChangeReasons::TransformChanged) { AZ::Aabb aabb; // unused, but required for GetTransformAndLocalBounds() @@ -133,7 +134,11 @@ namespace AZ { // now visible, acquire light handle and update values. m_lightHandle = m_featureProcessor->AcquireLight(); - OnShapeChanged(ShapeChangeReasons::TransformChanged); + if (m_shapeBus) + { + // For lights that get their transform from the shape bus, force an OnShapeChanged to update the transform. + OnShapeChanged(ShapeChangeReasons::TransformChanged); + } } } From 93974dd1c51cfcde72fe187a2072f6ffeb499da7 Mon Sep 17 00:00:00 2001 From: sconel Date: Mon, 10 May 2021 14:22:48 -0700 Subject: [PATCH 030/100] Seperated queue load and blocking load calls so queue loads aren't interrupted. Added comment about asset dispatch events --- .../PrefabEditorEntityOwnershipService.cpp | 38 +++++++++++++------ 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp index 0206875418..6b6f1475bb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp @@ -345,6 +345,7 @@ namespace AzToolsFramework void PrefabEditorEntityOwnershipService::LoadReferencedAssets(AZStd::vector>& referencedAssets) { + // Start our loads on all assets by calling GetAsset from the AssetManager for (AZ::Data::Asset& asset : referencedAssets) { if (!asset.GetId().IsValid()) @@ -362,7 +363,6 @@ namespace AzToolsFramework AZ::Data::AssetId assetId = asset.GetId(); AZ::Data::AssetType assetType = asset.GetType(); - const bool blockingLoad = loadBehavior == AZ::Data::AssetLoadBehavior::PreLoad; asset = AZ::Data::AssetManager::Instance().GetAsset(assetId, assetType, loadBehavior); @@ -371,18 +371,33 @@ namespace AzToolsFramework AZ_Error("Prefab", false, "Invalid asset found referenced in scene while entering game mode"); continue; } + } - if (blockingLoad) + // For all Preload assets we block until they're ready + // We do this as a seperate pass so that we don't interrupt queuing up all other asset loads + for (AZ::Data::Asset& asset : referencedAssets) + { + if (!asset.GetId().IsValid()) { - asset.BlockUntilLoadComplete(); + AZ_Error("Prefab", false, "Invalid asset found referenced in scene while entering game mode"); + continue; + } - if (asset.IsError()) - { - AZ_Error("Prefab", false, "Asset with id %s failed to preload while entering game mode", - asset.GetId().ToString().c_str()); + const AZ::Data::AssetLoadBehavior loadBehavior = asset.GetAutoLoadBehavior(); - continue; - } + if (loadBehavior != AZ::Data::AssetLoadBehavior::PreLoad) + { + continue; + } + + asset.BlockUntilLoadComplete(); + + if (asset.IsError()) + { + AZ_Error("Prefab", false, "Asset with id %s failed to preload while entering game mode", + asset.GetId().ToString().c_str()); + + continue; } } } @@ -438,6 +453,9 @@ namespace AzToolsFramework m_playInEditorData.m_assets.emplace_back(product.ReleaseAsset().release(), AZ::Data::AssetLoadBehavior::Default); } + // make sure that PRE_NOTIFY assets get their notify before we activate, so that we can preserve the order of + // (load asset) -> (notify) -> (init) -> (activate) + AZ::Data::AssetManager::Instance().DispatchEvents(); if (rootSpawnableIndex != NoRootSpawnable) { @@ -445,8 +463,6 @@ namespace AzToolsFramework m_playInEditorData.m_entities.SpawnAllEntities(); } - AZ::Data::AssetManager::Instance().DispatchEvents(); - // This is a workaround until the replacement for GameEntityContext is done AzFramework::GameEntityContextEventBus::Broadcast( &AzFramework::GameEntityContextEventBus::Events::OnGameEntitiesStarted); From 63b3dbefa82e6937b2a0eede1002a9a1fc520d03 Mon Sep 17 00:00:00 2001 From: mnaumov Date: Mon, 10 May 2021 14:24:45 -0700 Subject: [PATCH 031/100] Fixing parallax artifacts --- .../Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl | 2 +- Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.azsl | 2 +- .../Materials/Types/StandardMultilayerPBR_ForwardPass.azsl | 2 +- .../Assets/Materials/Types/StandardPBR_ForwardPass.azsl | 4 ++-- .../Features/LightCulling/LightCullingTileIterator.azsli | 6 +++--- 5 files changed, 8 insertions(+), 8 deletions(-) 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 23e28e8742..367b2e379c 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl @@ -268,7 +268,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float LightingData lightingData; // Light iterator - lightingData.tileIterator.Init(IN.m_position, PassSrg::m_lightListRemapped, PassSrg::m_tileLightData); + lightingData.tileIterator.Init(IN.m_position.xy, IN.m_position.z, PassSrg::m_lightListRemapped, PassSrg::m_tileLightData); lightingData.Init(surface.position, surface.normal, surface.roughnessLinear); // Directional light shadow coordinates diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.azsl index 84095ac163..c81d96d552 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.azsl @@ -324,7 +324,7 @@ PbrLightingOutput SkinPS_Common(VSOutput IN) LightingData lightingData; // Light iterator - lightingData.tileIterator.Init(IN.m_position, PassSrg::m_lightListRemapped, PassSrg::m_tileLightData); + lightingData.tileIterator.Init(IN.m_position.xy, IN.m_position.z, PassSrg::m_lightListRemapped, PassSrg::m_tileLightData); lightingData.Init(surface.position, surface.normal, surface.roughnessLinear); // Directional light shadow coordinates 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 a83ea629e4..5c527998c1 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl @@ -303,7 +303,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float LightingData lightingData; // Light iterator - lightingData.tileIterator.Init(IN.m_position, PassSrg::m_lightListRemapped, PassSrg::m_tileLightData); + lightingData.tileIterator.Init(IN.m_position.xy, IN.m_position.z, PassSrg::m_lightListRemapped, PassSrg::m_tileLightData); lightingData.Init(surface.position, surface.normal, surface.roughnessLinear); // Directional light shadow coordinates 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 22751b49bc..dc20f89a75 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl @@ -125,7 +125,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float // ------- Depth & Parallax ------- - depth = IN.m_position.z; + depth = IN.m_position.w; bool displacementIsClipped = false; @@ -210,7 +210,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float LightingData lightingData; // Light iterator - lightingData.tileIterator.Init(IN.m_position, PassSrg::m_lightListRemapped, PassSrg::m_tileLightData); + lightingData.tileIterator.Init(IN.m_position.xy, IN.m_position.z, PassSrg::m_lightListRemapped, PassSrg::m_tileLightData); lightingData.Init(surface.position, surface.normal, surface.roughnessLinear); // Directional light shadow coordinates diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/LightCulling/LightCullingTileIterator.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/LightCulling/LightCullingTileIterator.azsli index 001f672631..314a8951a4 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/LightCulling/LightCullingTileIterator.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/LightCulling/LightCullingTileIterator.azsli @@ -17,13 +17,13 @@ // This class is used by forward shaders to iterate through lights (and decals) that are visible at this pixel position class LightCullingTileIterator { - void Init(float4 svPosition, StructuredBuffer lightListRemapped, Texture2D tileLightDataTex) + void Init(float2 screenPos, float depth, StructuredBuffer lightListRemapped, Texture2D tileLightDataTex) { m_lightListRemapped = lightListRemapped; - uint2 tileId = ComputeTileId(svPosition.xy); + uint2 tileId = ComputeTileId(screenPos); - float viewz = abs(svPosition.w); + float viewz = abs(depth); // https://jira.agscollab.com/browse/ATOM-4198 // Replace GetDimensions() with a cbuffer uint read. Reading it from a cbuffer should be faster From a2cadb1d4056459bd133e50f80e5472851bc50d8 Mon Sep 17 00:00:00 2001 From: jckand-amzn Date: Mon, 10 May 2021 17:47:10 -0500 Subject: [PATCH 032/100] Restructuring DistanceBetweenFilter tests to allow for further debugging --- ...errides_InstancesPlantAtSpecifiedRadius.py | 25 +++++++++---------- ...nFilter_InstancesPlantAtSpecifiedRadius.py | 24 +++++++++--------- 2 files changed, 24 insertions(+), 25 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py index 85a16056f5..d0c6fc3c5a 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py @@ -87,30 +87,29 @@ class TestDistanceBetweenFilterComponentOverrides(EditorTestHelper): spawner_entity.add_component("Vegetation Distance Between Filter") spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Override Enabled", True) - self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 2), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 2), 5.0) and \ - self.test_success + num_expected = 16 * 16 + initial_success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + self.test_success = self.test_success and initial_success # 6) Change Radius Min to 1.0, refresh, and verify instance counts are accurate spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Radius Min", 1.0) - self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 1), 5.0) and \ - self.test_success + point_a_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) + point_b_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) + point_c_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 1), 5.0) + self.test_success = self.test_success and point_a_success and point_b_success and point_c_success # 7) Change Radius Min to 2.0, refresh, and verify instance counts are accurate spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Radius Min", 2.0) - self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 0), 5.0) and \ - self.test_success + point_a_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) + point_b_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) + point_c_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 0), 5.0) + self.test_success = self.test_success and point_a_success and point_b_success and point_c_success # 8) Change Radius Min to 16.0, refresh, and verify instance counts are accurate, only a single instance should plant spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Radius Min", 16.0) num_expected_instances = 1 final_check_success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) - self.test_success = final_check_success and self.test_success + self.test_success = self.test_success and final_check_success test = TestDistanceBetweenFilterComponentOverrides() diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py index 59fbca205f..d342afd7ca 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py @@ -82,24 +82,24 @@ class TestDistanceBetweenFilterComponent(EditorTestHelper): # 5) Add a Vegetation Distance Between Filter and verify initial instance counts are accurate spawner_entity.add_component("Vegetation Distance Between Filter") - self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 2), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 2), 5.0) and \ - self.test_success + num_expected = 16 * 16 + num_expected = 16 * 16 + initial_success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + self.test_success = self.test_success and initial_success # 6) Change Radius Min to 1.0, refresh, and verify instance counts are accurate spawner_entity.get_set_test(3, "Configuration|Radius Min", 1.0) - self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 1), 5.0) and \ - self.test_success + point_a_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) + point_b_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) + point_c_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 1), 5.0) + self.test_success = self.test_success and point_a_success and point_b_success and point_c_success # 7) Change Radius Min to 2.0, refresh, and verify instance counts are accurate spawner_entity.get_set_test(3, "Configuration|Radius Min", 2.0) - self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 0), 5.0) and \ - self.test_success + point_a_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) + point_b_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) + point_c_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 0), 5.0) + self.test_success = self.test_success and point_a_success and point_b_success and point_c_success # 8) Change Radius Min to 16.0, refresh, and verify instance counts are accurate spawner_entity.get_set_test(3, "Configuration|Radius Min", 16.0) From b5d54450d8511893da4663d84c93f4e95c9eb7ca Mon Sep 17 00:00:00 2001 From: catdo Date: Mon, 10 May 2021 15:55:31 -0700 Subject: [PATCH 033/100] added prefabnautomated test --- .../PrefabLevel_OpensLevelWithEntities.py | 78 ++++++++ .../PythonTests/prefab/TestSuite_Active.py | 39 ++++ .../Gem/PythonTests/prefab/__init__.py | 10 + .../PrefabLevel_OpensLevelWithEntities.prefab | 171 ++++++++++++++++++ .../tags.txt | 12 ++ 5 files changed, 310 insertions(+) create mode 100644 AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py create mode 100644 AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Active.py create mode 100644 AutomatedTesting/Gem/PythonTests/prefab/__init__.py create mode 100644 AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/PrefabLevel_OpensLevelWithEntities.prefab create mode 100644 AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/tags.txt diff --git a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py new file mode 100644 index 0000000000..45f44474e1 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py @@ -0,0 +1,78 @@ +""" +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. +""" + + +# fmt:off +class Tests (): + find_empty_entity = ("Entity: 'EmptyEntity' found", "Entity: 'EmptyEntity' *not* found in level") + empty_entity_pos = ( + "'EmptyEntity' position is at the expected position", "'EmptyEntity' position is *not* at the expected position") + find_pxentity = ("Entity: 'EntityWithPxCollider' found", "Entity: 'EntityWithPxCollider' *not* found in level") + pxentity_component = ( + "Entity: 'EntityWithPxCollider' has a Physx Collider", "Entity: 'EntityWithPxCollider' has *not* a Physx Collider") + +# fmt:on + +def PrefabLevel_OpensLevelWithEntities (): + """ + Opens the level that contains 2 entities, "EmptyEntity" and "EntityWithPxCollider". + This test makes sure that both entities exist after openning the level and that: + - EmptyEntity is at Position: (10, 20, 30) + - EntityWithPxCollider has a PhysXCollider component + """ + + import os + import sys + + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + import editor_python_test_tools.hydra_editor_utils as hydra + + import azlmbr.legacy.general as general + import azlmbr.bus + from azlmbr.math import Vector3 + + EXPECTED_EMPTY_ENTITY_POS = Vector3 (10.00, 20.0, 30.0) + + helper.init_idle () + helper.open_level ("prefab", "PrefabLevel_OpensLevelWithEntities") + + class EmptyEntity (): + value = None + + def find_empty_entity (): + EmptyEntity.value = general.find_editor_entity ("EmptyEntity") + return EmptyEntity.value.IsValid () + + helper.wait_for_condition (find_empty_entity, 5.0) + Report.result (Tests.find_empty_entity, EmptyEntity.value.IsValid ()) + + empty_entity_pos = azlmbr.components.TransformBus (azlmbr.bus.Event, "GetWorldTranslation", EmptyEntity.value) + is_at_position = empty_entity_pos.IsClose (EXPECTED_EMPTY_ENTITY_POS) + Report.result (Tests.empty_entity_pos, is_at_position) + if not is_at_position: + Report.info (f'Expected position: {EXPECTED_EMPTY_ENTITY_POS.ToString ()}, actual position: {empty_entity_pos.ToString ()}') + + pxentity = general.find_editor_entity ("EntityWithPxCollider") + Report.result (Tests.find_pxentity, pxentity.IsValid ()) + + pxcollider_id = hydra.get_component_type_id ("PhysX Collider") + hasComponent = azlmbr.editor.EditorComponentAPIBus (azlmbr.bus.Broadcast, 'HasComponentOfType', pxentity, + pxcollider_id) + Report.result (Tests.pxentity_component, hasComponent) + + +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test (PrefabLevel_OpensLevelWithEntities) + PrefabLevel_OpensLevelWithEntities () \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Active.py new file mode 100644 index 0000000000..3cd0a0d43d --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Active.py @@ -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. + + """ + +# This suite consists of all test cases that are passing and have been verified. + +import pytest +import os +import sys + +from ly_test_tools import LAUNCHERS + +sys.path.append (os.path.dirname (os.path.abspath (__file__)) + '/../automatedtesting_shared') + +from base import TestAutomationBase + + +@pytest.mark.SUITE_main +@pytest.mark.parametrize ("launcher_platform", ['windows_editor']) +@pytest.mark.parametrize ("project", ["AutomatedTesting"]) +class TestAutomation (TestAutomationBase): + + def _run_prefab_test (self, request, workspace, editor, test_module): + self._run_test (request, workspace, editor, test_module, + ["--regset=/Amazon/Preferences/EnablePrefabSystem=true"]) + + def test_PrefabLevel_OpensLevelWithEntities (self, request, workspace, editor, launcher_platform): + from . import PrefabLevel_OpensLevelWithEntities as test_module + + + self._run_prefab_test (request, workspace, editor, test_module) \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/prefab/__init__.py b/AutomatedTesting/Gem/PythonTests/prefab/__init__.py new file mode 100644 index 0000000000..6ed3dc4bda --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/prefab/__init__.py @@ -0,0 +1,10 @@ +""" +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. +""" \ No newline at end of file diff --git a/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/PrefabLevel_OpensLevelWithEntities.prefab b/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/PrefabLevel_OpensLevelWithEntities.prefab new file mode 100644 index 0000000000..0776f25935 --- /dev/null +++ b/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/PrefabLevel_OpensLevelWithEntities.prefab @@ -0,0 +1,171 @@ +{ + "Source": "Levels/PrefabLevel_OpensLevelWithEntities/PrefabLevel_OpensLevelWithEntities.prefab", + "ContainerEntity": { + "Id": "Entity_[403811863694]", + "Name": "Level", + "Components": { + "Component_[10582285743525614098]": { + "$type": "SelectionComponent", + "Id": 10582285743525614098 + }, + "Component_[12253783095375428046]": { + "$type": "EditorInspectorComponent", + "Id": 12253783095375428046 + }, + "Component_[13764860261821571747]": { + "$type": "{27F1E1A1-8D9D-4C3B-BD3A-AFB9762449C0} TransformComponent", + "Id": 13764860261821571747, + "Parent Entity": "" + }, + "Component_[15844324401733835865]": { + "$type": "EditorEntitySortComponent", + "Id": 15844324401733835865 + }, + "Component_[1605854641405361768]": { + "$type": "EditorLockComponent", + "Id": 1605854641405361768 + }, + "Component_[17698173984524983803]": { + "$type": "EditorOnlyEntityComponent", + "Id": 17698173984524983803 + }, + "Component_[3444251662966224826]": { + "$type": "EditorPendingCompositionComponent", + "Id": 3444251662966224826 + }, + "Component_[4231768881195179982]": { + "$type": "EditorVisibilityComponent", + "Id": 4231768881195179982 + }, + "Component_[4722360315410084479]": { + "$type": "EditorDisabledCompositionComponent", + "Id": 4722360315410084479 + }, + "Component_[7614719100624882952]": { + "$type": "EditorPrefabComponent", + "Id": 7614719100624882952 + }, + "Component_[9585901769691795481]": { + "$type": "EditorEntityIconComponent", + "Id": 9585901769691795481 + } + }, + "IsDependencyReady": true + }, + "Entities": { + "Entity_[438171602062]": { + "Id": "Entity_[438171602062]", + "Name": "EntityWithPxCollider", + "Components": { + "Component_[11161653124805884473]": { + "$type": "EditorPendingCompositionComponent", + "Id": 11161653124805884473 + }, + "Component_[13116773315299882093]": { + "$type": "EditorOnlyEntityComponent", + "Id": 13116773315299882093 + }, + "Component_[15820915681461536711]": { + "$type": "EditorVisibilityComponent", + "Id": 15820915681461536711 + }, + "Component_[2222061938345834243]": { + "$type": "SelectionComponent", + "Id": 2222061938345834243 + }, + "Component_[3861913165076405600]": { + "$type": "EditorEntitySortComponent", + "Id": 3861913165076405600 + }, + "Component_[7118587015611303204]": { + "$type": "EditorLockComponent", + "Id": 7118587015611303204 + }, + "Component_[7751174327125555504]": { + "$type": "EditorDisabledCompositionComponent", + "Id": 7751174327125555504 + }, + "Component_[8304730147756374057]": { + "$type": "{27F1E1A1-8D9D-4C3B-BD3A-AFB9762449C0} TransformComponent", + "Id": 8304730147756374057, + "Parent Entity": "Entity_[403811863694]", + "Transform Data": { + "Translate": [ + 0.0, + 20.0, + 34.0 + ] + } + }, + "Component_[8866353210615920259]": { + "$type": "EditorEntityIconComponent", + "Id": 8866353210615920259 + }, + "Component_[8988181228601932779]": { + "$type": "EditorInspectorComponent", + "Id": 8988181228601932779 + }, + "Component_[7103333782129541775]": { + "$type": "EditorColliderComponent", + "Id": 7103333782129541775 + } + }, + "IsDependencyReady": true + }, + "Entity_[532660882574]": { + "Id": "Entity_[532660882574]", + "Name": "EmptyEntity", + "Components": { + "Component_[16437814751543997955]": { + "$type": "EditorEntitySortComponent", + "Id": 16437814751543997955 + }, + "Component_[16751517102089557119]": { + "$type": "EditorPendingCompositionComponent", + "Id": 16751517102089557119 + }, + "Component_[16773275259304187949]": { + "$type": "EditorInspectorComponent", + "Id": 16773275259304187949 + }, + "Component_[17283539636910567200]": { + "$type": "SelectionComponent", + "Id": 17283539636910567200 + }, + "Component_[250004123617033400]": { + "$type": "EditorLockComponent", + "Id": 250004123617033400 + }, + "Component_[2791138963683667073]": { + "$type": "{27F1E1A1-8D9D-4C3B-BD3A-AFB9762449C0} TransformComponent", + "Id": 2791138963683667073, + "Parent Entity": "Entity_[403811863694]", + "Transform Data": { + "Translate": [ + 10.0, + 20.0, + 30.0 + ] + } + }, + "Component_[3296942400051129145]": { + "$type": "EditorEntityIconComponent", + "Id": 3296942400051129145 + }, + "Component_[3422076964671342434]": { + "$type": "EditorOnlyEntityComponent", + "Id": 3422076964671342434 + }, + "Component_[3431895414183121731]": { + "$type": "EditorVisibilityComponent", + "Id": 3431895414183121731 + }, + "Component_[7072085777705148766]": { + "$type": "EditorDisabledCompositionComponent", + "Id": 7072085777705148766 + } + }, + "IsDependencyReady": true + } + } +} \ No newline at end of file diff --git a/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/tags.txt b/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/tags.txt new file mode 100644 index 0000000000..0d6c1880e7 --- /dev/null +++ b/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/tags.txt @@ -0,0 +1,12 @@ +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 From 333fe5232c6c3d77fa6ed92018616cf6b6192857 Mon Sep 17 00:00:00 2001 From: catdo Date: Mon, 10 May 2021 15:59:12 -0700 Subject: [PATCH 034/100] added prefab to cmakelists --- AutomatedTesting/Gem/PythonTests/CMakeLists.txt | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 31afab87ed..b3d74055f9 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -122,6 +122,22 @@ endif() # ) #endif() +## Prefab ## + if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) + ly_add_pytest( + NAME AutomatedTesting::PrefabTests + TEST_SUITE main + TEST_SERIAL + PATH ${CMAKE_CURRENT_LIST_DIR}/prefab/TestSuite_Active.py + TIMEOUT 3600 + RUNTIME_DEPENDENCIES + Legacy::Editor + Legacy::CryRenderNULL + AZ::AssetProcessor + AutomatedTesting.Assets + ) + endif() + ## Editor Python Bindings ## if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_pytest( From cf0d3af78e55d3d4f18292d0f856e4dcc7744865 Mon Sep 17 00:00:00 2001 From: guthadam Date: Mon, 10 May 2021 18:02:26 -0500 Subject: [PATCH 035/100] ATOM-15128 replacing material editor icon --- .../Source/Window/Icons/materialeditor.svg | 20 +++++++++++++++ .../Code/Source/Window/MaterialEditor.qrc | 1 + .../Source/Window/MaterialEditorWindow.cpp | 2 +- Gems/Atom/Tools/MaterialEditor/preview.svg | 25 +++++++++++++------ 4 files changed, 40 insertions(+), 8 deletions(-) create mode 100644 Gems/Atom/Tools/MaterialEditor/Code/Source/Window/Icons/materialeditor.svg diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/Icons/materialeditor.svg b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/Icons/materialeditor.svg new file mode 100644 index 0000000000..31b0b304a1 --- /dev/null +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/Icons/materialeditor.svg @@ -0,0 +1,20 @@ + + + Icons / Application Icons / Material Editor + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditor.qrc b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditor.qrc index 4f93770096..cde48079ac 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditor.qrc +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditor.qrc @@ -1,6 +1,7 @@ MaterialEditor.qss + Icons/materialeditor.svg Icons/material.svg Icons/materialtype.svg Icons/mesh.svg diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index 6e47de189c..d87d3b81e3 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -58,7 +58,7 @@ namespace MaterialEditor { AzQtComponents::StyleManager::setStyleSheet(this, QStringLiteral(":/MaterialEditor.qss")); - QApplication::setWindowIcon(QIcon(":/Icons/materialtype.svg")); + QApplication::setWindowIcon(QIcon(":/Icons/materialeditor.svg")); AZ::Name apiName = AZ::RHI::Factory::Get().GetName(); if (!apiName.IsEmpty()) diff --git a/Gems/Atom/Tools/MaterialEditor/preview.svg b/Gems/Atom/Tools/MaterialEditor/preview.svg index 56c1ead3c1..31b0b304a1 100644 --- a/Gems/Atom/Tools/MaterialEditor/preview.svg +++ b/Gems/Atom/Tools/MaterialEditor/preview.svg @@ -1,9 +1,20 @@ - - Icons / Project Configurator / Gems / Material Editor - - - - + + Icons / Application Icons / Material Editor + + + + + + + + + + + + + + + - + \ No newline at end of file From 43f87d1541a3d810c782845935e14e57739d14ed Mon Sep 17 00:00:00 2001 From: mnaumov Date: Mon, 10 May 2021 17:58:12 -0700 Subject: [PATCH 036/100] another attempt fixing the artifacts --- .../Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl | 3 ++- Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.azsl | 2 +- .../Materials/Types/StandardMultilayerPBR_ForwardPass.azsl | 3 ++- .../Assets/Materials/Types/StandardPBR_ForwardPass.azsl | 5 +++-- .../Features/LightCulling/LightCullingTileIterator.azsli | 6 +++--- 5 files changed, 11 insertions(+), 8 deletions(-) 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 367b2e379c..34c57db974 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl @@ -163,6 +163,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float { DirectionalLightShadow::GetShadowCoords(shadowIndex, IN.m_worldPosition, IN.m_shadowCoords); } + IN.m_position.w = mul(ViewSrg::m_viewProjectionMatrix, IN.m_worldPosition).z; } } @@ -268,7 +269,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float LightingData lightingData; // Light iterator - lightingData.tileIterator.Init(IN.m_position.xy, IN.m_position.z, PassSrg::m_lightListRemapped, PassSrg::m_tileLightData); + lightingData.tileIterator.Init(IN.m_position, PassSrg::m_lightListRemapped, PassSrg::m_tileLightData); lightingData.Init(surface.position, surface.normal, surface.roughnessLinear); // Directional light shadow coordinates diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.azsl index c81d96d552..84095ac163 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/Skin.azsl @@ -324,7 +324,7 @@ PbrLightingOutput SkinPS_Common(VSOutput IN) LightingData lightingData; // Light iterator - lightingData.tileIterator.Init(IN.m_position.xy, IN.m_position.z, PassSrg::m_lightListRemapped, PassSrg::m_tileLightData); + lightingData.tileIterator.Init(IN.m_position, PassSrg::m_lightListRemapped, PassSrg::m_tileLightData); lightingData.Init(surface.position, surface.normal, surface.roughnessLinear); // Directional light shadow coordinates 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 5c527998c1..9cc0047b72 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl @@ -195,6 +195,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float { DirectionalLightShadow::GetShadowCoords(shadowIndex, IN.m_worldPosition, IN.m_shadowCoords); } + IN.m_position.w = mul(ViewSrg::m_viewProjectionMatrix, IN.m_worldPosition).z; } } @@ -303,7 +304,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float LightingData lightingData; // Light iterator - lightingData.tileIterator.Init(IN.m_position.xy, IN.m_position.z, PassSrg::m_lightListRemapped, PassSrg::m_tileLightData); + lightingData.tileIterator.Init(IN.m_position, PassSrg::m_lightListRemapped, PassSrg::m_tileLightData); lightingData.Init(surface.position, surface.normal, surface.roughnessLinear); // Directional light shadow coordinates 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 dc20f89a75..8621865f54 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl @@ -125,7 +125,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float // ------- Depth & Parallax ------- - depth = IN.m_position.w; + depth = IN.m_position.z; bool displacementIsClipped = false; @@ -147,6 +147,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float { DirectionalLightShadow::GetShadowCoords(shadowIndex, IN.m_worldPosition, IN.m_shadowCoords); } + IN.m_position.w = mul(ViewSrg::m_viewProjectionMatrix, IN.m_worldPosition).z; } } @@ -210,7 +211,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float LightingData lightingData; // Light iterator - lightingData.tileIterator.Init(IN.m_position.xy, IN.m_position.z, PassSrg::m_lightListRemapped, PassSrg::m_tileLightData); + lightingData.tileIterator.Init(IN.m_position, PassSrg::m_lightListRemapped, PassSrg::m_tileLightData); lightingData.Init(surface.position, surface.normal, surface.roughnessLinear); // Directional light shadow coordinates diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/LightCulling/LightCullingTileIterator.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/LightCulling/LightCullingTileIterator.azsli index 314a8951a4..001f672631 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/LightCulling/LightCullingTileIterator.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/LightCulling/LightCullingTileIterator.azsli @@ -17,13 +17,13 @@ // This class is used by forward shaders to iterate through lights (and decals) that are visible at this pixel position class LightCullingTileIterator { - void Init(float2 screenPos, float depth, StructuredBuffer lightListRemapped, Texture2D tileLightDataTex) + void Init(float4 svPosition, StructuredBuffer lightListRemapped, Texture2D tileLightDataTex) { m_lightListRemapped = lightListRemapped; - uint2 tileId = ComputeTileId(screenPos); + uint2 tileId = ComputeTileId(svPosition.xy); - float viewz = abs(depth); + float viewz = abs(svPosition.w); // https://jira.agscollab.com/browse/ATOM-4198 // Replace GetDimensions() with a cbuffer uint read. Reading it from a cbuffer should be faster From 36911723c2b9054468db629a23fa5cc9b1dfbc8d Mon Sep 17 00:00:00 2001 From: sconel Date: Mon, 10 May 2021 18:17:39 -0700 Subject: [PATCH 037/100] Addressed PR feedback --- .../AzCore/Asset/AssetJsonSerializer.cpp | 24 ++++++++++--- .../AzCore/AzCore/Asset/AssetJsonSerializer.h | 14 ++++++++ .../AzCore/Asset/SerializedAssetTracker.cpp | 34 ------------------- .../AzCore/Asset/SerializedAssetTracker.h | 34 ------------------- .../AzCore/AzCore/azcore_files.cmake | 2 -- .../Prefab/PrefabDomUtils.cpp | 9 +++-- .../AzToolsFramework/Prefab/PrefabDomUtils.h | 14 ++++---- 7 files changed, 44 insertions(+), 87 deletions(-) delete mode 100644 Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.cpp delete mode 100644 Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.h diff --git a/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp b/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp index 6968b51025..0078abf2d1 100644 --- a/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp +++ b/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp @@ -12,7 +12,6 @@ #include #include -#include #include #include #include @@ -112,8 +111,8 @@ namespace AZ AssetId id; JSR::ResultCode result(JSR::Tasks::ReadField); - SerializedAssetTracker** assetIdTracker = - context.GetMetadata().Find(); + SerializedAssetTracker* assetTracker = + context.GetMetadata().Find(); { Data::AssetLoadBehavior loadBehavior = instance->GetAutoLoadBehavior(); @@ -168,9 +167,9 @@ namespace AZ "The asset hint is missing for Asset, so it will be left empty.")); } - if (assetIdTracker && *assetIdTracker) + if (assetTracker) { - (*assetIdTracker)->AddAsset(*instance); + assetTracker->AddAsset(*instance); } bool success = result.GetOutcome() <= JSR::Outcomes::PartialSkip; @@ -181,5 +180,20 @@ namespace AZ "Not enough information was available to create an instance of Asset or data was corrupted."; return context.Report(result, message); } + + void SerializedAssetTracker::AddAsset(Asset& asset) + { + m_serializedAssets.emplace_back(asset); + } + + const AZStd::vector>& SerializedAssetTracker::GetTrackedAssets() const + { + return m_serializedAssets; + } + + AZStd::vector>& SerializedAssetTracker::GetTrackedAssets() + { + return m_serializedAssets; + } } // namespace Data } // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.h b/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.h index 3d5271035c..dca12df21b 100644 --- a/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.h +++ b/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.h @@ -13,6 +13,7 @@ #pragma once #include +#include #include namespace AZ @@ -37,5 +38,18 @@ namespace AZ private: JsonSerializationResult::Result LoadAsset(void* outputValue, const rapidjson::Value& inputValue, JsonDeserializerContext& context); }; + + class SerializedAssetTracker + { + public: + AZ_RTTI(SerializedAssetTracker, "{1E067091-8C0A-44B1-A455-6E97663F6963}"); + + void AddAsset(Asset& asset); + AZStd::vector>& GetTrackedAssets(); + const AZStd::vector>& GetTrackedAssets() const; + + private: + AZStd::vector> m_serializedAssets; + }; } // namespace Data } // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.cpp b/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.cpp deleted file mode 100644 index bdd89683f6..0000000000 --- a/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.cpp +++ /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. -* -*/ - -#include - -namespace AZ -{ - namespace Data - { - void SerializedAssetTracker::AddAsset(Asset& asset) - { - m_serializedAssets.emplace_back(asset); - } - - const AZStd::vector>& SerializedAssetTracker::GetTrackedAssets() const - { - return m_serializedAssets; - } - - AZStd::vector>& SerializedAssetTracker::GetTrackedAssets() - { - return m_serializedAssets; - } - } -} diff --git a/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.h b/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.h deleted file mode 100644 index ad80a077fe..0000000000 --- a/Code/Framework/AzCore/AzCore/Asset/SerializedAssetTracker.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 -namespace AZ -{ - namespace Data - { - class SerializedAssetTracker - { - public: - AZ_RTTI(SerializedAssetTracker, "{1E067091-8C0A-44B1-A455-6E97663F6963}"); - - void AddAsset(Asset& asset); - AZStd::vector>& GetTrackedAssets(); - const AZStd::vector>& GetTrackedAssets() const; - - private: - AZStd::vector> m_serializedAssets; - }; - } -} diff --git a/Code/Framework/AzCore/AzCore/azcore_files.cmake b/Code/Framework/AzCore/AzCore/azcore_files.cmake index c6ad90200b..5357ed66a6 100644 --- a/Code/Framework/AzCore/AzCore/azcore_files.cmake +++ b/Code/Framework/AzCore/AzCore/azcore_files.cmake @@ -35,8 +35,6 @@ set(FILES Asset/AssetSerializer.h Asset/AssetTypeInfoBus.h Asset/AssetInternal/WeakAsset.h - Asset/SerializedAssetTracker.cpp - Asset/SerializedAssetTracker.h Casting/lossy_cast.h Casting/numeric_cast.h Component/Component.cpp diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp index 9163b681de..0bffd26be0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include #include @@ -132,15 +132,13 @@ namespace AzToolsFramework entityIdMapper.SetEntityIdGenerationApproach(InstanceEntityIdMapper::EntityIdGenerationApproach::Random); } - AZ::Data::SerializedAssetTracker assetTracker; - AZ::JsonDeserializerSettings settings; // The InstanceEntityIdMapper is registered twice because it's used in several places during deserialization where one is // specific for the InstanceEntityIdMapper and once for the generic JsonEntityIdMapper. Because the Json Serializer's meta // data has strict typing and doesn't look for inheritance both have to be explicitly added so they're found both locations. settings.m_metadata.Add(static_cast(&entityIdMapper)); settings.m_metadata.Add(&entityIdMapper); - settings.m_metadata.Add(&assetTracker); + settings.m_metadata.Create(); AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::Load(instance, prefabDom, settings); @@ -155,8 +153,9 @@ namespace AzToolsFramework return false; } + AZ::Data::SerializedAssetTracker* assetTracker = settings.m_metadata.Find(); - referencedAssets = AZStd::move(assetTracker.GetTrackedAssets()); + referencedAssets = AZStd::move(assetTracker->GetTrackedAssets()); return true; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h index 6778c236ee..c7c2827770 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomUtils.h @@ -43,7 +43,7 @@ namespace AzToolsFramework /** * Stores a valid Prefab Instance within a Prefab Dom. Useful for generating Templates * @param instance The instance to store - * @param prefabDom the prefabDom that will be used to store the Instance data + * @param prefabDom The prefabDom that will be used to store the Instance data * @return bool on whether the operation succeeded */ bool StoreInstanceInPrefabDom(const Instance& instance, PrefabDom& prefabDom); @@ -61,8 +61,8 @@ namespace AzToolsFramework /** * Loads a valid Prefab Instance from a Prefab Dom. Useful for generating Instances. * @param instance The Instance to load. - * @param prefabDom the prefabDom that will be used to load the Instance data. - * @param shouldClearContainers whether to clear containers in Instance while loading. + * @param prefabDom The prefabDom that will be used to load the Instance data. + * @param shouldClearContainers Whether to clear containers in Instance while loading. * @return bool on whether the operation succeeded. */ bool LoadInstanceFromPrefabDom( @@ -72,8 +72,8 @@ namespace AzToolsFramework * Loads a valid Prefab Instance from a Prefab Dom. Useful for generating Instances. * @param instance The Instance to load. * @param referencedAssets AZ::Assets discovered during json load are added to this list - * @param prefabDom the prefabDom that will be used to load the Instance data. - * @param shouldClearContainers whether to clear containers in Instance while loading. + * @param prefabDom The prefabDom that will be used to load the Instance data. + * @param shouldClearContainers Whether to clear containers in Instance while loading. * @return bool on whether the operation succeeded. */ bool LoadInstanceFromPrefabDom( @@ -85,8 +85,8 @@ namespace AzToolsFramework * @param instance The Instance to load. * @param newlyAddedEntities The new instances added during deserializing the instance. These are the entities found * in the prefabDom. - * @param prefabDom the prefabDom that will be used to load the Instance data. - * @param shouldClearContainers whether to clear containers in Instance while loading. + * @param prefabDom The prefabDom that will be used to load the Instance data. + * @param shouldClearContainers Whether to clear containers in Instance while loading. * @return bool on whether the operation succeeded. */ bool LoadInstanceFromPrefabDom( From 12fb07c3e32289707616bf66563b95a79b66b46e Mon Sep 17 00:00:00 2001 From: sconel Date: Mon, 10 May 2021 18:56:29 -0700 Subject: [PATCH 038/100] Fix for failing AssetJsonSerializer conformity tests --- Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp | 2 +- Code/Framework/AzCore/Tests/AssetJsonSerializerTests.cpp | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp b/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp index 0078abf2d1..17b0cba09d 100644 --- a/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp +++ b/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp @@ -129,7 +129,7 @@ namespace AZ if (it != inputValue.MemberEnd()) { ScopedContextPath subPath(context, "assetId"); - result = ContinueLoading(&id, azrtti_typeid(), it->value, context); + result.Combine(ContinueLoading(&id, azrtti_typeid(), it->value, context)); if (!id.m_guid.IsNull()) { *instance = AssetManager::Instance().FindOrCreateAsset(id, instance->GetType(), instance->GetAutoLoadBehavior()); diff --git a/Code/Framework/AzCore/Tests/AssetJsonSerializerTests.cpp b/Code/Framework/AzCore/Tests/AssetJsonSerializerTests.cpp index a494207850..bacbc3649d 100644 --- a/Code/Framework/AzCore/Tests/AssetJsonSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/AssetJsonSerializerTests.cpp @@ -130,6 +130,7 @@ namespace JsonSerializationTests auto instance = AZStd::make_shared(); instance->Create(id, false); instance->SetHint("TestFile"); + instance->SetAutoLoadBehavior(AZ::Data::AssetLoadBehavior::PreLoad); return instance; } @@ -153,6 +154,7 @@ namespace JsonSerializationTests "guid": "{BBEAC89F-8BAD-4A9D-BF6E-D0DF84A8DFD6}", "subId": 1 }, + "loadBehavior": "PreLoad", "assetHint": "TestFile" })"; } From 5cff7994bfce1a1ddce2f6199ff9e1775786458e Mon Sep 17 00:00:00 2001 From: sconel Date: Mon, 10 May 2021 19:00:24 -0700 Subject: [PATCH 039/100] Small update to AssetJsonSerializer result assignment --- Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp b/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp index 17b0cba09d..555eedf034 100644 --- a/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp +++ b/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.cpp @@ -117,10 +117,10 @@ namespace AZ { Data::AssetLoadBehavior loadBehavior = instance->GetAutoLoadBehavior(); - result.Combine( + result = ContinueLoadingFromJsonObjectField(&loadBehavior, azrtti_typeid(), - inputValue, "loadBehavior", context)); + inputValue, "loadBehavior", context); instance->SetAutoLoadBehavior(loadBehavior); } From 286a1aafa984519cb67eda776216362796ec2bb1 Mon Sep 17 00:00:00 2001 From: sconel Date: Mon, 10 May 2021 19:11:51 -0700 Subject: [PATCH 040/100] Clang build fix --- Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.h b/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.h index dca12df21b..780066cd42 100644 --- a/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.h +++ b/Code/Framework/AzCore/AzCore/Asset/AssetJsonSerializer.h @@ -39,7 +39,7 @@ namespace AZ JsonSerializationResult::Result LoadAsset(void* outputValue, const rapidjson::Value& inputValue, JsonDeserializerContext& context); }; - class SerializedAssetTracker + class SerializedAssetTracker final { public: AZ_RTTI(SerializedAssetTracker, "{1E067091-8C0A-44B1-A455-6E97663F6963}"); From fcbdd9e418fd85a1c69ff48c0dcc552e05e36acb Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Mon, 10 May 2021 19:34:54 -0700 Subject: [PATCH 041/100] Added RHI feature flag for unbounded arrays --- Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/DeviceFeatures.h | 3 +++ Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp | 2 ++ Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp | 1 + 3 files changed, 6 insertions(+) diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/DeviceFeatures.h b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/DeviceFeatures.h index 246db1522a..94d1cbd9ae 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/DeviceFeatures.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/DeviceFeatures.h @@ -76,6 +76,9 @@ namespace AZ //! Whether Ray Tracing support is available. bool m_rayTracing = false; + //! Whether Unbounded Array support is available. + bool m_unboundedArrays = false; + /// Additional features here. }; } diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp index 2c47a5a443..af94aef3fb 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp @@ -166,6 +166,8 @@ namespace AZ m_features.m_rayTracing = false; #endif + m_features.m_unboundedArrays = true; + m_limits.m_maxImageDimension1D = D3D12_REQ_TEXTURE1D_U_DIMENSION; m_limits.m_maxImageDimension2D = D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION; m_limits.m_maxImageDimension3D = D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION; diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp index ff7eb7f4c0..76662ebc6e 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp @@ -720,6 +720,7 @@ namespace AZ StringList deviceExtensions = physicalDevice.GetDeviceExtensionNames(); StringList::iterator itRayTracingExtension = AZStd::find(deviceExtensions.begin(), deviceExtensions.end(), VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME); m_features.m_rayTracing = (itRayTracingExtension != deviceExtensions.end()); + m_features.m_unboundedArrays = true; const auto& deviceLimits = physicalDevice.GetDeviceLimits(); m_limits.m_maxImageDimension1D = deviceLimits.maxImageDimension1D; From 8e90e87bc83774d767cda5124871dd40df8c8642 Mon Sep 17 00:00:00 2001 From: greerdv Date: Tue, 11 May 2021 16:17:23 +0100 Subject: [PATCH 042/100] fixing bug with shape collider editor body not being deleted when it is recreated --- .../Source/EditorShapeColliderComponent.cpp | 34 ++++++++++++++----- .../Source/EditorShapeColliderComponent.h | 1 - 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp index 0a8bca33ea..2c86a18301 100644 --- a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp @@ -267,8 +267,14 @@ namespace PhysX if (m_sceneInterface) { + //remove the previous body if any + if (m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) + { + m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); + m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; + } + m_editorBodyHandle = m_sceneInterface->AddSimulatedBody(m_editorSceneHandle, &configuration); - m_editorBody = azdynamic_cast(m_sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorBodyHandle)); } AzPhysics::SimulatedBodyComponentRequestsBus::Handler::BusConnect(GetEntityId()); @@ -676,7 +682,6 @@ namespace PhysX { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - m_editorBody = nullptr; } } @@ -747,21 +752,31 @@ namespace PhysX bool EditorShapeColliderComponent::IsPhysicsEnabled() const { - return m_editorBody != nullptr && m_editorBody->m_simulating; + return m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle; } AZ::Aabb EditorShapeColliderComponent::GetAabb() const { - if (m_editorBody) + if (m_sceneInterface && m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { - return m_editorBody->GetAabb(); + if (auto* body = m_sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorBodyHandle)) + { + return body->GetAabb(); + } } return AZ::Aabb::CreateNull(); } AzPhysics::SimulatedBody* EditorShapeColliderComponent::GetSimulatedBody() { - return m_editorBody; + if (m_sceneInterface && m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) + { + if (auto* body = m_sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorBodyHandle)) + { + return body; + } + } + return nullptr; } AzPhysics::SimulatedBodyHandle EditorShapeColliderComponent::GetSimulatedBodyHandle() const @@ -771,9 +786,12 @@ namespace PhysX AzPhysics::SceneQueryHit EditorShapeColliderComponent::RayCast(const AzPhysics::RayCastRequest& request) { - if (m_editorBody) + if (m_sceneInterface && m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { - return m_editorBody->RayCast(request); + if (auto* body = m_sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorBodyHandle)) + { + return body->RayCast(request); + } } return AzPhysics::SceneQueryHit(); } diff --git a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.h b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.h index bcf5ac4eba..7b7fab789a 100644 --- a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.h +++ b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.h @@ -143,7 +143,6 @@ namespace PhysX DebugDraw::Collider m_colliderDebugDraw; //!< Handles drawing the collider based on global and local AzPhysics::SceneInterface* m_sceneInterface = nullptr; AzPhysics::SceneHandle m_editorSceneHandle = AzPhysics::InvalidSceneHandle; - StaticRigidBody* m_editorBody = nullptr; //!< Body in the editor physics scene if there is no rigid body component. AzPhysics::SimulatedBodyHandle m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; //!< Handle to the body in the editor physics scene if there is no rigid body component. bool m_shapeTypeWarningIssued = false; //!< Records whether a warning about unsupported shapes has been previously issued. PolygonPrismMeshUtils::Mesh2D m_mesh; //!< Used for storing decompositions of the polygon prism. From 704443ac89eeb0774c489ddacbbf6289caa63a7f Mon Sep 17 00:00:00 2001 From: mbalfour Date: Tue, 11 May 2021 10:25:03 -0500 Subject: [PATCH 043/100] Fix up incorrect autoDelete use and handling. Several UI property handlers were incorrectly using the autoDelete feature by calling UnregisterPropertyType and deleting the pointer themselves, which caused double-delete crashes on application shutdown. PropertyManagerComponent now gracefully handles that condition but also explicitly asserts explaining how the code should be changed, and the "known offenders" have been fixed up to use autoDelete correctly. --- .../PropertyManagerComponent.cpp | 33 +++++++++++++++++-- .../Source/UI/GradientPreviewDataWidget.cpp | 23 +++++-------- .../Source/UI/GradientPreviewDataWidget.h | 3 -- .../Code/Editor/SystemComponent.cpp | 8 +---- .../Code/Editor/SystemComponent.h | 1 - .../ScriptEventsSystemEditorComponent.cpp | 8 +---- .../ScriptEventsSystemEditorComponent.h | 2 -- .../EditorVegetationSystemComponent.cpp | 5 +-- .../Editor/EditorVegetationSystemComponent.h | 3 -- 9 files changed, 41 insertions(+), 45 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyManagerComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyManagerComponent.cpp index 21f3b7d1c6..bd61e6ceed 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyManagerComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyManagerComponent.cpp @@ -63,23 +63,40 @@ namespace AzToolsFramework void PropertyManagerComponent::Deactivate() { + // Delete all remaining auto-delete or built-in handlers. for (auto it = m_builtInHandlers.begin(); it != m_builtInHandlers.end(); ++it) { - UnregisterPropertyType(*it); +#ifdef AZ_DEBUG_BUILD + // For debug builds, we'll take the extra time to delete each handler that we're deleting from m_Handlers. + // We loop through m_Handlers below to ensure that we don't have any other handlers still registered after + // we've deleted these. + AZStd::erase_if(m_Handlers, [it](const auto& item) { + auto const& [key, value] = item; + return (key == (*it)->GetHandlerName()) && (value == (*it)); + }); +#endif + delete *it; } m_builtInHandlers.clear(); - #ifdef _DEBUG +#ifdef AZ_DEBUG_BUILD + // Loop through all the remaining registered handlers (if any) and print out an error, as these all are probably memory + // leaks. UnregisterPropertyType should have been called on these already, and their pointers should have been deleted + // by the caller. auto it = m_Handlers.begin(); while (it != m_Handlers.end()) { AZ_Error("PropertyManager", false, "Property Handler 0x%08x is still registered during shutdown", it->first); ++it; } - #endif +#endif + + m_Handlers.clear(); + m_DefaultHandlers.clear(); + PropertyTypeRegistrationMessages::Bus::Handler::BusDisconnect(); } @@ -142,6 +159,16 @@ namespace AzToolsFramework } ++defaultIt; } + + if (pHandler->AutoDelete()) + { + m_builtInHandlers.erase(AZStd::remove(m_builtInHandlers.begin(), m_builtInHandlers.end(), pHandler), + m_builtInHandlers.end()); + AZ_Assert(false, + "Handlers with AutoDelete set should not call UnregisterPropertyType. To fix, do one of the following:\n" + " 1. Set AutoDelete to false in the handler, call UnregisterPropertyType, and the caller should delete the handler.\n" + " 2. Set AutoDelete to true in the handler and do NOT call UnregisterPropertyType or delete the handler."); + } } diff --git a/Gems/GradientSignal/Code/Source/UI/GradientPreviewDataWidget.cpp b/Gems/GradientSignal/Code/Source/UI/GradientPreviewDataWidget.cpp index 14f21c105d..d0f45be56d 100644 --- a/Gems/GradientSignal/Code/Source/UI/GradientPreviewDataWidget.cpp +++ b/Gems/GradientSignal/Code/Source/UI/GradientPreviewDataWidget.cpp @@ -25,8 +25,6 @@ namespace GradientSignal // GradientPreviewDataWidgetHandler // - GradientPreviewDataWidgetHandler* GradientPreviewDataWidgetHandler::s_instance = nullptr; - AZ::u32 GradientPreviewDataWidgetHandler::GetHandlerName() const { return AZ_CRC("GradientPreviewer", 0x1dbbba45); @@ -92,23 +90,18 @@ namespace GradientSignal { using namespace AzToolsFramework; - if (!s_instance) - { - s_instance = aznew GradientPreviewDataWidgetHandler(); - PropertyTypeRegistrationMessages::Bus::Broadcast(&PropertyTypeRegistrationMessages::Bus::Events::RegisterPropertyType, s_instance); - } + // Property handlers are set to auto-delete by default, which means that we're handing off ownership of the pointer to the + // PropertyManagerComponent, where it will get cleaned up on system shutdown. + auto propertyHandler = aznew GradientPreviewDataWidgetHandler(); + AZ_Assert(propertyHandler->AutoDelete(), + "GradientPreviewDataWidgetHandler is no longer set to auto-delete, it will leak memory."); + PropertyTypeRegistrationMessages::Bus::Broadcast( + &PropertyTypeRegistrationMessages::Bus::Events::RegisterPropertyType, propertyHandler); } void GradientPreviewDataWidgetHandler::Unregister() { - using namespace AzToolsFramework; - - if (s_instance) - { - PropertyTypeRegistrationMessages::Bus::Broadcast(&PropertyTypeRegistrationMessages::Bus::Events::UnregisterPropertyType, s_instance); - delete s_instance; - s_instance = nullptr; - } + // We don't need to call UnregisterPropertyType here because it's an autoDelete handler. } // diff --git a/Gems/GradientSignal/Code/Source/UI/GradientPreviewDataWidget.h b/Gems/GradientSignal/Code/Source/UI/GradientPreviewDataWidget.h index b5ee732ed7..cb5c0f8f20 100644 --- a/Gems/GradientSignal/Code/Source/UI/GradientPreviewDataWidget.h +++ b/Gems/GradientSignal/Code/Source/UI/GradientPreviewDataWidget.h @@ -76,8 +76,5 @@ namespace GradientSignal static void Register(); static void Unregister(); - - private: - static GradientPreviewDataWidgetHandler* s_instance; }; } diff --git a/Gems/ScriptCanvas/Code/Editor/SystemComponent.cpp b/Gems/ScriptCanvas/Code/Editor/SystemComponent.cpp index 7d9cb176a3..60e8e5f23a 100644 --- a/Gems/ScriptCanvas/Code/Editor/SystemComponent.cpp +++ b/Gems/ScriptCanvas/Code/Editor/SystemComponent.cpp @@ -134,7 +134,7 @@ namespace ScriptCanvasEditor PopulateEditorCreatableTypes(); - m_propertyHandlers.emplace_back(AzToolsFramework::RegisterGenericComboBoxHandler()); + AzToolsFramework::RegisterGenericComboBoxHandler(); SystemRequestBus::Handler::BusConnect(); ScriptCanvasExecutionBus::Handler::BusConnect(); @@ -177,12 +177,6 @@ namespace ScriptCanvasEditor SystemRequestBus::Handler::BusDisconnect(); AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); - for (auto&& propertyHandler : m_propertyHandlers) - { - AzToolsFramework::PropertyTypeRegistrationMessages::Bus::Broadcast(&AzToolsFramework::PropertyTypeRegistrationMessages::UnregisterPropertyType, propertyHandler.get()); - } - m_propertyHandlers.clear(); - m_jobContext.reset(); m_jobManager.reset(); m_assetTracker.Deactivate(); diff --git a/Gems/ScriptCanvas/Code/Editor/SystemComponent.h b/Gems/ScriptCanvas/Code/Editor/SystemComponent.h index 07ea44e482..f2ebad38cd 100644 --- a/Gems/ScriptCanvas/Code/Editor/SystemComponent.h +++ b/Gems/ScriptCanvas/Code/Editor/SystemComponent.h @@ -147,7 +147,6 @@ namespace ScriptCanvasEditor AZStd::unique_ptr m_jobManager; AZStd::unique_ptr m_jobContext; - AZStd::vector> m_propertyHandlers; AZStd::unordered_set m_creatableTypes; AssetTracker m_assetTracker; diff --git a/Gems/ScriptEvents/Code/Source/Editor/ScriptEventsSystemEditorComponent.cpp b/Gems/ScriptEvents/Code/Source/Editor/ScriptEventsSystemEditorComponent.cpp index 5a4bc33550..f895517f8d 100644 --- a/Gems/ScriptEvents/Code/Source/Editor/ScriptEventsSystemEditorComponent.cpp +++ b/Gems/ScriptEvents/Code/Source/Editor/ScriptEventsSystemEditorComponent.cpp @@ -236,17 +236,11 @@ namespace ScriptEventsEditor moduleConfiguration->RegisterAssetHandler(); } - m_propertyHandlers.emplace_back(AzToolsFramework::RegisterGenericComboBoxHandler()); + AzToolsFramework::RegisterGenericComboBoxHandler(); } void ScriptEventEditorSystemComponent::Deactivate() { - for (auto&& propertyHandler : m_propertyHandlers) - { - AzToolsFramework::PropertyTypeRegistrationMessages::Bus::Broadcast(&AzToolsFramework::PropertyTypeRegistrationMessages::UnregisterPropertyType, propertyHandler.get()); - } - m_propertyHandlers.clear(); - using namespace ScriptEvents; ScriptEventsSystemComponentImpl* moduleConfiguration = nullptr; ScriptEventModuleConfigurationRequestBus::BroadcastResult(moduleConfiguration, &ScriptEventModuleConfigurationRequests::GetSystemComponentImpl); diff --git a/Gems/ScriptEvents/Code/Source/Editor/ScriptEventsSystemEditorComponent.h b/Gems/ScriptEvents/Code/Source/Editor/ScriptEventsSystemEditorComponent.h index d80dcffcf9..a5d34a9a9e 100644 --- a/Gems/ScriptEvents/Code/Source/Editor/ScriptEventsSystemEditorComponent.h +++ b/Gems/ScriptEvents/Code/Source/Editor/ScriptEventsSystemEditorComponent.h @@ -90,8 +90,6 @@ namespace ScriptEventsEditor void Deactivate() override; //////////////////////////////////////////////////////////////////////// - AZStd::vector> m_propertyHandlers; - // Script Event Assets AZStd::unordered_map> m_scriptEvents; diff --git a/Gems/Vegetation/Code/Source/Editor/EditorVegetationSystemComponent.cpp b/Gems/Vegetation/Code/Source/Editor/EditorVegetationSystemComponent.cpp index 00849ed94b..17174fa132 100644 --- a/Gems/Vegetation/Code/Source/Editor/EditorVegetationSystemComponent.cpp +++ b/Gems/Vegetation/Code/Source/Editor/EditorVegetationSystemComponent.cpp @@ -58,14 +58,11 @@ namespace Vegetation void EditorVegetationSystemComponent::Activate() { // This is necessary for the m_spawnerType in Descriptor.cpp to display properly as a ComboBox - m_propertyHandler = aznew AzToolsFramework::GenericComboBoxHandler(); - AzToolsFramework::PropertyTypeRegistrationMessages::Bus::Broadcast(&AzToolsFramework::PropertyTypeRegistrationMessages::RegisterPropertyType, m_propertyHandler); + AzToolsFramework::RegisterGenericComboBoxHandler(); } void EditorVegetationSystemComponent::Deactivate() { - AzToolsFramework::PropertyTypeRegistrationMessages::Bus::Broadcast(&AzToolsFramework::PropertyTypeRegistrationMessages::UnregisterPropertyType, m_propertyHandler); - delete m_propertyHandler; } } diff --git a/Gems/Vegetation/Code/Source/Editor/EditorVegetationSystemComponent.h b/Gems/Vegetation/Code/Source/Editor/EditorVegetationSystemComponent.h index 76ac881f7c..2b45303672 100644 --- a/Gems/Vegetation/Code/Source/Editor/EditorVegetationSystemComponent.h +++ b/Gems/Vegetation/Code/Source/Editor/EditorVegetationSystemComponent.h @@ -35,9 +35,6 @@ namespace Vegetation void Activate() override; void Deactivate() override; - - private: - AzToolsFramework::PropertyHandlerBase* m_propertyHandler{ nullptr }; }; } // namespace Vegetation From 3defbce31b42452f8cd598acdce37f95472fb0ed Mon Sep 17 00:00:00 2001 From: bosnichd Date: Tue, 11 May 2021 09:31:02 -0600 Subject: [PATCH 044/100] Remove legacy serialization and QPropertyTree (#684) Remove: - CryCommon/CryExtension/* - CryCommon/Serialization/* - Sandbox/Plugins/EditorCommon/QPropertyTree/* - All related CryCommon interfaces - All CrySystem implementations - Various related Editor classes --- Code/CryEngine/CryCommon/AnimTime.h | 173 - Code/CryEngine/CryCommon/Bezier.h | 321 -- .../CryExtension/CryCreateClassInstance.h | 96 - .../CryCommon/CryExtension/CryGUID.h | 123 - .../CryCommon/CryExtension/CryTypeID.h | 29 - .../CryCommon/CryExtension/ICryFactory.h | 41 - .../CryExtension/ICryFactoryRegistry.h | 56 - .../CryCommon/CryExtension/ICryUnknown.h | 224 -- .../CryCommon/CryExtension/Impl/ClassWeaver.h | 461 --- .../CryCommon/CryExtension/Impl/Conversion.h | 109 - .../CryExtension/Impl/CryGUIDHelper.h | 67 - .../Impl/ICryFactoryRegistryImpl.h | 58 - .../CryExtension/Impl/RegFactoryNode.h | 52 - .../CryCommon/CryExtension/Impl/TypeList.h | 236 -- Code/CryEngine/CryCommon/CryPool/Allocator.h | 207 -- Code/CryEngine/CryCommon/CryPool/Container.h | 655 ---- Code/CryEngine/CryCommon/CryPool/Defrag.h | 65 - Code/CryEngine/CryCommon/CryPool/Fallback.h | 81 - Code/CryEngine/CryCommon/CryPool/Inspector.h | 203 -- Code/CryEngine/CryCommon/CryPool/List.h | 366 -- Code/CryEngine/CryCommon/CryPool/Memory.h | 70 - Code/CryEngine/CryCommon/CryPool/PoolAlloc.h | 55 - Code/CryEngine/CryCommon/CryPool/STLWrapper.h | 148 - Code/CryEngine/CryCommon/CryPool/ThreadSafe.h | 58 - Code/CryEngine/CryCommon/CryPool/example.h | 287 -- .../CryEngine/CryCommon/GeomCacheFileFormat.h | 202 -- Code/CryEngine/CryCommon/IEngineModule.h | 53 - Code/CryEngine/CryCommon/IRemoteCommand.h | 763 ---- Code/CryEngine/CryCommon/IServiceNetwork.h | 344 -- Code/CryEngine/CryCommon/ISystem.h | 22 - Code/CryEngine/CryCommon/Mocks/IConsoleMock.h | 1 - Code/CryEngine/CryCommon/Mocks/ISystemMock.h | 8 - .../CryCommon/Serialization/Assert.h | 46 - .../CryCommon/Serialization/BitVector.h | 39 - .../CryCommon/Serialization/BitVectorImpl.h | 88 - .../CryCommon/Serialization/BlackBox.h | 93 - .../CryCommon/Serialization/BoostSharedPtr.h | 102 - .../CryCommon/Serialization/CRCRef.h | 30 - .../CryCommon/Serialization/CRCRefImpl.h | 100 - .../CryCommon/Serialization/Callback.h | 184 - .../CryCommon/Serialization/ClassFactory.h | 376 -- .../Serialization/ClassFactoryImpl.h | 47 - .../CryEngine/CryCommon/Serialization/Color.h | 55 - .../CryCommon/Serialization/ColorImpl.h | 53 - .../CryCommon/Serialization/CryExtension.h | 44 - .../Serialization/CryExtensionImpl.h | 281 -- .../CryCommon/Serialization/CryName.h | 26 - .../CryCommon/Serialization/CryNameImpl.h | 61 - .../CryCommon/Serialization/CryStrings.h | 36 - .../CryCommon/Serialization/CryStringsImpl.h | 74 - .../Serialization/Decorators/ActionButton.h | 89 - .../Serialization/Decorators/BitFlags.h | 64 - .../Serialization/Decorators/BitFlagsImpl.h | 67 - .../Serialization/Decorators/ColorPicker.h | 43 - .../Decorators/ColorPickerImpl.h | 33 - .../Serialization/Decorators/JointName.h | 19 - .../Serialization/Decorators/JointNameImpl.h | 19 - .../Serialization/Decorators/LocalFrame.h | 117 - .../Serialization/Decorators/LocalFrameImpl.h | 89 - .../Serialization/Decorators/OutputFilePath.h | 49 - .../Decorators/OutputFilePathImpl.h | 32 - .../Serialization/Decorators/Range.h | 63 - .../Serialization/Decorators/RangeImpl.h | 50 - .../Decorators/ResourceFilePath.h | 59 - .../Decorators/ResourceFilePathImpl.h | 32 - .../Decorators/ResourceFolderPath.h | 43 - .../Decorators/ResourceFolderPathImpl.h | 34 - .../Decorators/ResourceSelector.h | 100 - .../Serialization/Decorators/Resources.h | 67 - .../Serialization/Decorators/ResourcesAudio.h | 31 - .../Serialization/Decorators/ResourcesImpl.h | 44 - .../Serialization/Decorators/Slider.h | 88 - .../Serialization/Decorators/SliderImpl.h | 47 - .../Serialization/Decorators/Sprite.h | 44 - .../Serialization/Decorators/SpriteImpl.h | 35 - .../Serialization/Decorators/TagList.h | 49 - .../Serialization/Decorators/TagListImpl.h | 40 - .../CryCommon/Serialization/DynArray.h | 27 - .../CryCommon/Serialization/DynArrayImpl.h | 28 - Code/CryEngine/CryCommon/Serialization/Enum.h | 170 - .../CryCommon/Serialization/EnumImpl.h | 248 -- .../CryCommon/Serialization/IArchive.h | 446 --- .../CryCommon/Serialization/IArchiveHost.h | 153 - .../CryCommon/Serialization/IClassFactory.h | 85 - .../Serialization/ITextInputArchive.h | 46 - .../Serialization/ITextOutputArchive.h | 55 - .../CryCommon/Serialization/IXmlArchive.h | 175 - .../Serialization/IntrusiveFactory.h | 99 - .../CryCommon/Serialization/KeyValue.h | 37 - Code/CryEngine/CryCommon/Serialization/Math.h | 166 - .../CryCommon/Serialization/MathImpl.h | 207 -- .../Serialization/NetScriptSerialize.h | 27 - .../CryCommon/Serialization/Object.h | 153 - Code/CryEngine/CryCommon/Serialization/STL.h | 52 - .../CryCommon/Serialization/STLImpl.h | 251 -- .../CryCommon/Serialization/Serializer.h | 268 -- .../CryCommon/Serialization/SerializerImpl.h | 95 - .../CryCommon/Serialization/SmartPtr.h | 31 - .../CryCommon/Serialization/SmartPtrImpl.h | 73 - .../CryCommon/Serialization/StringList.h | 301 -- .../CryCommon/Serialization/StringListImpl.h | 126 - .../CryCommon/Serialization/Strings.h | 32 - .../CryCommon/Serialization/TypeID.h | 290 -- .../CryCommon/Serialization/TypeInfo.h | 46 - .../CryCommon/Serialization/TypeInfoImpl.h | 245 -- .../CryEngine/CryCommon/crycommon_files.cmake | 100 - Code/CryEngine/CryCommon/platform_impl.cpp | 16 +- Code/CryEngine/CrySystem/DllMain.cpp | 9 +- .../CryFactoryRegistryImpl.cpp | 359 -- .../ExtensionSystem/CryFactoryRegistryImpl.h | 128 - .../TestCases/TestExtensions.cpp | 955 ----- .../TestCases/TestExtensions.h | 126 - Code/CryEngine/CrySystem/RemoteCommand.cpp | 191 - Code/CryEngine/CrySystem/RemoteCommand.h | 459 --- .../CrySystem/RemoteCommandClient.cpp | 756 ---- .../CrySystem/RemoteCommandHelpers.cpp | 361 -- .../CrySystem/RemoteCommandHelpers.h | 307 -- .../CrySystem/RemoteCommandServer.cpp | 832 ----- .../CrySystem/Serialization/ArchiveHost.cpp | 239 -- .../CrySystem/Serialization/ArchiveHost.h | 21 - .../CrySystem/Serialization/BinArchive.cpp | 839 ----- .../CrySystem/Serialization/BinArchive.h | 180 - .../CrySystem/Serialization/JSONIArchive.cpp | 1525 -------- .../CrySystem/Serialization/JSONIArchive.h | 95 - .../CrySystem/Serialization/JSONOArchive.cpp | 828 ----- .../CrySystem/Serialization/JSONOArchive.h | 102 - .../CrySystem/Serialization/MemoryReader.cpp | 92 - .../CrySystem/Serialization/MemoryReader.h | 56 - .../CrySystem/Serialization/MemoryWriter.cpp | 236 -- .../CrySystem/Serialization/MemoryWriter.h | 72 - .../Serialization/Test_ArchiveHost.cpp | 492 --- .../CryEngine/CrySystem/Serialization/Token.h | 89 - .../CrySystem/Serialization/XmlIArchive.cpp | 297 -- .../CrySystem/Serialization/XmlIArchive.h | 62 - .../CrySystem/Serialization/XmlOArchive.cpp | 213 -- .../CrySystem/Serialization/XmlOArchive.h | 60 - Code/CryEngine/CrySystem/ServiceNetwork.cpp | 2035 ----------- Code/CryEngine/CrySystem/ServiceNetwork.h | 475 --- Code/CryEngine/CrySystem/System.cpp | 5 - Code/CryEngine/CrySystem/System.h | 9 - Code/CryEngine/CrySystem/SystemInit.cpp | 172 - Code/CryEngine/CrySystem/XConsole.cpp | 1 - .../CryEngine/CrySystem/crysystem_files.cmake | 29 - .../CrySystem/crysystem_test_files.cmake | 1 - .../Editor/Controls/CurveEditorCtrl.cpp | 821 ----- .../Sandbox/Editor/Controls/CurveEditorCtrl.h | 112 - Code/Sandbox/Editor/EditorViewportWidget.cpp | 8 - Code/Sandbox/Editor/IEditorImpl.cpp | 3 - .../Editor/Include/IResourceSelectorHost.h | 26 - Code/Sandbox/Editor/ResourceSelectorHost.cpp | 10 - Code/Sandbox/Editor/Serialization.h | 26 - .../Editor/Serialization/VariableIArchive.cpp | 283 -- .../Editor/Serialization/VariableIArchive.h | 71 - .../Editor/Serialization/VariableOArchive.cpp | 416 --- .../Editor/Serialization/VariableOArchive.h | 83 - Code/Sandbox/Editor/SettingsBlock.cpp | 177 - Code/Sandbox/Editor/SettingsBlock.h | 76 - Code/Sandbox/Editor/editor_lib_files.cmake | 9 - .../ComponentEntityEditorPlugin.cpp | 1 - .../Plugins/EditorCommon/BatchFileDialog.cpp | 357 -- .../Plugins/EditorCommon/BatchFileDialog.h | 77 - .../Plugins/EditorCommon/CMakeLists.txt | 3 - .../Plugins/EditorCommon/CurveEditor.cpp | 2459 ------------- .../Plugins/EditorCommon/CurveEditor.h | 233 -- .../Plugins/EditorCommon/CurveEditorContent.h | 155 - .../EditorCommon/CurveEditorContent_38.h | 84 - .../EditorCommon/CurveEditorContent_impl.h | 20 - .../EditorCommon/CurveEditorControl.cpp | 352 -- .../Plugins/EditorCommon/CurveEditorControl.h | 150 - .../Plugins/EditorCommon/CurveEditor_38.cpp | 1825 ---------- .../Plugins/EditorCommon/CurveEditor_38.h | 154 - .../EditorCommon/DisplayViewportAdapter.cpp | 194 -- .../EditorCommon/DisplayViewportAdapter.h | 64 - .../EditorCommon/DockTitleBarWidget.cpp | 17 +- .../EditorCommon/DrawingPrimitives/Ruler.cpp | 6 +- .../Plugins/EditorCommon/EditorCommon.qrc | 15 - .../EditorCommon/Events/EventManager.cpp | 144 - .../EditorCommon/Events/EventManager.h | 204 -- .../EditorCommon/ListSelectionDialog.cpp | 224 -- .../EditorCommon/ListSelectionDialog.h | 73 - .../QPropertyTree/Unicode_UnixLike.cpp | 29 - .../Platform/Linux/platform_linux_files.cmake | 14 - .../Platform/Mac/platform_mac_files.cmake | 14 - .../Windows/QPropertyTree/Unicode_Windows.cpp | 41 - .../Windows/platform_windows_files.cmake | 14 - .../QAbstractQVariantTreeDataModel.cpp | 75 - .../QAbstractQVariantTreeDataModel.h | 87 - .../Plugins/EditorCommon/QParentWndWidget.cpp | 309 -- .../Plugins/EditorCommon/QParentWndWidget.h | 67 - .../Plugins/EditorCommon/QPropertyCtrl.h | 49 - .../EditorCommon/QPropertyTree/Color.cpp | 123 - .../EditorCommon/QPropertyTree/Color.h | 66 - .../QPropertyTree/ConstStringList.cpp | 58 - .../QPropertyTree/ConstStringList.h | 46 - .../EditorCommon/QPropertyTree/ContextList.h | 76 - .../EditorCommon/QPropertyTree/Factory.h | 156 - .../EditorCommon/QPropertyTree/MathUtils.h | 54 - .../QPropertyTree/PropertyDrawContext.cpp | 466 --- .../QPropertyTree/PropertyDrawContext.h | 98 - .../QPropertyTree/PropertyIArchive.cpp | 377 -- .../QPropertyTree/PropertyIArchive.h | 80 - .../QPropertyTree/PropertyOArchive.cpp | 487 --- .../QPropertyTree/PropertyOArchive.h | 112 - .../QPropertyTree/PropertyRow.cpp | 1906 ---------- .../EditorCommon/QPropertyTree/PropertyRow.h | 575 --- .../QPropertyTree/PropertyRowActionButton.cpp | 168 - .../QPropertyTree/PropertyRowBool.cpp | 116 - .../QPropertyTree/PropertyRowBool.h | 50 - .../QPropertyTree/PropertyRowColor.cpp | 241 -- .../QPropertyTree/PropertyRowColor.h | 75 - .../QPropertyTree/PropertyRowColorPicker.cpp | 158 - .../QPropertyTree/PropertyRowColorPicker.h | 56 - .../QPropertyTree/PropertyRowContainer.cpp | 439 --- .../QPropertyTree/PropertyRowContainer.h | 96 - .../QPropertyTree/PropertyRowField.cpp | 84 - .../QPropertyTree/PropertyRowField.h | 39 - .../QPropertyTree/PropertyRowIconXPM.cpp | 119 - .../QPropertyTree/PropertyRowImpl.h | 48 - .../QPropertyTree/PropertyRowLocalFrame.cpp | 152 - .../QPropertyTree/PropertyRowLocalFrame.h | 70 - .../QPropertyTree/PropertyRowNumber.cpp | 43 - .../QPropertyTree/PropertyRowNumber.h | 237 -- .../QPropertyTree/PropertyRowNumberField.cpp | 287 -- .../QPropertyTree/PropertyRowNumberField.h | 75 - .../QPropertyTree/PropertyRowObject.cpp | 42 - .../QPropertyTree/PropertyRowObject.h | 51 - .../PropertyRowOutputFilePath.cpp | 205 -- .../QPropertyTree/PropertyRowOutputFilePath.h | 74 - .../QPropertyTree/PropertyRowPointer.cpp | 346 -- .../QPropertyTree/PropertyRowPointer.h | 95 - .../PropertyRowResourceFilePath.cpp | 177 - .../PropertyRowResourceFilePath.h | 79 - .../PropertyRowResourceFolderPath.cpp | 159 - .../PropertyRowResourceFolderPath.h | 76 - .../PropertyRowResourceSelector.cpp | 425 --- .../PropertyRowResourceSelector.h | 100 - .../QPropertyTree/PropertyRowSlider.cpp | 521 --- .../QPropertyTree/PropertyRowSprite.cpp | 299 -- .../QPropertyTree/PropertyRowSprite.h | 70 - .../QPropertyTree/PropertyRowString.cpp | 87 - .../QPropertyTree/PropertyRowString.h | 114 - .../PropertyRowStringListValue.cpp | 42 - .../PropertyRowStringListValue.h | 303 -- .../QPropertyTree/PropertyRowTagList.cpp | 132 - .../QPropertyTree/PropertyRowTagList.h | 51 - .../QPropertyTree/PropertyRowToggleButton.cpp | 205 -- .../QPropertyTree/PropertyTreeMenuHandler.h | 45 - .../QPropertyTree/PropertyTreeModel.cpp | 445 --- .../QPropertyTree/PropertyTreeModel.h | 208 -- .../QPropertyTree/PropertyTreeOperator.cpp | 53 - .../QPropertyTree/PropertyTreeOperator.h | 65 - .../QPropertyTree/QPropertyDialog.cpp | 227 -- .../QPropertyTree/QPropertyDialog.h | 76 - .../QPropertyTree/QPropertyTree.cpp | 3083 ----------------- .../QPropertyTree/QPropertyTree.h | 528 --- .../QPropertyTree/QPropertyTreeStyle.h | 90 - .../QPropertyTree/Serialization.h | 29 - .../EditorCommon/QPropertyTree/SlicerEdit.cpp | 56 - .../EditorCommon/QPropertyTree/SlicerEdit.h | 46 - .../QPropertyTree/SlicerManipulator.cpp | 143 - .../QPropertyTree/SlicerManipulator.h | 58 - .../EditorCommon/QPropertyTree/SlicerView.cpp | 25 - .../EditorCommon/QPropertyTree/SlicerView.h | 34 - .../QPropertyTree/SpriteBorderEditor.cpp | 175 - .../QPropertyTree/SpriteBorderEditor.h | 41 - .../SpriteBorderEditorCommon.cpp | 120 - .../QPropertyTree/SpriteBorderEditorCommon.h | 78 - .../EditorCommon/QPropertyTree/Strings.h | 29 - .../EditorCommon/QPropertyTree/Unicode.h | 24 - .../QPropertyTree/ValidatorBlock.h | 172 - .../EditorCommon/QPropertyTree/error.xpm | 126 - .../EditorCommon/QPropertyTree/file_open.xpm | 142 - .../EditorCommon/QPropertyTree/file_save.xpm | 168 - .../EditorCommon/QPropertyTree/gear.xpm | 24 - .../QPropertyTree/wWidgets_NOTICES.txt | 49 - .../EditorCommon/QPropertyTree/warning.xpm | 134 - .../Plugins/EditorCommon/QViewport.cpp | 913 ----- Code/Sandbox/Plugins/EditorCommon/QViewport.h | 193 -- .../Plugins/EditorCommon/QViewportConsumer.h | 37 - .../Plugins/EditorCommon/QViewportEvents.h | 96 - .../Plugins/EditorCommon/QViewportSettings.h | 269 -- .../Plugins/EditorCommon/Serialization.cpp | 15 - .../Plugins/EditorCommon/Serialization.h | 44 - .../EditorCommon/Serialization/BinArchive.cpp | 839 ----- .../EditorCommon/Serialization/BinArchive.h | 183 - .../Decorators/EditorActionButton.h | 76 - .../Serialization/Decorators/IGizmoSink.h | 49 - .../Decorators/INavigationProvider.h | 43 - .../Serialization/Decorators/IconXPM.h | 100 - .../Serialization/Decorators/ToggleButton.h | 50 - .../Decorators/ToggleButtonImpl.h | 44 - .../Serialization/JSONIArchive.cpp | 1522 -------- .../EditorCommon/Serialization/JSONIArchive.h | 103 - .../Serialization/JSONOArchive.cpp | 828 ----- .../EditorCommon/Serialization/JSONOArchive.h | 108 - .../Serialization/MemoryReader.cpp | 92 - .../EditorCommon/Serialization/MemoryReader.h | 62 - .../Serialization/MemoryWriter.cpp | 275 -- .../EditorCommon/Serialization/MemoryWriter.h | 80 - .../EditorCommon/Serialization/Pointers.h | 265 -- .../EditorCommon/Serialization/PointersImpl.h | 140 - .../Plugins/EditorCommon/Serialization/Qt.cpp | 393 --- .../Plugins/EditorCommon/Serialization/Qt.h | 33 - .../EditorCommon/Serialization/QtImpl.h | 24 - .../EditorCommon/Serialization/Token.h | 93 - .../Serialization/yasli_NOTICES.txt | 49 - .../Sandbox/Plugins/EditorCommon/Timeline.cpp | 2728 --------------- Code/Sandbox/Plugins/EditorCommon/Timeline.h | 216 -- .../Plugins/EditorCommon/TimelineContent.cpp | 20 - .../Plugins/EditorCommon/TimelineContent.h | 154 - .../EditorCommon/UnsavedChangesDialog.cpp | 117 - .../EditorCommon/UnsavedChangesDialog.h | 42 - .../EditorCommon/editorcommon_files.cmake | 132 - Code/Sandbox/Plugins/EditorCommon/moc.cpp | 21 - .../Android/AudioEngineWwise_Traits_Android.h | 1 - .../Linux/AudioEngineWwise_Traits_Linux.h | 1 - .../Mac/AudioEngineWwise_Traits_Mac.h | 1 - .../Windows/AudioEngineWwise_Traits_Windows.h | 1 - .../iOS/AudioEngineWwise_Traits_iOS.h | 1 - .../AudioEngineWwiseGemSystemComponent.cpp | 11 - .../Source/Editor/AudioSystemEditor_wwise.h | 11 - .../Source/Engine/AudioSystemImpl_wwise.cpp | 7 - .../Code/Source/Engine/Common_wwise.h | 14 - .../Code/Include/Editor/IAudioConnection.h | 6 - .../Code/Source/Editor/AudioControl.h | 1 + .../Source/Editor/AudioResourceSelectors.cpp | 1 - .../Code/Source/Editor/ConnectionsWidget.ui | 28 - .../Code/Source/Editor/QConnectionsWidget.cpp | 17 - Gems/GameEffectSystem/preview.png | 3 - Gems/LyShine/Code/Editor/ViewportWidget.cpp | 1 - .../Code/Source/Cinematics/CryMovie.cpp | 79 - .../Code/Source/Cinematics/CryMovie.def | 3 - .../Maestro/Code/Source/Cinematics/CryMovie.h | 40 - .../Code/Source/Cinematics/CryMovie.rc | 111 - Gems/SVOGI/preview.png | 3 - .../ConsoleFrontendConfig.in | 1 - .../Windows/package_filelists/atom.json | 1 - .../commit_validation/pal_allowedlist.txt | 1 - 338 files changed, 16 insertions(+), 63358 deletions(-) delete mode 100644 Code/CryEngine/CryCommon/AnimTime.h delete mode 100644 Code/CryEngine/CryCommon/Bezier.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/CryCreateClassInstance.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/CryGUID.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/CryTypeID.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/ICryFactory.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/ICryFactoryRegistry.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/ICryUnknown.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/Impl/ClassWeaver.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/Impl/Conversion.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/Impl/CryGUIDHelper.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/Impl/ICryFactoryRegistryImpl.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/Impl/RegFactoryNode.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/Impl/TypeList.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/Allocator.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/Container.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/Defrag.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/Fallback.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/Inspector.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/List.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/Memory.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/PoolAlloc.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/STLWrapper.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/ThreadSafe.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/example.h delete mode 100644 Code/CryEngine/CryCommon/GeomCacheFileFormat.h delete mode 100644 Code/CryEngine/CryCommon/IEngineModule.h delete mode 100644 Code/CryEngine/CryCommon/IRemoteCommand.h delete mode 100644 Code/CryEngine/CryCommon/IServiceNetwork.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Assert.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/BitVector.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/BitVectorImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/BlackBox.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/BoostSharedPtr.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/CRCRef.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/CRCRefImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Callback.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/ClassFactory.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/ClassFactoryImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Color.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/ColorImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/CryExtension.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/CryExtensionImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/CryName.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/CryNameImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/CryStrings.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/CryStringsImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ActionButton.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/BitFlags.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/BitFlagsImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ColorPicker.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ColorPickerImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/JointName.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/JointNameImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/LocalFrame.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/LocalFrameImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/OutputFilePath.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/OutputFilePathImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/Range.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/RangeImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFilePath.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFilePathImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFolderPath.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFolderPathImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ResourceSelector.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/Resources.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ResourcesAudio.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ResourcesImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/Slider.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/SliderImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/Sprite.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/SpriteImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/TagList.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/TagListImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/DynArray.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/DynArrayImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Enum.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/EnumImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/IArchive.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/IArchiveHost.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/IClassFactory.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/ITextInputArchive.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/ITextOutputArchive.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/IXmlArchive.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/IntrusiveFactory.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/KeyValue.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Math.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/MathImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/NetScriptSerialize.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Object.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/STL.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/STLImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Serializer.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/SerializerImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/SmartPtr.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/SmartPtrImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/StringList.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/StringListImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Strings.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/TypeID.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/TypeInfo.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/TypeInfoImpl.h delete mode 100644 Code/CryEngine/CrySystem/ExtensionSystem/CryFactoryRegistryImpl.cpp delete mode 100644 Code/CryEngine/CrySystem/ExtensionSystem/CryFactoryRegistryImpl.h delete mode 100644 Code/CryEngine/CrySystem/ExtensionSystem/TestCases/TestExtensions.cpp delete mode 100644 Code/CryEngine/CrySystem/ExtensionSystem/TestCases/TestExtensions.h delete mode 100644 Code/CryEngine/CrySystem/RemoteCommand.cpp delete mode 100644 Code/CryEngine/CrySystem/RemoteCommand.h delete mode 100644 Code/CryEngine/CrySystem/RemoteCommandClient.cpp delete mode 100644 Code/CryEngine/CrySystem/RemoteCommandHelpers.cpp delete mode 100644 Code/CryEngine/CrySystem/RemoteCommandHelpers.h delete mode 100644 Code/CryEngine/CrySystem/RemoteCommandServer.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/ArchiveHost.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/ArchiveHost.h delete mode 100644 Code/CryEngine/CrySystem/Serialization/BinArchive.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/BinArchive.h delete mode 100644 Code/CryEngine/CrySystem/Serialization/JSONIArchive.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/JSONIArchive.h delete mode 100644 Code/CryEngine/CrySystem/Serialization/JSONOArchive.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/JSONOArchive.h delete mode 100644 Code/CryEngine/CrySystem/Serialization/MemoryReader.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/MemoryReader.h delete mode 100644 Code/CryEngine/CrySystem/Serialization/MemoryWriter.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/MemoryWriter.h delete mode 100644 Code/CryEngine/CrySystem/Serialization/Test_ArchiveHost.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/Token.h delete mode 100644 Code/CryEngine/CrySystem/Serialization/XmlIArchive.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/XmlIArchive.h delete mode 100644 Code/CryEngine/CrySystem/Serialization/XmlOArchive.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/XmlOArchive.h delete mode 100644 Code/CryEngine/CrySystem/ServiceNetwork.cpp delete mode 100644 Code/CryEngine/CrySystem/ServiceNetwork.h delete mode 100644 Code/Sandbox/Editor/Controls/CurveEditorCtrl.cpp delete mode 100644 Code/Sandbox/Editor/Controls/CurveEditorCtrl.h delete mode 100644 Code/Sandbox/Editor/Serialization.h delete mode 100644 Code/Sandbox/Editor/Serialization/VariableIArchive.cpp delete mode 100644 Code/Sandbox/Editor/Serialization/VariableIArchive.h delete mode 100644 Code/Sandbox/Editor/Serialization/VariableOArchive.cpp delete mode 100644 Code/Sandbox/Editor/Serialization/VariableOArchive.h delete mode 100644 Code/Sandbox/Editor/SettingsBlock.cpp delete mode 100644 Code/Sandbox/Editor/SettingsBlock.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/BatchFileDialog.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/BatchFileDialog.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditor.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditor.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditorContent.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditorContent_38.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditorContent_impl.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditorControl.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditorControl.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditor_38.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditor_38.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/DisplayViewportAdapter.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/DisplayViewportAdapter.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/EditorCommon.qrc delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Events/EventManager.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Events/EventManager.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/ListSelectionDialog.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/ListSelectionDialog.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Platform/Common/UnixLike/QPropertyTree/Unicode_UnixLike.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Platform/Linux/platform_linux_files.cmake delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Platform/Mac/platform_mac_files.cmake delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Platform/Windows/QPropertyTree/Unicode_Windows.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Platform/Windows/platform_windows_files.cmake delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QAbstractQVariantTreeDataModel.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QAbstractQVariantTreeDataModel.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QParentWndWidget.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QParentWndWidget.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyCtrl.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Color.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Color.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ConstStringList.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ConstStringList.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ContextList.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Factory.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/MathUtils.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyDrawContext.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyDrawContext.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyIArchive.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyIArchive.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyOArchive.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyOArchive.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRow.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRow.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowActionButton.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowBool.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowBool.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColor.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColor.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColorPicker.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColorPicker.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowContainer.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowContainer.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowField.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowField.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowIconXPM.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowImpl.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowLocalFrame.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowLocalFrame.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumber.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumber.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumberField.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumberField.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowObject.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowObject.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowOutputFilePath.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowOutputFilePath.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowPointer.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowPointer.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFilePath.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFilePath.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFolderPath.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFolderPath.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceSelector.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceSelector.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSlider.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSprite.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSprite.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowString.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowString.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowStringListValue.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowStringListValue.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowTagList.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowTagList.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowToggleButton.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeMenuHandler.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeModel.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeModel.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeOperator.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeOperator.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyDialog.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyDialog.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTree.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTree.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTreeStyle.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Serialization.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerEdit.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerEdit.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerManipulator.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerManipulator.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerView.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerView.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditor.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditor.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditorCommon.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditorCommon.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Strings.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Unicode.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ValidatorBlock.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/error.xpm delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/file_open.xpm delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/file_save.xpm delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/gear.xpm delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/wWidgets_NOTICES.txt delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/warning.xpm delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QViewport.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QViewport.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QViewportConsumer.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QViewportEvents.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QViewportSettings.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/BinArchive.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/BinArchive.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/EditorActionButton.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/IGizmoSink.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/INavigationProvider.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/IconXPM.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/ToggleButton.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/ToggleButtonImpl.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/JSONIArchive.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/JSONIArchive.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/JSONOArchive.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/JSONOArchive.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryReader.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryReader.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryWriter.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryWriter.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Pointers.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/PointersImpl.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Qt.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Qt.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/QtImpl.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Token.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/yasli_NOTICES.txt delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Timeline.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Timeline.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/TimelineContent.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/TimelineContent.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/UnsavedChangesDialog.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/UnsavedChangesDialog.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/moc.cpp delete mode 100644 Gems/GameEffectSystem/preview.png delete mode 100644 Gems/Maestro/Code/Source/Cinematics/CryMovie.cpp delete mode 100644 Gems/Maestro/Code/Source/Cinematics/CryMovie.def delete mode 100644 Gems/Maestro/Code/Source/Cinematics/CryMovie.h delete mode 100644 Gems/Maestro/Code/Source/Cinematics/CryMovie.rc delete mode 100644 Gems/SVOGI/preview.png diff --git a/Code/CryEngine/CryCommon/AnimTime.h b/Code/CryEngine/CryCommon/AnimTime.h deleted file mode 100644 index 8bd0b9d442..0000000000 --- a/Code/CryEngine/CryCommon/AnimTime.h +++ /dev/null @@ -1,173 +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 __animtime_h__ -#define __animtime_h__ - -#include -#include -#include - -struct SAnimTime -{ - static const uint numTicksPerSecond = 6000; - - // List of possible frame rates (dividers of 6000). Most commonly used ones first. - enum EFrameRate - { - // Common - eFrameRate_30fps, eFrameRate_60fps, eFrameRate_120fps, - - // Possible - eFrameRate_10fps, eFrameRate_12fps, eFrameRate_15fps, eFrameRate_24fps, - eFrameRate_25fps, eFrameRate_40fps, eFrameRate_48fps, eFrameRate_50fps, - eFrameRate_75fps, eFrameRate_80fps, eFrameRate_100fps, eFrameRate_125fps, - eFrameRate_150fps, eFrameRate_200fps, eFrameRate_240fps, eFrameRate_250fps, - eFrameRate_300fps, eFrameRate_375fps, eFrameRate_400fps, eFrameRate_500fps, - eFrameRate_600fps, eFrameRate_750fps, eFrameRate_1000fps, eFrameRate_1200fps, - eFrameRate_1500fps, eFrameRate_2000fps, eFrameRate_3000fps, eFrameRate_6000fps, - - eFrameRate_Num - }; - - SAnimTime() - : m_ticks(0) {} - explicit SAnimTime(int32 ticks) - : m_ticks(ticks) {} - explicit SAnimTime(float time) - : m_ticks(aznumeric_caster(std::lround(static_cast(time) * numTicksPerSecond))) {} - - static uint GetFrameRateValue(EFrameRate frameRate) - { - const uint frameRateValues[eFrameRate_Num] = - { - // Common - 30, 60, 120, - - // Possible - 10, 12, 15, 24, 25, 40, 48, 50, 75, 80, 100, 125, - 150, 200, 240, 250, 300, 375, 400, 500, 600, 750, - 1000, 1200, 1500, 2000, 3000, 6000 - }; - - return frameRateValues[frameRate]; - } - - static const char* GetFrameRateName(EFrameRate frameRate) - { - const char* frameRateNames[eFrameRate_Num] = - { - // Common - "30 fps", "60 fps", "120 fps", - - // Possible - "10 fps", "12 fps", "15 fps", "24 fps", - "25 fps", "40 fps", "48 fps", "50 fps", - "75 fps", "80 fps", "100 fps", "125 fps", - "150 fps", "200 fps", "240 fps", "250 fps", - "300 fps", "375 fps", "400 fps", "500 fps", - "600 fps", "750 fps", "1000 fps", "1200 fps", - "1500 fps", "2000 fps", "3000 fps", "6000 fps" - }; - - return frameRateNames[frameRate]; - } - - float ToFloat() const { return static_cast(m_ticks) / numTicksPerSecond; } - - void Serialize(Serialization::IArchive& ar) - { - ar(m_ticks, "ticks", "Ticks"); - } - - // Helper to serialize from ticks or old float time - void Serialize(XmlNodeRef keyNode, bool bLoading, const char* pName, const char* pLegacyName) - { - if (bLoading) - { - int32 ticks; - if (!keyNode->getAttr(pName, ticks)) - { - // Backwards compatibility - float time = 0.0f; - keyNode->getAttr(pLegacyName, time); - *this = SAnimTime(time); - } - else - { - m_ticks = ticks; - } - } - else if (m_ticks > 0) - { - keyNode->setAttr(pName, m_ticks); - } - } - - int32 GetTicks() const { return m_ticks; } - - static SAnimTime Min() { SAnimTime minTime; minTime.m_ticks = std::numeric_limits::lowest(); return minTime; } - static SAnimTime Max() { SAnimTime maxTime; maxTime.m_ticks = (std::numeric_limits::max)(); return maxTime; } - - SAnimTime operator-() const { return SAnimTime(-m_ticks); } - SAnimTime operator-(SAnimTime r) const { SAnimTime temp = *this; temp.m_ticks -= r.m_ticks; return temp; } - SAnimTime operator+(SAnimTime r) const { SAnimTime temp = *this; temp.m_ticks += r.m_ticks; return temp; } - SAnimTime operator*(SAnimTime r) const { SAnimTime temp = *this; temp.m_ticks *= r.m_ticks; return temp; } - SAnimTime operator/(SAnimTime r) const { SAnimTime temp; temp.m_ticks = static_cast((static_cast(m_ticks) * numTicksPerSecond) / r.m_ticks); return temp; } - SAnimTime operator%(SAnimTime r) const { SAnimTime temp = *this; temp.m_ticks %= r.m_ticks; return temp; } - SAnimTime operator*(float r) const { SAnimTime temp; temp.m_ticks = aznumeric_caster(std::lround(static_cast(m_ticks) * r)); return temp; } - SAnimTime operator/(float r) const { SAnimTime temp; temp.m_ticks = aznumeric_caster(std::lround(static_cast(m_ticks) / r)); return temp; } - SAnimTime& operator+=(SAnimTime r) { *this = *this + r; return *this; } - SAnimTime& operator-=(SAnimTime r) { *this = *this - r; return *this; } - SAnimTime& operator*=(SAnimTime r) { *this = *this * r; return *this; } - SAnimTime& operator/=(SAnimTime r) { *this = *this / r; return *this; } - SAnimTime& operator%=(SAnimTime r) { *this = *this % r; return *this; } - SAnimTime& operator*=(float r) { *this = *this * r; return *this; } - SAnimTime& operator/=(float r) { *this = *this / r; return *this; } - - bool operator<(SAnimTime r) const { return m_ticks < r.m_ticks; } - bool operator<=(SAnimTime r) const { return m_ticks <= r.m_ticks; } - bool operator>(SAnimTime r) const { return m_ticks > r.m_ticks; } - bool operator>=(SAnimTime r) const { return m_ticks >= r.m_ticks; } - bool operator==(SAnimTime r) const { return m_ticks == r.m_ticks; } - bool operator!=(SAnimTime r) const { return m_ticks != r.m_ticks; } - - // Snap to nearest multiple of given frame rate - SAnimTime SnapToNearest(const EFrameRate frameRate) - { - const int sign = sgn(m_ticks); - const int32 absTicks = abs(m_ticks); - - const int framesMod = numTicksPerSecond / GetFrameRateValue(frameRate); - const int32 remainder = absTicks % framesMod; - const bool bNextMultiple = remainder >= (framesMod / 2); - return SAnimTime(sign * ((absTicks - remainder) + (bNextMultiple ? framesMod : 0))); - } - -private: - int32 m_ticks; - - friend bool Serialize(Serialization::IArchive& ar, SAnimTime& animTime, const char* name, const char* label); -}; - -inline bool Serialize(Serialization::IArchive& ar, SAnimTime& animTime, const char* name, const char* label) -{ - return ar(animTime.m_ticks, name, label); -} - -inline SAnimTime abs(SAnimTime time) -{ - return (time >= SAnimTime(0)) ? time : -time; -} - -#endif diff --git a/Code/CryEngine/CryCommon/Bezier.h b/Code/CryEngine/CryCommon/Bezier.h deleted file mode 100644 index fa1cf60d49..0000000000 --- a/Code/CryEngine/CryCommon/Bezier.h +++ /dev/null @@ -1,321 +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 __BEZIER_H__ -#define __BEZIER_H__ - -#include -#include -#include - -struct SBezierControlPoint -{ - SBezierControlPoint() - : m_value(0.0f) - , m_inTangent(ZERO) - , m_outTangent(ZERO) - , m_inTangentType(eTangentType_Auto) - , m_outTangentType(eTangentType_Auto) - , m_bBreakTangents(false) - { - } - - enum ETangentType - { - eTangentType_Custom, - eTangentType_Auto, - eTangentType_Zero, - eTangentType_Step, - eTangentType_Linear, - }; - - void Serialize(Serialization::IArchive& ar) - { - ar(m_value, "value", "Value"); - - if (ar.IsOutput()) - { - bool breakTangents = m_bBreakTangents; - ar(breakTangents, "breakTangents", "Break Tangents"); - } - else - { - bool breakTangents = false; - ar(breakTangents, "breakTangents", "Break Tangents"); - m_bBreakTangents = breakTangents; - } - - if (ar.IsOutput()) - { - ETangentType inTangentType = m_inTangentType; - ar(inTangentType, "inTangentType", "Incoming tangent type"); - } - else - { - ETangentType inTangentType = eTangentType_Auto; - ar(inTangentType, "inTangentType", "Incoming tangent type"); - m_inTangentType = inTangentType; - } - - ar(m_inTangent, "inTangent", (m_inTangentType == eTangentType_Custom) ? "Incoming Tangent" : NULL); - - if (ar.IsOutput()) - { - ETangentType outTangentType = m_outTangentType; - ar(outTangentType, "outTangentType", "Outgoing tangent type"); - } - else - { - ETangentType outTangentType = eTangentType_Auto; - ar(outTangentType, "outTangentType", "Outgoing tangent type"); - m_outTangentType = outTangentType; - } - - ar(m_outTangent, "outTangent", (m_outTangentType == eTangentType_Custom) ? "Outgoing Tangent" : NULL); - } - - float m_value; - - // For 1D Bezier only the Y component is used - Vec2 m_inTangent; - Vec2 m_outTangent; - - ETangentType m_inTangentType : 4; - ETangentType m_outTangentType : 4; - bool m_bBreakTangents : 1; -}; - -struct SBezierKey -{ - SBezierKey() - : m_time(0) {} - - void Serialize(Serialization::IArchive& ar) - { - ar(m_time, "time", "Time"); - ar(m_controlPoint, "controlPoint", "Control Point"); - } - - SAnimTime m_time; - SBezierControlPoint m_controlPoint; -}; - -namespace Bezier -{ - inline float Evaluate(float t, float p0, float p1, float p2, float p3) - { - const float a = 1 - t; - const float aSq = a * a; - const float tSq = t * t; - return (aSq * a * p0) + (3.0f * aSq * t * p1) + (3.0f * a * tSq * p2) + (tSq * t * p3); - } - - inline float EvaluateDeriv(float t, float p0, float p1, float p2, float p3) - { - const float a = 1 - t; - const float ta = t * a; - const float aSq = a * a; - const float tSq = t * t; - return 3.0f * ((-p2 * tSq) + (p3 * tSq) - (p0 * aSq) + (p1 * aSq) + 2.0f * ((-p1 * ta) + (p2 * ta))); - } - - inline float EvaluateX(const float t, const float duration, const SBezierControlPoint& start, const SBezierControlPoint& end) - { - const float p0 = 0.0f; - const float p1 = p0 + start.m_outTangent.x; - const float p3 = duration; - const float p2 = p3 + end.m_inTangent.x; - return Evaluate(t, p0, p1, p2, p3); - } - - inline float EvaluateY(const float t, const SBezierControlPoint& start, const SBezierControlPoint& end) - { - const float p0 = start.m_value; - const float p1 = p0 + start.m_outTangent.y; - const float p3 = end.m_value; - const float p2 = p3 + end.m_inTangent.y; - return Evaluate(t, p0, p1, p2, p3); - } - - // Duration = (time at end key) - (time at start key) - inline float EvaluateDerivX(const float t, const float duration, const SBezierControlPoint& start, const SBezierControlPoint& end) - { - const float p0 = 0.0f; - const float p1 = p0 + start.m_outTangent.x; - const float p3 = duration; - const float p2 = p3 + end.m_inTangent.x; - return EvaluateDeriv(t, p0, p1, p2, p3); - } - - inline float EvaluateDerivY(const float t, const SBezierControlPoint& start, const SBezierControlPoint& end) - { - const float p0 = start.m_value; - const float p1 = p0 + start.m_outTangent.y; - const float p3 = end.m_value; - const float p2 = p3 + end.m_inTangent.y; - return EvaluateDeriv(t, p0, p1, p2, p3); - } - - // Find interpolation factor where 2D bezier curve has the given x value. Works only for curves where x is monotonically increasing. - // The passed x must be in range [0, duration]. Uses the Newton-Raphson root finding method. Usually takes 2 or 3 iterations. - // - // Note: This is for "1D" 2D bezier curves as used in TrackView. The curves are restricted by the curve editor to be monotonically increasing. - // - inline float InterpolationFactorFromX(const float x, const float duration, const SBezierControlPoint& start, const SBezierControlPoint& end) - { - float t = (x / duration); - - const float epsilon = 0.00001f; - const uint maxSteps = 10; - - for (uint i = 0; i < maxSteps; ++i) - { - const float currentX = EvaluateX(t, duration, start, end) - x; - if (fabs(currentX) <= epsilon) - { - break; - } - - const float currentXDeriv = EvaluateDerivX(t, duration, start, end); - t -= currentX / currentXDeriv; - } - - return t; - } - - inline SBezierControlPoint CalculateInTangent( - float time, const SBezierControlPoint& point, - float leftTime, const SBezierControlPoint* pLeftPoint, - float rightTime, const SBezierControlPoint* pRightPoint) - { - SBezierControlPoint newPoint = point; - - // In tangent X can never be positive - newPoint.m_inTangent.x = std::min(point.m_inTangent.x, 0.0f); - - if (pLeftPoint) - { - switch (point.m_inTangentType) - { - case SBezierControlPoint::eTangentType_Custom: - { - // Need to clamp tangent if it is reaching over last point - const float deltaTime = time - leftTime; - if (deltaTime < -newPoint.m_inTangent.x) - { - if (newPoint.m_inTangent.x == 0) - { - newPoint.m_inTangent = Vec2(ZERO); - } - else - { - float scaleFactor = deltaTime / -newPoint.m_inTangent.x; - newPoint.m_inTangent.x = -deltaTime; - newPoint.m_inTangent.y *= scaleFactor; - } - } - } - break; - case SBezierControlPoint::eTangentType_Zero: - // Fall through. Zero for y is same as Auto, x is set to 0.0f - case SBezierControlPoint::eTangentType_Auto: - { - const SBezierControlPoint& rightPoint = pRightPoint ? *pRightPoint : point; - const float deltaTime = (pRightPoint ? rightTime : time) - leftTime; - if (deltaTime > 0.0f) - { - const float ratio = (time - leftTime) / deltaTime; - const float deltaValue = rightPoint.m_value - pLeftPoint->m_value; - const bool bIsZeroTangent = (point.m_inTangentType == SBezierControlPoint::eTangentType_Zero); - newPoint.m_inTangent = Vec2(-(deltaTime * ratio) / 3.0f, bIsZeroTangent ? 0.0f : -(deltaValue * ratio) / 3.0f); - } - else - { - newPoint.m_inTangent = Vec2(ZERO); - } - } - break; - case SBezierControlPoint::eTangentType_Linear: - newPoint.m_inTangent = Vec2((leftTime - time) / 3.0f, - (pLeftPoint->m_value - point.m_value) / 3.0f); - break; - } - } - - return newPoint; - } - - inline SBezierControlPoint CalculateOutTangent( - float time, const SBezierControlPoint& point, - float leftTime, const SBezierControlPoint* pLeftPoint, - float rightTime, const SBezierControlPoint* pRightPoint) - { - SBezierControlPoint newPoint = point; - - // Out tangent X can never be negative - newPoint.m_outTangent.x = std::max(point.m_outTangent.x, 0.0f); - - if (pRightPoint) - { - switch (point.m_outTangentType) - { - case SBezierControlPoint::eTangentType_Custom: - { - // Need to clamp tangent if it is reaching over next point - const float deltaTime = rightTime - time; - if (deltaTime < newPoint.m_outTangent.x) - { - if (newPoint.m_outTangent.x == 0) - { - newPoint.m_outTangent = Vec2(ZERO); - } - else - { - float scaleFactor = deltaTime / newPoint.m_outTangent.x; - newPoint.m_outTangent.x = deltaTime; - newPoint.m_outTangent.y *= scaleFactor; - } - } - } - break; - case SBezierControlPoint::eTangentType_Zero: - // Fall through. Zero for y is same as Auto, x is set to 0.0f - case SBezierControlPoint::eTangentType_Auto: - { - const SBezierControlPoint& leftPoint = pLeftPoint ? *pLeftPoint : point; - const float deltaTime = rightTime - (pLeftPoint ? leftTime : time); - if (deltaTime > 0.0f) - { - const float ratio = (rightTime - time) / deltaTime; - const float deltaValue = pRightPoint->m_value - leftPoint.m_value; - const bool bIsZeroTangent = (point.m_outTangentType == SBezierControlPoint::eTangentType_Zero); - newPoint.m_outTangent = Vec2((deltaTime * ratio) / 3.0f, bIsZeroTangent ? 0.0f : (deltaValue * ratio) / 3.0f); - } - else - { - newPoint.m_outTangent = Vec2(ZERO); - } - } - break; - case SBezierControlPoint::eTangentType_Linear: - newPoint.m_outTangent = Vec2((rightTime - time) / 3.0f, - (pRightPoint->m_value - point.m_value) / 3.0f); - break; - } - } - - return newPoint; - } -} - -#endif diff --git a/Code/CryEngine/CryCommon/CryExtension/CryCreateClassInstance.h b/Code/CryEngine/CryCommon/CryExtension/CryCreateClassInstance.h deleted file mode 100644 index 1d1a4805d4..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/CryCreateClassInstance.h +++ /dev/null @@ -1,96 +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 : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_CRYCREATECLASSINSTANCE_H -#define CRYINCLUDE_CRYEXTENSION_CRYCREATECLASSINSTANCE_H -#pragma once - - -#include "ICryUnknown.h" -#include "ICryFactory.h" -#include "ICryFactoryRegistry.h" -#include // <> required for Interfuscator - - -template -bool CryCreateClassInstance(const CryClassID& cid, AZStd::shared_ptr& p) -{ - p = AZStd::shared_ptr(); - ICryFactoryRegistry* pFactoryReg = gEnv->pSystem->GetCryFactoryRegistry(); - if (pFactoryReg) - { - ICryFactory* pFactory = pFactoryReg->GetFactory(cid); - if (pFactory && pFactory->ClassSupports(cryiidof())) - { - ICryUnknownPtr pUnk = pFactory->CreateClassInstance(); - AZStd::shared_ptr pT = cryinterface_cast(pUnk); - if (pT) - { - p = pT; - } - } - } - return p.get() != NULL; -} - - -template -bool CryCreateClassInstance(const char* cname, AZStd::shared_ptr& p) -{ - p = AZStd::shared_ptr(); - ICryFactoryRegistry* pFactoryReg = gEnv->pSystem->GetCryFactoryRegistry(); - if (pFactoryReg) - { - ICryFactory* pFactory = pFactoryReg->GetFactory(cname); - if (pFactory != NULL && pFactory->ClassSupports(cryiidof())) - { - ICryUnknownPtr pUnk = pFactory->CreateClassInstance(); - AZStd::shared_ptr pT = cryinterface_cast(pUnk); - if (pT) - { - p = pT; - } - } - } - return p.get() != NULL; -} - - -template -bool CryCreateClassInstanceForInterface(const CryInterfaceID& iid, AZStd::shared_ptr& p) -{ - p = AZStd::shared_ptr(); - ICryFactoryRegistry* pFactoryReg = gEnv->pSystem->GetCryFactoryRegistry(); - if (pFactoryReg) - { - size_t numFactories = 1; - ICryFactory* pFactory = 0; - pFactoryReg->IterateFactories(iid, &pFactory, numFactories); - if (numFactories == 1 && pFactory) - { - ICryUnknownPtr pUnk = pFactory->CreateClassInstance(); - AZStd::shared_ptr pT = cryinterface_cast(pUnk); - if (pT) - { - p = pT; - } - } - } - return p.get() != NULL; -} - - -#endif // CRYINCLUDE_CRYEXTENSION_CRYCREATECLASSINSTANCE_H diff --git a/Code/CryEngine/CryCommon/CryExtension/CryGUID.h b/Code/CryEngine/CryCommon/CryExtension/CryGUID.h deleted file mode 100644 index a779e91bd2..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/CryGUID.h +++ /dev/null @@ -1,123 +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 : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_CRYGUID_H -#define CRYINCLUDE_CRYEXTENSION_CRYGUID_H -#pragma once - -#include "Serialization/IArchive.h" -#include "Random.h" - -#include - -struct CryGUID -{ - uint64 hipart; - uint64 lopart; - - // !!! Do NOT turn CryGUID into a non-aggregate !!! - // It will prevent inlining and type list unrolling opportunities within - // cryinterface_cast() and cryiidof(). As such prevent constructors, - // non-public members, base classes and virtual functions! - - //CryGUID() : hipart(0), lopart(0) {} - //CryGUID(uint64 h, uint64 l) : hipart(h), lopart(l) {} - - static CryGUID Construct(const uint64& hipart, const uint64& lopart) - { - CryGUID guid = {hipart, lopart}; - return guid; - } - - static CryGUID Create() - { - uint64 lopart = 0; - uint64 hipart = 0; - while (lopart == 0 || hipart == 0) - { - const uint32 a = cry_random_uint32(); - const uint32 b = cry_random_uint32(); - const uint32 c = cry_random_uint32(); - const uint32 d = cry_random_uint32(); - lopart = (uint64)a | ((uint64)b << 32); - hipart = (uint64)c | ((uint64)d << 32); - } - - return Construct(lopart, hipart); - } - - static CryGUID Null() - { - return Construct(0, 0); - } - - bool operator ==(const CryGUID& rhs) const {return hipart == rhs.hipart && lopart == rhs.lopart; } - bool operator !=(const CryGUID& rhs) const {return hipart != rhs.hipart || lopart != rhs.lopart; } - bool operator <(const CryGUID& rhs) const {return hipart == rhs.hipart ? lopart < rhs.lopart : hipart < rhs.hipart; } - - void Serialize(Serialization::IArchive& ar) - { - if (ar.IsInput()) - { - uint32 dwords[4]; - ar(dwords, "guid"); - lopart = (((uint64)dwords[1]) << 32) | (uint64)dwords[0]; - hipart = (((uint64)dwords[3]) << 32) | (uint64)dwords[2]; - } - else - { - uint32 guid[4] = { - (uint32)(lopart & 0xFFFFFFFF), (uint32)((lopart >> 32) & 0xFFFFFFFF), - (uint32)(hipart & 0xFFFFFFFF), (uint32)((hipart >> 32) & 0xFFFFFFFF) - }; - ar(guid, "guid"); - } - } -}; - -// This is only used by the editor where we use C++ 11. -namespace std -{ - template<> - struct hash - { - public: - size_t operator()(const CryGUID& guid) const - { - std::hash hasher; - return hasher(guid.lopart) ^ hasher(guid.hipart); - } - }; -} - -namespace AZStd -{ - template<> - struct hash - { - public: - size_t operator()(const CryGUID& guid) const - { - std::hash hasher; - return hasher(guid); - } - }; -} - -#define MAKE_CRYGUID(high, low) CryGUID::Construct((uint64) high##LL, (uint64) low##LL) - - -#endif // CRYINCLUDE_CRYEXTENSION_CRYGUID_H diff --git a/Code/CryEngine/CryCommon/CryExtension/CryTypeID.h b/Code/CryEngine/CryCommon/CryExtension/CryTypeID.h deleted file mode 100644 index 16ae05b448..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/CryTypeID.h +++ /dev/null @@ -1,29 +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 : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_CRYTYPEID_H -#define CRYINCLUDE_CRYEXTENSION_CRYTYPEID_H -#pragma once - - -#include "CryGUID.h" - - -typedef CryGUID CryInterfaceID; -typedef CryGUID CryClassID; - - -#endif // CRYINCLUDE_CRYEXTENSION_CRYTYPEID_H diff --git a/Code/CryEngine/CryCommon/CryExtension/ICryFactory.h b/Code/CryEngine/CryCommon/CryExtension/ICryFactory.h deleted file mode 100644 index a1a7344198..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/ICryFactory.h +++ /dev/null @@ -1,41 +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 : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_ICRYFACTORY_H -#define CRYINCLUDE_CRYEXTENSION_ICRYFACTORY_H -#pragma once - - -#include "CryTypeID.h" -#include - -struct ICryUnknown; -DECLARE_SMART_POINTERS(ICryUnknown); - -struct ICryFactory -{ - virtual const char* GetName() const = 0; - virtual const CryClassID& GetClassID() const = 0; - virtual bool ClassSupports(const CryInterfaceID& iid) const = 0; - virtual void ClassSupports(const CryInterfaceID*& pIIDs, size_t& numIIDs) const = 0; - virtual ICryUnknownPtr CreateClassInstance() const = 0; - -protected: - // prevent explicit destruction from client side (delete, shared_ptr, etc) - virtual ~ICryFactory() {} -}; - -#endif // CRYINCLUDE_CRYEXTENSION_ICRYFACTORY_H diff --git a/Code/CryEngine/CryCommon/CryExtension/ICryFactoryRegistry.h b/Code/CryEngine/CryCommon/CryExtension/ICryFactoryRegistry.h deleted file mode 100644 index f97c0780a1..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/ICryFactoryRegistry.h +++ /dev/null @@ -1,56 +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 : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_ICRYFACTORYREGISTRY_H -#define CRYINCLUDE_CRYEXTENSION_ICRYFACTORYREGISTRY_H -#pragma once - - -#include "CryTypeID.h" - - -struct ICryFactory; - - -struct ICryFactoryRegistry -{ - virtual ICryFactory* GetFactory(const char* cname) const = 0; - virtual ICryFactory* GetFactory(const CryClassID& cid) const = 0; - /** - * Iterates all factories implementing the interface specified by \p iid. - * \param[in] iid ID of the interface to iterate. Often procured using cryiidof<...>(). - * \param[out] pFactories A pointer of the array of factories to fill in. May be nullptr (see below). - * \param[in] Size (in elements) of the pFactories array [out] Number of elements actually written to pFactories or, when pFactories is null, the number of elements that would be written if sufficient storage was available. - * - * Example: - * \code{.cpp} - * size_t factoryCount = 0; - * // Assigns the number of found factories to factoryCount - * factoryRegistry->IterateFactories(cryiidof(), 0, factoryCount); - * // Allocate an array of the proper length on the stack - * ICryFactory** factories = static_cast(alloca(sizeof(ICryFactory*) * factoryCount); - * // Fill in factories with factoryCount results. - * factoryRegistry->IterateFactories(cryiidof(), factories, factoryCount); - * \endcode - */ - virtual void IterateFactories(const CryInterfaceID& iid, ICryFactory** pFactories, size_t& numFactories) const = 0; - -protected: - // prevent explicit destruction from client side (delete, shared_ptr, etc) - virtual ~ICryFactoryRegistry() {} -}; - -#endif // CRYINCLUDE_CRYEXTENSION_ICRYFACTORYREGISTRY_H diff --git a/Code/CryEngine/CryCommon/CryExtension/ICryUnknown.h b/Code/CryEngine/CryCommon/CryExtension/ICryUnknown.h deleted file mode 100644 index 0de018305b..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/ICryUnknown.h +++ /dev/null @@ -1,224 +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 : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_ICRYUNKNOWN_H -#define CRYINCLUDE_CRYEXTENSION_ICRYUNKNOWN_H -#pragma once - - -#include "CryTypeID.h" -#include - - -struct ICryFactory; -struct ICryUnknown; - -namespace InterfaceCastSemantics -{ - template - const CryInterfaceID& cryiidof() - { - return T::IID(); - } - -#define _BEFRIEND_CRYIIDOF() \ - template \ - friend const CryInterfaceID&InterfaceCastSemantics::cryiidof(); - - - template - Dst* cryinterface_cast(Src* p) - { - return static_cast(p ? p->QueryInterface(cryiidof()) : 0); - } - - template - Dst* cryinterface_cast(const Src* p) - { - return static_cast(p ? p->QueryInterface(cryiidof()) : 0); - } - - namespace Internal - { - template - struct cryinterface_cast_shared_ptr_helper; - - template - struct cryinterface_cast_shared_ptr_helper - { - static AZStd::shared_ptr Op(const AZStd::shared_ptr& p) - { - Dst* dp = cryinterface_cast(p.get()); - return dp ? AZStd::shared_ptr(p, dp) : AZStd::shared_ptr(); - } - }; - - template - struct cryinterface_cast_shared_ptr_helper - { - static AZStd::shared_ptr Op(const AZStd::shared_ptr& p) - { - ICryUnknown* dp = cryinterface_cast(p.get()); - return dp ? AZStd::shared_ptr(*((const AZStd::shared_ptr*) & p), dp) : AZStd::shared_ptr(); - } - }; - - template - struct cryinterface_cast_shared_ptr_helper - { - static AZStd::shared_ptr Op(const AZStd::shared_ptr& p) - { - const ICryUnknown* dp = cryinterface_cast(p.get()); - return dp ? AZStd::shared_ptr(*((const AZStd::shared_ptr*) & p), dp) : AZStd::shared_ptr(); - } - }; - } // namespace Internal - - template - AZStd::shared_ptr cryinterface_cast(const AZStd::shared_ptr& p) - { - return Internal::cryinterface_cast_shared_ptr_helper::Op(p); - } - -#define _BEFRIEND_CRYINTERFACE_CAST() \ - template \ - friend Dst * InterfaceCastSemantics::cryinterface_cast(Src*); \ - template \ - friend Dst * InterfaceCastSemantics::cryinterface_cast(const Src*); \ - template \ - friend AZStd::shared_ptr InterfaceCastSemantics::cryinterface_cast(const AZStd::shared_ptr&); -} // namespace InterfaceCastSemantics - -using InterfaceCastSemantics::cryiidof; -using InterfaceCastSemantics::cryinterface_cast; - - -template -bool CryIsSameClassInstance(S* p0, T* p1) -{ - return static_cast(p0) == static_cast(p1) || cryinterface_cast(p0) == cryinterface_cast(p1); -} - -template -bool CryIsSameClassInstance(const AZStd::shared_ptr& p0, T* p1) -{ - return CryIsSameClassInstance(p0.get(), p1); -} - -template -bool CryIsSameClassInstance(S* p0, const AZStd::shared_ptr& p1) -{ - return CryIsSameClassInstance(p0, p1.get()); -} - -template -bool CryIsSameClassInstance(const AZStd::shared_ptr& p0, const AZStd::shared_ptr& p1) -{ - return CryIsSameClassInstance(p0.get(), p1.get()); -} - - -namespace CompositeQuerySemantics -{ - template - AZStd::shared_ptr crycomposite_query(Src* p, const char* name, bool* pExposed = 0) - { - void* pComposite = p ? p->QueryComposite(name) : 0; - pExposed ? *pExposed = pComposite != 0 : 0; - return pComposite ? *static_cast*>(pComposite) : AZStd::shared_ptr(); - } - - template - AZStd::shared_ptr crycomposite_query(const Src* p, const char* name, bool* pExposed = 0) - { - void* pComposite = p ? p->QueryComposite(name) : 0; - pExposed ? *pExposed = pComposite != 0 : 0; - return pComposite ? *static_cast*>(pComposite) : AZStd::shared_ptr(); - } - - template - AZStd::shared_ptr crycomposite_query(const AZStd::shared_ptr& p, const char* name, bool* pExposed = 0) - { - return crycomposite_query(p.get(), name, pExposed); - } - - template - AZStd::shared_ptr crycomposite_query(const AZStd::shared_ptr& p, const char* name, bool* pExposed = 0) - { - return crycomposite_query(p.get(), name, pExposed); - } - -#define _BEFRIEND_CRYCOMPOSITE_QUERY() \ - template \ - friend AZStd::shared_ptr CompositeQuerySemantics::crycomposite_query(Src*, const char*, bool*); \ - template \ - friend AZStd::shared_ptr CompositeQuerySemantics::crycomposite_query(const Src*, const char*, bool*); \ - template \ - friend AZStd::shared_ptr CompositeQuerySemantics::crycomposite_query(const AZStd::shared_ptr&, const char*, bool*); \ - template \ - friend AZStd::shared_ptr CompositeQuerySemantics::crycomposite_query(const AZStd::shared_ptr&, const char*, bool*); -} // namespace CompositeQuerySemantics - -using CompositeQuerySemantics::crycomposite_query; - - -#define _BEFRIEND_MAKE_SHARED() \ - template \ - friend class AZStd::Internal::sp_ms_deleter; \ - template \ - friend AZStd::shared_ptr AZStd::make_shared(); \ - template \ - friend AZStd::shared_ptr AZStd::allocate_shared(A const& a); - -// prevent explicit destruction from client side -#define _PROTECTED_DTOR(iname) \ -protected: \ - virtual ~iname() {} - - -// Befriending cryinterface_cast() and crycomposite_query() via CRYINTERFACE_DECLARE is actually only needed for ICryUnknown -// since QueryInterface() and QueryComposite() are usually not redeclared in derived interfaces but it doesn't hurt either -#define CRYINTERFACE_DECLARE(iname, iidHigh, iidLow) \ - _BEFRIEND_CRYIIDOF() \ - _BEFRIEND_CRYINTERFACE_CAST() \ - _BEFRIEND_CRYCOMPOSITE_QUERY() \ - _BEFRIEND_MAKE_SHARED() \ - _PROTECTED_DTOR(iname) \ - \ -private: \ - static const CryInterfaceID& IID() \ - { \ - static const CryInterfaceID iid = {(uint64) iidHigh##LL, (uint64) iidLow##LL}; \ - return iid; \ - } \ -public: - - -struct ICryUnknown -{ - CRYINTERFACE_DECLARE(ICryUnknown, 0x1000000010001000, 0x1000100000000000) - - virtual ICryFactory * GetFactory() const = 0; - -protected: - virtual void* QueryInterface(const CryInterfaceID& iid) const = 0; - virtual void* QueryComposite(const char* name) const = 0; -}; - -DECLARE_SMART_POINTERS(ICryUnknown); - - -#endif // CRYINCLUDE_CRYEXTENSION_ICRYUNKNOWN_H diff --git a/Code/CryEngine/CryCommon/CryExtension/Impl/ClassWeaver.h b/Code/CryEngine/CryCommon/CryExtension/Impl/ClassWeaver.h deleted file mode 100644 index c3b5bb340c..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/Impl/ClassWeaver.h +++ /dev/null @@ -1,461 +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 : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_IMPL_CLASSWEAVER_H -#define CRYINCLUDE_CRYEXTENSION_IMPL_CLASSWEAVER_H -#pragma once - -#include "TypeList.h" -#include "Conversion.h" -#include "RegFactoryNode.h" -#include "../ICryUnknown.h" -#include "../ICryFactory.h" -#include - -namespace CW -{ - namespace Internal - { - template - struct InterfaceCast; - - template - struct InterfaceCast - { - template - static void* Op(T* p) - { - return (Dst*) p; - } - }; - - template <> - struct InterfaceCast - { - template - static void* Op(T* p) - { - return const_cast(static_cast(static_cast(p))); - } - }; - } - - template - struct InterfaceCast; - - template <> - struct InterfaceCast - { - template - static void* Op(T*, const CryInterfaceID&) - { - return 0; - } - }; - - template - struct InterfaceCast > - { - template - static void* Op(T* p, const CryInterfaceID& iid) - { - if (cryiidof() == iid) - { - return Internal::InterfaceCast::Op(p); - } - return InterfaceCast::Op(p, iid); - } - }; - - template - struct FillIIDs; - - template <> - struct FillIIDs - { - static void Op(CryInterfaceID*) - { - } - }; - - template - struct FillIIDs > - { - static void Op(CryInterfaceID* p) - { - *p++ = cryiidof(); - FillIIDs::Op(p); - } - }; - - namespace Internal - { - template - struct PickList; - - template - struct PickList - { - typedef TL::BuildTypelist<>::Result Result; - }; - - template - struct PickList - { - typedef typename S::FullCompositeList Result; - }; - } - - template - struct ProbeFullCompositeList - { - private: - typedef char y[1]; - typedef char n[2]; - - template - static y& test(typename S::FullCompositeList*); - - template - static n& test(...); - - public: - enum - { - listFound = sizeof(test(0)) == sizeof(y) - }; - - typedef typename Internal::PickList::Result ListType; - }; - - namespace Internal - { - template - struct CompositeQuery; - - template <> - struct CompositeQuery - { - template - static void* Op(const T&, const char*) - { - return 0; - } - }; - - template - struct CompositeQuery > - { - template - static void* Op(const T& ref, const char* name) - { - void* p = ref.Head::CompositeQueryImpl(name); - return p ? p : CompositeQuery::Op(ref, name); - } - }; - } - - struct CompositeQuery - { - template - static void* Op(const T& ref, const char* name) - { - return Internal::CompositeQuery::ListType>::Op(ref, name); - } - }; - - inline bool NameMatch(const char* name, const char* compositeName) - { - if (!name || !compositeName) - { - return false; - } - size_t i = 0; - for (; name[i] && name[i] == compositeName[i]; ++i) - { - } - return name[i] == compositeName[i]; - } - - template - void* CheckCompositeMatch(const char* name, const AZStd::shared_ptr& composite, const char* compositeName) - { - typedef TC::SuperSubClass Rel; - COMPILE_TIME_ASSERT(Rel::exists); - return NameMatch(name, compositeName) ? const_cast(static_cast(&composite)) : 0; - } -} // namespace CW - - -#define CRYINTERFACE_BEGIN() \ -private: \ - typedef TL::BuildTypelist < ICryUnknown - -#define CRYINTERFACE_ADD(iname) , iname - -#define CRYINTERFACE_END() > ::Result _UserDefinedPartialInterfaceList; \ -protected: \ - typedef TL::NoDuplicates<_UserDefinedPartialInterfaceList>::Result FullInterfaceList; - -#define _CRY_TPL_APPEND0(base) TL::Append::Result -#define _CRY_TPL_APPEND(base, intermediate) TL::Append::Result - -#define CRYINTERFACE_ENDWITHBASE(base) > ::Result _UserDefinedPartialInterfaceList; \ -protected: \ - typedef TL::NoDuplicates<_CRY_TPL_APPEND0(base)>::Result FullInterfaceList; - -#define CRYINTERFACE_ENDWITHBASE2(base0, base1) > ::Result _UserDefinedPartialInterfaceList; \ -protected: \ - typedef TL::NoDuplicates<_CRY_TPL_APPEND(base0, _CRY_TPL_APPEND0(base1))>::Result FullInterfaceList; - -#define CRYINTERFACE_ENDWITHBASE3(base0, base1, base2) > ::Result _UserDefinedPartialInterfaceList; \ -protected: \ - typedef TL::NoDuplicates<_CRY_TPL_APPEND(base0, _CRY_TPL_APPEND(base1, _CRY_TPL_APPEND0(base2)))>::Result FullInterfaceList; - -#define CRYINTERFACE_SIMPLE(iname) \ - CRYINTERFACE_BEGIN() \ - CRYINTERFACE_ADD(iname) \ - CRYINTERFACE_END() - -#define CRYCOMPOSITE_BEGIN() \ -private: \ - void* CompositeQueryImpl(const char* name) const \ - { \ - (void)(name); \ - void* res = 0; (void)(res); \ - -#define CRYCOMPOSITE_ADD(member, membername) \ - COMPILE_TIME_ASSERT((sizeof(membername) / sizeof(membername[0])) > 1); \ - if ((res = CW::CheckCompositeMatch(name, member, membername)) != 0) { \ - return res; } - -#define _CRYCOMPOSITE_END(implclassname) \ - return 0; \ - }; \ -protected: \ - typedef TL::BuildTypelist::Result _PartialCompositeList; \ - \ - template \ - friend struct CW::Internal::PickList; - -#define CRYCOMPOSITE_END(implclassname) \ - _CRYCOMPOSITE_END(implclassname) \ -protected: \ - typedef _PartialCompositeList FullCompositeList; - -#define _CRYCOMPOSITE_APPEND0(base) TL::Append<_PartialCompositeList, CW::ProbeFullCompositeList::ListType>::Result -#define _CRYCOMPOSITE_APPEND(base, intermediate) TL::Append::ListType>::Result - -#define CRYCOMPOSITE_ENDWITHBASE(implclassname, base) \ - _CRYCOMPOSITE_END(implclassname) \ -protected: \ - typedef _CRYCOMPOSITE_APPEND0 (base) FullCompositeList; - -#define CRYCOMPOSITE_ENDWITHBASE2(implclassname, base0, base1) \ - _CRYCOMPOSITE_END(implclassname) \ -protected: \ - typedef TL::NoDuplicates<_CRYCOMPOSITE_APPEND(base1, _CRYCOMPOSITE_APPEND0(base0))>::Result FullCompositeList; - -#define CRYCOMPOSITE_ENDWITHBASE3(implclassname, base0, base1, base2) \ - _CRYCOMPOSITE_END(implclassname) \ -protected: \ - typedef TL::NoDuplicates<_CRYCOMPOSITE_APPEND(base2, _CRYCOMPOSITE_APPEND(base1, _CRYCOMPOSITE_APPEND0(base0)))>::Result FullCompositeList; - -template -class CFactory - : public ICryFactory -{ -public: - virtual const char* GetName() const - { - return T::GetCName(); - } - - virtual const CryClassID& GetClassID() const - { - return T::GetCID(); - } - - virtual bool ClassSupports(const CryInterfaceID& iid) const - { - for (size_t i = 0; i < m_numIIDs; ++i) - { - if (iid == m_pIIDs[i]) - { - return true; - } - } - return false; - } - - virtual void ClassSupports(const CryInterfaceID*& pIIDs, size_t& numIIDs) const - { - pIIDs = m_pIIDs; - numIIDs = m_numIIDs; - } -public: - virtual ICryUnknownPtr CreateClassInstance() const - { - AZStd::shared_ptr p = AZStd::make_shared(); - return cryinterface_cast (p); - } - - CFactory() - : m_numIIDs(0) - , m_pIIDs(0) - , m_regFactory() - { - static CryInterfaceID supportedIIDs[TL::Length < typename T::FullInterfaceList > ::value]; - CW::FillIIDs::Op(supportedIIDs); - m_pIIDs = &supportedIIDs[0]; - m_numIIDs = TL::Length::value; - new(&m_regFactory)SRegFactoryNode(this); - } - -protected: - CFactory(const CFactory&); - CFactory& operator =(const CFactory&); - - - size_t m_numIIDs; - CryInterfaceID* m_pIIDs; - SRegFactoryNode m_regFactory; -}; - -template -class CSingletonFactory - : public CFactory -{ -public: - CSingletonFactory() - : CFactory() - , m_csCreateClassInstance() - { - } - - virtual ICryUnknownPtr CreateClassInstance() const - { - CryAutoLock lock(m_csCreateClassInstance); - // override the allocator. These function static instances are being destroyed after the AZ alloctor has been deleted. - // On win, TerminateProcess() prevents these destructors from being called, but that is not the case on OSX. - static typename AZStd::aligned_storage,SingletonAllocator>), AZStd::alignment_of::value>::type m_storage; - static ICryUnknownPtr p = AZStd::allocate_shared(SingletonAllocator(AZStd::addressof(m_storage))); - return p; - } - - mutable CryCriticalSection m_csCreateClassInstance; - - struct SingletonAllocator - { - SingletonAllocator(void* ptr) : - m_data(ptr) - {} - void* allocate(size_t /*byteSize*/, size_t /*alignment*/, int /*flags*/ = 0) - { - return m_data; - } - void deallocate(void* /*ptr*/, size_t /*byteSize*/, size_t /*alignment*/) - { - // nothing to see here - } - void* m_data; - }; -}; - -#define _CRYFACTORY_DECLARE(implclassname) \ -private: \ - friend class CFactory; \ - static CFactory s_factory; - -#define _CRYFACTORY_DECLARE_SINGLETON(implclassname) \ -private: \ - friend class CFactory; \ - friend void* Get##implclassname##Factory(); \ - static CSingletonFactory s_factory; - -#define _IMPLEMENT_ICRYUNKNOWN() \ -public: \ - virtual ICryFactory* GetFactory() const \ - { \ - return &s_factory; \ - } \ - \ -protected: \ - virtual void* QueryInterface(const CryInterfaceID&iid) const \ - { \ - return CW::InterfaceCast::Op(this, iid); \ - } \ - \ - template \ - friend struct CW::Internal::CompositeQuery; \ - \ - virtual void* QueryComposite(const char* name) const \ - { \ - return CW::CompositeQuery::Op(*this, name); \ - } - -#define _ENFORCE_CRYFACTORY_USAGE(implclassname, cname, cidHigh, cidLow) \ -public: \ - static const char* GetCName() \ - { \ - return cname; \ - } \ - static const CryClassID& GetCID() \ - { \ - static const CryClassID cid = {(uint64) cidHigh##LL, (uint64) cidLow##LL}; \ - return cid; \ - } \ - static AZStd::shared_ptr CreateClassInstance() \ - { \ - ICryUnknownPtr p = s_factory.CreateClassInstance(); \ - return AZStd::shared_ptr(*static_cast*>(static_cast(&p))); \ - } \ - \ -protected: \ - implclassname(); \ - virtual ~implclassname(); - -#define _BEFRIEND_OPS() \ - _BEFRIEND_CRYINTERFACE_CAST() \ - _BEFRIEND_CRYCOMPOSITE_QUERY() \ - _BEFRIEND_MAKE_SHARED() - -#define CRYGENERATE_CLASS(implclassname, cname, cidHigh, cidLow) \ - _CRYFACTORY_DECLARE(implclassname) \ - _BEFRIEND_OPS() \ - _IMPLEMENT_ICRYUNKNOWN() \ - _ENFORCE_CRYFACTORY_USAGE(implclassname, cname, cidHigh, cidLow) - -#define CRYGENERATE_SINGLETONCLASS(implclassname, cname, cidHigh, cidLow) \ - _CRYFACTORY_DECLARE_SINGLETON(implclassname) \ - _BEFRIEND_OPS() \ - _IMPLEMENT_ICRYUNKNOWN() \ - _ENFORCE_CRYFACTORY_USAGE(implclassname, cname, cidHigh, cidLow) - - -#define CRYREGISTER_CLASS(implclassname) \ - CFactory implclassname::s_factory; - -#define DECLARE_CRYREGISTER_SINGLETON_CLASS(implclassname) \ - void* Get##implclassname##Factory(); - -#define CRYREGISTER_SINGLETON_CLASS(implclassname) \ - CSingletonFactory implclassname::s_factory; \ - void* Get##implclassname##Factory() { \ - return &implclassname::s_factory; \ - } - -#endif // CRYINCLUDE_CRYEXTENSION_IMPL_CLASSWEAVER_H diff --git a/Code/CryEngine/CryCommon/CryExtension/Impl/Conversion.h b/Code/CryEngine/CryCommon/CryExtension/Impl/Conversion.h deleted file mode 100644 index bd729f259e..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/Impl/Conversion.h +++ /dev/null @@ -1,109 +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 : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_IMPL_CONVERSION_H -#define CRYINCLUDE_CRYEXTENSION_IMPL_CONVERSION_H -#pragma once - - -namespace TC -{ - //template - //struct Conversion - //{ - //private: - // typedef char y[1]; - // typedef char n[2]; - // static y& Test(U); - // static n& Test(...); - // static T MakeT(); - - //public: - // enum - // { - // exists = sizeof(Test(MakeT())) == sizeof(y), - // sameType = false - // }; - //}; - - //template - //struct Conversion - //{ - //public: - // enum - // { - // exists = true, - // sameType = true - // }; - //}; - - //template - //struct CheckInheritance - //{ - // enum - // { - // exists = Conversion::exists && !Conversion::sameType - // }; - //}; - - //template - //struct CheckStrictInheritance - //{ - // enum - // { - // exists = CheckInheritance::exists && !Conversion::sameType - // }; - //}; - - - template - struct SuperSubClass - { - private: - typedef char y[1]; - typedef char n[2]; - - template - static y& check(const volatile Derived&, T); - static n& check(const volatile Base&, int); - - struct C - { - operator const volatile Base&() const; - operator const volatile Derived&(); - }; - - static C getC(); - - public: - enum - { - exists = sizeof(check(getC(), 0)) == sizeof(y), - sameType = false - }; - }; - - template - struct SuperSubClass - { - enum - { - exists = true - }; - }; -} // namespace TC - -#endif // CRYINCLUDE_CRYEXTENSION_IMPL_CONVERSION_H diff --git a/Code/CryEngine/CryCommon/CryExtension/Impl/CryGUIDHelper.h b/Code/CryEngine/CryCommon/CryExtension/Impl/CryGUIDHelper.h deleted file mode 100644 index 53ee4352fc..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/Impl/CryGUIDHelper.h +++ /dev/null @@ -1,67 +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 : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_IMPL_CRYGUIDHELPER_H -#define CRYINCLUDE_CRYEXTENSION_IMPL_CRYGUIDHELPER_H -#pragma once - - -#include "../CryGUID.h" -#include "../../CryString.h" - - -namespace CryGUIDHelper -{ - string Print(const CryGUID& val) - { - char buf[39]; // sizeof("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}") - - static const char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; - char* p = buf; - *p++ = '{'; - for (int i = 15; i >= 8; --i) - { - *p++ = hex[(unsigned char) ((val.hipart >> (i << 2)) & 0xF)]; - } - *p++ = '-'; - for (int i = 7; i >= 4; --i) - { - *p++ = hex[(unsigned char) ((val.hipart >> (i << 2)) & 0xF)]; - } - *p++ = '-'; - for (int i = 3; i >= 0; --i) - { - *p++ = hex[(unsigned char) ((val.hipart >> (i << 2)) & 0xF)]; - } - *p++ = '-'; - for (int i = 15; i >= 12; --i) - { - *p++ = hex[(unsigned char) ((val.lopart >> (i << 2)) & 0xF)]; - } - *p++ = '-'; - for (int i = 11; i >= 0; --i) - { - *p++ = hex[(unsigned char) ((val.lopart >> (i << 2)) & 0xF)]; - } - *p++ = '}'; - *p++ = '\0'; - - return string(buf); - } -} - - -#endif // CRYINCLUDE_CRYEXTENSION_IMPL_CRYGUIDHELPER_H diff --git a/Code/CryEngine/CryCommon/CryExtension/Impl/ICryFactoryRegistryImpl.h b/Code/CryEngine/CryCommon/CryExtension/Impl/ICryFactoryRegistryImpl.h deleted file mode 100644 index 051c33fc33..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/Impl/ICryFactoryRegistryImpl.h +++ /dev/null @@ -1,58 +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 : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_IMPL_ICRYFACTORYREGISTRYIMPL_H -#define CRYINCLUDE_CRYEXTENSION_IMPL_ICRYFACTORYREGISTRYIMPL_H -#pragma once - - -#include "../ICryFactoryRegistry.h" - - -struct SRegFactoryNode; - - -struct ICryFactoryRegistryCallback -{ - virtual void OnNotifyFactoryRegistered(ICryFactory* pFactory) = 0; - virtual void OnNotifyFactoryUnregistered(ICryFactory* pFactory) = 0; - -protected: - virtual ~ICryFactoryRegistryCallback() {} -}; - - -struct ICryFactoryRegistryImpl - : public ICryFactoryRegistry -{ - virtual ICryFactory* GetFactory(const char* cname) const = 0; - virtual ICryFactory* GetFactory(const CryClassID& cid) const = 0; - virtual void IterateFactories(const CryInterfaceID& iid, ICryFactory** pFactories, size_t& numFactories) const = 0; - - virtual void RegisterCallback(ICryFactoryRegistryCallback* pCallback) = 0; - virtual void UnregisterCallback(ICryFactoryRegistryCallback* pCallback) = 0; - - virtual void RegisterFactories(const SRegFactoryNode* pFactories) = 0; - virtual void UnregisterFactories(const SRegFactoryNode* pFactories) = 0; - - virtual void UnregisterFactory(ICryFactory* const pFactory) = 0; - -protected: - // prevent explicit destruction from client side (delete, shared_ptr, etc) - virtual ~ICryFactoryRegistryImpl() {} -}; - -#endif // CRYINCLUDE_CRYEXTENSION_IMPL_ICRYFACTORYREGISTRYIMPL_H diff --git a/Code/CryEngine/CryCommon/CryExtension/Impl/RegFactoryNode.h b/Code/CryEngine/CryCommon/CryExtension/Impl/RegFactoryNode.h deleted file mode 100644 index 8209ae9728..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/Impl/RegFactoryNode.h +++ /dev/null @@ -1,52 +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 : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_IMPL_REGFACTORYNODE_H -#define CRYINCLUDE_CRYEXTENSION_IMPL_REGFACTORYNODE_H -#pragma once - -struct ICryFactory; -struct SRegFactoryNode; - -extern SRegFactoryNode* g_pHeadToRegFactories; - -struct SRegFactoryNode -{ - SRegFactoryNode() - { - } - - SRegFactoryNode(ICryFactory* pFactory) - : m_pFactory(pFactory) - , m_pNext(g_pHeadToRegFactories) - { - g_pHeadToRegFactories = this; - } - - static void* operator new(size_t, void* p) - { - return p; - } - - static void operator delete(void*, void*) - { - } - - ICryFactory* m_pFactory; - SRegFactoryNode* m_pNext; -}; - -#endif // CRYINCLUDE_CRYEXTENSION_IMPL_REGFACTORYNODE_H diff --git a/Code/CryEngine/CryCommon/CryExtension/Impl/TypeList.h b/Code/CryEngine/CryCommon/CryExtension/Impl/TypeList.h deleted file mode 100644 index 231283fc19..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/Impl/TypeList.h +++ /dev/null @@ -1,236 +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 : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_TYPELIST_H -#define CRYINCLUDE_CRYEXTENSION_TYPELIST_H -#pragma once - - -namespace TL -{ - // typelist terminator - class NullType - { - }; - - - // structure for typelist generation - template - struct Typelist - { - typedef T Head; - typedef U Tail; - }; - - - // helper structure to automatically build typelists containing n types - template - < - typename T0 = NullType, typename T1 = NullType, typename T2 = NullType, typename T3 = NullType, typename T4 = NullType, - typename T5 = NullType, typename T6 = NullType, typename T7 = NullType, typename T8 = NullType, typename T9 = NullType, - typename T10 = NullType, typename T11 = NullType, typename T12 = NullType, typename T13 = NullType, typename T14 = NullType, - typename T15 = NullType, typename T16 = NullType, typename T17 = NullType, typename T18 = NullType, typename T19 = NullType - > - struct BuildTypelist - { - private: - typedef typename BuildTypelist::Result TailResult; - - public: - typedef Typelist Result; - }; - - template <> - struct BuildTypelist<> - { - typedef NullType Result; - }; - - // typelist operation : Length - template - struct Length; - - template <> - struct Length - { - enum - { - value = 0 - }; - }; - - template - struct Length > - { - enum - { - value = 1 + Length::value - }; - }; - - - // typelist operation : TypeAt - template - struct TypeAt; - - template - struct TypeAt, 0> - { - typedef Head Result; - }; - - template - struct TypeAt, index> - { - typedef typename TypeAt::Result Result; - }; - - - // typelist operation : IndexOf - template - struct IndexOf; - - template - struct IndexOf - { - enum - { - value = -1 - }; - }; - - template - struct IndexOf, T> - { - enum - { - value = 0 - }; - }; - - template - struct IndexOf, T> - { - private: - enum - { - temp = IndexOf::value - }; - public: - enum - { - value = temp == -1 ? -1 : 1 + temp - }; - }; - - - // typelist operation : Append - template - struct Append; - - template <> - struct Append - { - typedef NullType Result; - }; - - template - struct Append - { - typedef Typelist Result; - }; - - template - struct Append > - { - typedef Typelist Result; - }; - - template - struct Append, T> - { - typedef Typelist::Result> Result; - }; - - - // typelist operation : Erase - template - struct Erase; - - template - struct Erase - { - typedef NullType Result; - }; - - template - struct Erase, T> - { - typedef Tail Result; - }; - - template - struct Erase, T> - { - typedef Typelist::Result> Result; - }; - - - // typelist operation : Erase All - template - struct EraseAll; - - template - struct EraseAll - { - typedef NullType Result; - }; - - template - struct EraseAll, T> - { - typedef typename EraseAll::Result Result; - }; - - template - struct EraseAll, T> - { - typedef Typelist::Result> Result; - }; - - - // typelist operation : NoDuplicates - template - struct NoDuplicates; - - template <> - struct NoDuplicates - { - typedef NullType Result; - }; - - template - struct NoDuplicates > - { - private: - typedef typename NoDuplicates::Result L1; - typedef typename Erase::Result L2; - public: - typedef Typelist Result; - }; -} // namespace TL - -#endif // CRYINCLUDE_CRYEXTENSION_TYPELIST_H diff --git a/Code/CryEngine/CryCommon/CryPool/Allocator.h b/Code/CryEngine/CryCommon/CryPool/Allocator.h deleted file mode 100644 index cc751e68f1..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/Allocator.h +++ /dev/null @@ -1,207 +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_CRYPOOL_ALLOCATOR_H -#define CRYINCLUDE_CRYPOOL_ALLOCATOR_H -#pragma once - - -namespace NCryPoolAlloc -{ - template - class CFirstFit - : public TPool - { - public: - ILINE CFirstFit() - { - } - - template - ILINE T Allocate(size_t Size, size_t Align = 1) - { - //fastpath? - if (TPool::m_pEmpty && TPool::m_pEmpty->Available(Size, Align)) - { - TItem* pItem = TPool::Split(TPool::m_pEmpty, Size, Align); - if (!pItem) - { - return 0; - } - pItem->InUse(Align); - TPool::AllocatedMemory(pItem->MemSize()); - - //not fully occupied empty space? - TPool::m_pEmpty = pItem != TPool::m_pEmpty ? TPool::m_pEmpty : 0; - return TPool::Handle(pItem); - } - - TItem* pBestItem; - for (pBestItem = TPool::m_Items.First(); pBestItem; pBestItem = pBestItem->Next()) - { - if (pBestItem->Available(Size, Align)) // && (!pBestItem || pItem->MemSize()MemSize())) - { - break; - } - } - if (!pBestItem) - { - return 0; //out of mem - } - TItem* pItem = TPool::Split(pBestItem, Size, Align); - if (!pItem) //no free node - { - return 0; - } - pItem->InUse(Align); - TPool::AllocatedMemory(pItem->MemSize()); - - //not fully occupied empty space? - TPool::m_pEmpty = pItem != pBestItem ? pBestItem : 0; - return TPool::Handle(pItem); - } - template - ILINE bool Free(T Handle, bool ForceBoundsCheck = false) - { - return Handle ? TPool::Free(Handle, ForceBoundsCheck) : false; - } - }; - - template - class CWorstFit - : public TPool - { - public: - ILINE CWorstFit() - { - } - - template - ILINE T Allocate(size_t Size, size_t Align = 1) - { - TItem* pBestItem = 0; - for (TItem* pItem = TPool::m_Items.First(); pItem; pItem = pItem->Next()) - { - if (pItem->IsFree() && (!pBestItem || pItem->MemSize() > pBestItem->MemSize())) - { - pBestItem = pItem; - } - } - if (!pBestItem || !pBestItem->Available(Size, Align)) - { - return 0; //out of mem - } - TItem* pItem = Split(pBestItem, Size, Align); - if (!pItem) //no free node - { - return 0; - } - pItem->InUse(Align); - AllocatedMemory(pItem->MemSize()); - return Handle(pItem); - } - }; - - template - class CBestFit - : public TPool - { - public: - ILINE CBestFit() - { - } - - template - ILINE T Allocate(size_t Size, size_t Align = 1) - { - TItem* pBestItem = 0; - for (TItem* pItem = TPool::m_Items.First(); pItem; pItem = pItem->Next()) - { - if ((!pBestItem || pItem->MemSize() < pBestItem->MemSize()) && pItem->Available(Size, Align)) - { - if (pItem->MemSize() == Size) - { - pItem->InUse(Align); - AllocatedMemory(pItem->MemSize()); - return (T)Handle(pItem); - } - pBestItem = pItem; - } - } - if (!pBestItem) - { - return 0; //out of mem - } - TItem* pItem = Split(pBestItem, Size, Align); - if (!pItem) //no free node - { - return 0; - } - pItem->InUse(Align); - AllocatedMemory(pItem->MemSize()); - return (T)Handle(pItem); - } - }; - - - template - class CReallocator - : public TAllocator - { - public: - - template - ILINE bool Reallocate(T* pData, size_t Size, size_t Alignment) - { - //special cases - if (!Size) //just free? - { - TAllocator::Free(*pData); - *pData = 0; - return true; - } - - if (!*pData) //just alloc? - { - *pData = TAllocator::template Allocate(Size, Alignment); - return *pData != 0; - } - - //same size, nothing to do at all? - if (TAllocator::Item(*pData)->MemSize() == Size) - { - return true; - } - - if (TAllocator::ReSize(pData, Size)) - { - return true; - } - - T pNewData = TAllocator::template Allocate(Size, Alignment); - if (!pNewData) - { - return false; - } - memcpy(TAllocator::template Resolve(pNewData), - TAllocator::template Resolve(*pData), min(TAllocator::Item(*pData)->MemSize(), Size)); - TAllocator::template Free(*pData); - *pData = pNewData; - return true; - } - }; -} - - -#endif // CRYINCLUDE_CRYPOOL_ALLOCATOR_H - diff --git a/Code/CryEngine/CryCommon/CryPool/Container.h b/Code/CryEngine/CryCommon/CryPool/Container.h deleted file mode 100644 index 82ea2735bc..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/Container.h +++ /dev/null @@ -1,655 +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_CRYPOOL_CONTAINER_H -#define CRYINCLUDE_CRYPOOL_CONTAINER_H -#pragma once - - -namespace NCryPoolAlloc -{ - template - class CPool - : public CMemoryStatic - { - class CPoolNode; - class CPoolNode - : public CListItem - { - }; - CList m_List; - public: - ILINE CPool() - { - CPoolNode* pPrev = 0; - CPoolNode* pNode = 0; - for (size_t a = 1; a < TElementCount; a++) //skip first element as it would be counted as zero ptr - { - uint8* pData = &CMemoryStatic::Data()[a * sizeof(TElement)]; - pNode = reinterpret_cast(pData); - pNode->Prev(pPrev); - if (pPrev) - { - pPrev->Next(pNode); - } - else - { - m_List.First(pNode); - } - pPrev = pNode; - // m_List.AddLast(pNode); - } - if (pPrev) - { - pPrev->Next(0); - m_List.Last(pPrev); - } - } - ILINE uint8* Allocate([[maybe_unused]] size_t Size, [[maybe_unused]] size_t Align = 1) - { - CPoolNode* pNode = m_List.PopFirst(); - return reinterpret_cast(pNode); - } - - template - ILINE void Free(T* pData) - { - if (pData) - { - CPoolNode* pNode = reinterpret_cast(pData); - m_List.AddLast(pNode); - } - } - - ILINE TElement& operator[](uint32 Idx) - { - uint8* pData = &CMemoryStatic::Data()[Idx * sizeof(TElement)]; - return *reinterpret_cast(pData); - } - - ILINE const TElement& operator[](uint32 Idx) const - { - const uint8* pData = &CMemoryStatic::Data()[Idx * sizeof(TElement)]; - return *reinterpret_cast(pData); - } - }; - - template - class CInPlace - : public TMemory - { - protected: - CList m_Items; - size_t m_Allocated; - CListItemInPlace* m_pEmpty; - - - ILINE void AllocatedMemory(size_t S) - { - m_Allocated += S + sizeof(CListItemInPlace); - } - ILINE void FreedMemory(size_t S) - { - m_Allocated -= S + sizeof(CListItemInPlace); - } - ILINE void Stack(CListItemInPlace* pItem) - { - } - public: - ILINE CInPlace() - : m_Allocated(0) - { - } - - ILINE void InitMem(const size_t S = 0, uint8* pData = 0) - { - TMemory::InitMem(S, pData); - if (!TMemory::MemSize()) - { - return; - } - pData = TMemory::Data(); - CListItemInPlace* pFirst = reinterpret_cast(pData); - CListItemInPlace* pFree = pFirst + 1; - CListItemInPlace* pLast = reinterpret_cast(pData + TMemory::MemSize()) - 1; - m_Items.~CList(); - new (&m_Items)CList(); - m_Items.AddLast(pFirst); - m_Items.AddLast(pFree); - m_Items.AddLast(pLast); - - pFirst->InUse(0); //static first item - pFree->Free(); - pLast->InUse(0); //static last item - m_pEmpty = pFree; - m_Allocated = 0; - } - - ILINE size_t FragmentCount() const - { - return m_Items.Count(); - } - - ILINE CListItemInPlace* Split(CListItemInPlace* pItem, size_t Size, size_t Align) - { - size_t Offset = reinterpret_cast(pItem->Data()); - Offset += pItem->MemSize(); //ptr to end - Offset -= Size; //minus size - Size += Offset & (Align - 1); //adjust size to fit required alignment - Offset -= Offset & (Align - 1); - size_t TSize = sizeof(CListItemInPlace); - Offset -= TSize; //header - - if (Offset <= reinterpret_cast(pItem + 1)) //not enough space for splitting? - { - return pItem; - } - - CListItemInPlace* pItemNext = reinterpret_cast(Offset); - - const size_t Offset2 = reinterpret_cast(pItemNext->Data()); - CPA_ASSERT(!(Offset2 & (Align - 1))); - m_Items.AddBehind(pItemNext, pItem); - //pItemNext->Prev(pItem); - //pItemNext->Next(pItem->Next()); - - // if(pItem->Next()) - // pItem->Next()->Prev(pItemNext); - - // pItem->Next(pItemNext); - pItemNext->Free(); - return pItemNext; - } - - ILINE void Merge(CListItemInPlace* pItem) - { - //merge with next if possible - CListItemInPlace* pItemNext = pItem->Next(); - if (pItemNext->IsFree()) - { - if (m_pEmpty == pItemNext) - { - m_pEmpty = pItem; - } - m_Items.Remove(pItemNext); - //pItem->Next(pItemNext->Next()); - //pItem->Next()->Prev(pItem); - } - //merge with prev if possible - CListItemInPlace* pItemPrev = pItem->Prev(); - if (pItemPrev->IsFree()) - { - if (m_pEmpty == pItem) - { - m_pEmpty = pItemPrev; - } - m_Items.Remove(pItem); - //pItemPrev->Next(pItem->Next()); - //pItem->Next()->Prev(pItemPrev); - pItem = pItemPrev; - } - } - template - ILINE T Resolve(void* rItem) const - { - return reinterpret_cast(rItem); - } - - template - ILINE size_t Size(const T* pData) const - { - const CListItemInPlace* pItem = Item(pData); - return pItem->MemSize(); - } - - bool InBounds(const void* pData, const bool Check) const - { - return !Check || ( - reinterpret_cast(pData) >= reinterpret_cast(TMemory::Data()) && - reinterpret_cast(pData) < reinterpret_cast(TMemory::Data()) + TMemory::MemSize()); - } - - template - ILINE bool Free(T* pData, bool ForceBoundsCheck = false) - { - if (pData && InBounds(pData, BoundsCheck | ForceBoundsCheck)) - { - CListItemInPlace* pItem = Item(pData); - FreedMemory(pItem->MemSize()); - pItem->Free(); - Merge(pItem); - return true; - } - return false; - } - - ILINE bool Beat(){return false; }//dummy beat in case no defragmentator is wraping - ILINE size_t MemFree() const{return TMemory::MemSize() - m_Allocated; } - ILINE size_t MemSize() const{return TMemory::MemSize(); } - - ILINE uint8* Handle(CListItemInPlace* pItem) const - { - return pItem->Data(); - } - template - ILINE CListItemInPlace* Item(T* pData) - { - return reinterpret_cast(pData) - 1; - } - template - ILINE const CListItemInPlace* Item(const T* pData) const - { - return reinterpret_cast(pData) - 1; - } - ILINE static bool Defragmentable(){return false; } - - template - ILINE bool ReSize(T* pData, size_t SizeNew) - { - //special cases - CListItemInPlace* pItem = Item(*pData); - const size_t SizeOld = pItem->MemSize(); - - //reduction - if (SizeOld > SizeNew) - { - if (pItem->Next()->IsFree()) - { - CListItemInPlace* pNextNext = pItem->Next()->Next(); - size_t Offset = reinterpret_cast(pItem->Data()); - Offset += SizeNew; //Offset to next - CListItemInPlace* pItemNext = reinterpret_cast(Offset); - pItem->Next(pItemNext); - pNextNext->Prev(pItemNext); - pItemNext->Prev(pItem); - pItemNext->Next(pNextNext); - pItemNext->Free(); - return true; - } - - if (SizeOld - SizeNew <= sizeof(CListItemInPlace)) - { - return true; //header is bigger than the amount of freed memory - } - //split - size_t Offset = reinterpret_cast(pItem->Data()); - Offset += SizeNew; //Offset to next - CListItemInPlace* pItemNext = reinterpret_cast(Offset); - m_Items.AddBehind(pItemNext, pItem); - pItemNext->Free(); - return true; - } - - //SizeOldNext(); - CListItemInPlace* pNextNext = pNext->Next(); - const size_t SizeNext = pNext->IsFree() ? pNext->MemSize() + sizeof(CListItemInPlace) : 0; - if (SizeNew <= SizeNext + SizeOld) - { - if (SizeNew + sizeof(CListItemInPlace) + 1 < SizeNext + SizeOld) - { - size_t Offset = reinterpret_cast(pItem->Data()); - Offset += SizeNew; //Offset to next - CListItemInPlace* pItemNext = reinterpret_cast(Offset); - pItem->Next(pItemNext); - pNextNext->Prev(pItemNext); - pItemNext->Prev(pItem); - pItemNext->Next(pNextNext); - pItemNext->Free(); - } - else - { - pItem->Next(pNextNext); - pNextNext->Prev(pItem); - } - return true; - } - return false; //no further in-place realloc possible - } - }; - - template - class CReferenced - : public TMemory - { - typedef CPool tdNodePool; - - protected: - tdNodePool m_NodePool; - CList m_Items; - size_t m_Allocated; - CListItemReference* m_pEmpty; - - ILINE void AllocatedMemory(size_t S) - { - m_Allocated += S; - } - ILINE void FreedMemory(size_t S) - { - m_Allocated -= S; - } - ILINE void Stack(CListItemReference* pItem) - { - m_Items.Validate(pItem); - CListItemReference* pItem2 = 0; - CListItemReference* pNext = pItem->Next(); - uint8* pData = pItem->Data(pNext->Align()); - if (pData != pItem->Data()) //needs splitting 'cause of alignment? - { - pItem2 = reinterpret_cast(m_NodePool.Allocate(1, 1)); - if (!pItem2) //no free node found for splitting? - { - return; //failed to stack -> return - } - } - - memmove(pData, pNext->Data(), pNext->MemSize()); - - if (pItem2) //was not aligned? - { - //then keep the current ITem - const size_t SizeItem = pItem->MemSize(); - const size_t SizeNext = pNext->MemSize(); - m_Items.AddBehind(pItem2, pNext); - pItem2->Data(pData + SizeNext); - pNext->Data(pData); - pItem2->MemSize(pItem2->Next()->Data() - pItem2->Data()); - pNext->MemSize(SizeNext); - pItem->MemSize(pNext->Data() - pItem->Data()); - m_Items.Validate(pItem); - m_Items.Validate(pItem2); - m_Items.Validate(pNext); - } - else - { - const size_t SizeItem = pItem->MemSize(); - const size_t SizeNext = pNext->MemSize(); - m_Items.Remove(pItem); - m_Items.AddBehind(pItem, pNext); - pItem->Data(pNext->Data()); - pNext->Data(pData); - pNext->MemSize(SizeItem); - pItem->MemSize(SizeNext); - m_Items.Validate(pItem); - m_Items.Validate(pNext); - } - } - public: - ILINE CReferenced() - : m_Allocated(0) - { - } - - ILINE void InitMem(const size_t S = 0, uint8* pData = 0) - { - TMemory::InitMem(S, pData); - if (!TMemory::MemSize()) - { - return; - } - pData = TMemory::Data(); - CListItemReference* pItem = reinterpret_cast(m_NodePool.Allocate(1, 1)); - CListItemReference* pLast = reinterpret_cast(m_NodePool.Allocate(1, 1)); - m_Items.AddFirst(pItem); - m_Items.AddLast(pLast); - pLast->Init(pData + TMemory::MemSize(), 0, pItem, 0); - pLast->InUse(0); - pItem->Init(pData, TMemory::MemSize(), 0, pLast); - pItem->Free(); - m_pEmpty = pItem; - m_Allocated = 0; - } - - ILINE size_t FragmentCount() const - { - return m_Items.Count(); - } - - ILINE CListItemReference* Split(CListItemReference* pItem, size_t Size, size_t Align) - { - size_t Offset = reinterpret_cast(pItem->Data()); - if (!(Offset & (Align - 1))) //perfectly aligned? - { - if (pItem->MemSize() != Size) //not perfectly fitting? - { //then split - CListItemReference* pItemPrev = reinterpret_cast(m_NodePool.Allocate(1, 1)); - if (!pItemPrev) - { - return 0; - } - const size_t OrgSize = pItem->MemSize(); - m_Items.AddBefore(pItemPrev, pItem); - pItemPrev->Data(pItem->Data()); - pItem->Data(pItem->Data() + Size); - pItem->MemSize(OrgSize - Size); - pItemPrev->MemSize(Size); - pItem = pItemPrev; - } - return pItem; - } - - //not aligned to block start - //then lets try to align to block end - Offset += pItem->MemSize(); //ptr to end - Offset -= Size; //minus size - if (!(Offset & (Align - 1))) //perfectly aligned? - { - CListItemReference* pItemPrev = reinterpret_cast(m_NodePool.Allocate(1, 1)); - if (!pItemPrev) - { - return 0; - } - const size_t OrgSize = pItem->MemSize(); - m_Items.AddBefore(pItemPrev, pItem); - pItemPrev->Data(pItem->Data()); - pItem->Data(reinterpret_cast(Offset)); - pItemPrev->MemSize(OrgSize - Size); - pItem->MemSize(Size); - pItemPrev->Free(); - return pItem; - } - //last resort, fragment it into 3 parts - - //Size +=Offset&(Align-1); //adjust size to fit required alignment - Offset -= Offset & (Align - 1); - - CListItemReference* pItemPrev = reinterpret_cast(m_NodePool.Allocate(1, 1)); - CListItemReference* pItemNext = reinterpret_cast(m_NodePool.Allocate(1, 1)); - if (!pItemPrev || !pItemNext) - { - return 0; - } - const size_t OrgSize = pItem->MemSize(); - - m_Items.AddBefore(pItemPrev, pItem); - m_Items.AddBehind(pItemNext, pItem); - - pItemPrev->Data(pItem->Data()); - pItem->Data(reinterpret_cast(Offset)); - pItemNext->Data(pItem->Data() + Size); - pItemPrev->MemSize(pItem->Data() - pItemPrev->Data()); - pItemNext->MemSize(OrgSize - pItemPrev->MemSize() - Size); - pItem->MemSize(Size); - - pItemPrev->Free(); - pItemNext->Free(); - return pItem; - } - - ILINE void Merge(CListItemReference* pItem) - { - m_Items.Validate(pItem); - - //merge with next if possible - CListItemReference* pItemNext = pItem->Next(); - if (pItemNext && pItemNext->IsFree()) - { - if (m_pEmpty == pItemNext) - { - m_pEmpty = pItem; - } - const size_t OrgSize = pItem->MemSize(); - const size_t NextSize = pItemNext->MemSize(); - m_Items.Remove(pItemNext); - pItem->MemSize(OrgSize + NextSize); - m_NodePool.Free(pItemNext); - } - //merge with prev if possible - CListItemReference* pItemPrev = pItem->Prev(); - if (pItemPrev && pItemPrev->IsFree()) - { - if (m_pEmpty == pItem) - { - m_pEmpty = pItemPrev; - } - const size_t OrgSize = pItem->MemSize(); - const size_t PrevSize = pItemPrev->MemSize(); - m_Items.Remove(pItem); - pItemPrev->MemSize(PrevSize + OrgSize); - m_NodePool.Free(pItem); - } - } - - template - ILINE T Resolve(const uint32 ID) - { - CPA_ASSERT(ID); //0 is invalid - return reinterpret_cast(Item(ID)->Data()); - } - - ILINE uint32 AddressToHandle(void* pData) - { - for (CListItemReference* pItem = m_Items.First(); pItem; pItem = pItem->Next()) - { - if (pItem->Data() == pData) - { - return Handle(pItem); - } - } - return 0; - } - - template - ILINE size_t Size(T ID) const - { - CPA_ASSERT(ID); //0 is invalid - return Item(ID)->MemSize(); - } - template - bool InBounds([[maybe_unused]] T ID, [[maybe_unused]] const bool Check) const - { - //boundscheck doesn't work for Referenced containers - return true; - } - - template - ILINE bool Free(T ID, bool ForceBoundsCheck = false) - { - IF (!ID, false) - { - return true; - } - IF (!InBounds(ID, BoundsCheck | ForceBoundsCheck), false) - { - return false; - } - - CListItemReference* pItem = Item(ID); - FreedMemory(pItem->MemSize()); - pItem->Free(); - Merge(pItem); - return true; - } - - ILINE bool Beat(){return false; }//dummy beat in case no defragmentator is wraping - - ILINE size_t MemFree() const{return TMemory::MemSize() - m_Allocated; } - - ILINE size_t MemSize() const{return TMemory::MemSize(); } - - ILINE uint32 Handle(CListItemReference* pItem) const - { - return static_cast(pItem - &m_NodePool[0]); - } - ILINE CListItemReference* Item(uint32 ID) - { - return &m_NodePool[ID]; - } - ILINE const CListItemReference* Item(uint32 ID) const - { - return &m_NodePool[ID]; - } - ILINE static bool Defragmentable(){return true; } - - - - template - ILINE bool ReSize(T* pData, size_t SizeNew) - { - CListItemReference* pItem = Item(*pData); - const size_t SizeOld = pItem->MemSize(); - - //reduction - if (SizeOld > SizeNew) - { - if (pItem->Next()->IsFree()) - { - CListItemReference* pNext = pItem->Next(); - const size_t NextSize = pNext->MemSize(); - pNext->Data(pNext->Data() + SizeNew - SizeOld); - pNext->MemSize(NextSize - SizeNew + SizeOld); - pItem->MemSize(SizeNew); - return true; - } - - //split - CListItemReference* pItemNext = reinterpret_cast(m_NodePool.Allocate(1, 1)); - m_Items.AddBehind(pItemNext, pItem); - pItemNext->Data(pItem->Data() + SizeNew); - pItem->MemSize(SizeNew); - pItemNext->MemSize(SizeOld - SizeNew); - pItemNext->Free(); - return true; - } - - //SizeOldNext(); - const size_t SizeNext = pNext->IsFree() ? pNext->MemSize() : 0; - if (SizeNew <= SizeNext + SizeOld) - { - if (SizeNew == SizeNext + SizeOld) - { - m_Items.Remove(pNext); - m_NodePool.Free(pNext); - } - else - { - pNext->Data(pNext->Data() + SizeNew - SizeOld); - pNext->MemSize(SizeNext - SizeNew + SizeOld); - } - pItem->MemSize(SizeNew); - return true; - } - return false; //no further in-place realloc possible - } - }; -} - - - - - - - -#endif // CRYINCLUDE_CRYPOOL_CONTAINER_H - diff --git a/Code/CryEngine/CryCommon/CryPool/Defrag.h b/Code/CryEngine/CryCommon/CryPool/Defrag.h deleted file mode 100644 index 51fe6fabfb..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/Defrag.h +++ /dev/null @@ -1,65 +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_CRYPOOL_DEFRAG_H -#define CRYINCLUDE_CRYPOOL_DEFRAG_H -#pragma once - - -namespace NCryPoolAlloc -{ - template - class CDefragStacked - : public T - { - template - ILINE bool DefragElement(TItem* pItem) - { - T::m_Items.Validate(); - if (pItem) - { - for (; pItem->Next(); pItem = pItem->Next()) - { - if (!pItem->IsFree()) - { - continue; - } - if (pItem->Next()->Locked()) - { - continue; - } - if (!pItem->Available(pItem->Next()->Align(), pItem->Next()->Align())) - { - continue; - } - T::m_Items.Validate(pItem); - Stack(pItem); - T::m_Items.Validate(pItem); - Merge(pItem); - T::m_Items.Validate(); - return true; - } - } - return false; - } - public: - ILINE bool Beat() - { - return T::Defragmentable() && DefragElement(T::m_Items.First()); - }; - }; -} - - -#endif // CRYINCLUDE_CRYPOOL_DEFRAG_H - diff --git a/Code/CryEngine/CryCommon/CryPool/Fallback.h b/Code/CryEngine/CryCommon/CryPool/Fallback.h deleted file mode 100644 index 4a2babce1a..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/Fallback.h +++ /dev/null @@ -1,81 +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_CRYPOOL_FALLBACK_H -#define CRYINCLUDE_CRYPOOL_FALLBACK_H -#pragma once - - -namespace NCryPoolAlloc -{ - enum EFallbackMode - { - EFM_DISABLED, - EFM_ENABLED, - EFM_ALWAYS - }; - template - class CFallback - : public TAllocator - { - EFallbackMode m_Fallback; - public: - ILINE CFallback() - : m_Fallback(EFM_DISABLED) - { - } - - template - ILINE T Allocate(size_t Size, size_t Align = 1) - { - if (EFM_ALWAYS == m_Fallback) - { - return reinterpret_cast(CPA_ALLOC(Align, Size)); - } - T pRet = TAllocator::template Allocate(Size, Align); - if (!pRet && EFM_ENABLED == m_Fallback) - { - return reinterpret_cast(CPA_ALLOC(Align, Size)); - } - return pRet; - } - - template - ILINE bool Free(T Handle) - { - if (!Handle) - { - return true; - } - if (EFM_ALWAYS == m_Fallback) - { - CPA_FREE(Handle); - return true; - } - - if (EFM_ENABLED == m_Fallback && TAllocator::InBounds(Handle, true)) - { - CPA_FREE(Handle); - return true; - } - return TAllocator::template Free(Handle); - } - - void FallbackMode(EFallbackMode M){m_Fallback = M; } - EFallbackMode FallbaclMode() const{return m_Fallback; } - }; -} - - -#endif // CRYINCLUDE_CRYPOOL_FALLBACK_H - diff --git a/Code/CryEngine/CryCommon/CryPool/Inspector.h b/Code/CryEngine/CryCommon/CryPool/Inspector.h deleted file mode 100644 index 1d16095828..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/Inspector.h +++ /dev/null @@ -1,203 +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_CRYPOOL_INSPECTOR_H -#define CRYINCLUDE_CRYPOOL_INSPECTOR_H -#pragma once - - -namespace NCryPoolAlloc -{ - template - class CInspector - : public TAllocator - { - enum - { - EITableSize = 30 - }; - size_t m_Allocations[EITableSize]; - size_t m_Alignment[EITableSize]; - char m_LogFileName[1024]; - size_t m_AllocCount; - size_t m_FreeCount; - size_t m_ResizeCount; - size_t m_FailAllocCount; - size_t m_FailFreeCount; - size_t m_FailResizeCount; - - void WriteOut(const char* pFileName, uint32 Stack, const char* pFormat, ...) const - { - /* - if(!pFileName) - { - if(!*m_LogFileName) - return; - pFileName = m_LogFileName; - } - FILE* File = fopen(pFileName,"a"); - if(File) - { - - char Buffer[1024]; - for(uint32 a=0;a>= 1; - while (C) - { - Count++; - C >>= 1; - } - return Count >= EITableSize ? EITableSize - 1 : Count; - } - public: - CInspector() - { - for (size_t a = 0; a < EITableSize; a++) - { - m_Allocations[a] = m_Alignment[a] = 0; - } - - m_LogFileName[0] = 0; - m_AllocCount = 0; - m_FreeCount = 0; - m_ResizeCount = 0; - m_FailAllocCount = 0; - m_FailFreeCount = 0; - m_FailResizeCount = 0; - } - - bool LogFileName(const char* pFileName) - { - const size_t Size = strlen(pFileName) + 1; - if (Size > sizeof(m_LogFileName)) - { - m_LogFileName[0] = 0; - return false; - } - memcpy(m_LogFileName, pFileName, Size); - WriteOut(0, "[log start]\n"); - return true; - } - void SaveStats(const char* pFileName) const - { - WriteOut(pFileName, 0, "stats:\n"); - - WriteOut(pFileName, 1, "Counter calls|fails\n"); - WriteOut(pFileName, 2, "Alloc: %6d|%6d\n", m_AllocCount, m_FailAllocCount); - WriteOut(pFileName, 2, "Free: %6d|%6d\n", m_FreeCount, m_FailFreeCount); - WriteOut(pFileName, 2, "Resize:%6d|%6d\n", m_ResizeCount, m_FailResizeCount); - - WriteOut(pFileName, 1, "Allocations:\n"); - for (size_t a = 0; a < EITableSize; a++) - { - WriteOut(pFileName, 2, "%9dByte: %8d\n", 1 << a, m_Allocations[a]); - } - - WriteOut(pFileName, 1, "Alignment:\n"); - for (size_t a = 0; a < EITableSize; a++) - { - WriteOut(pFileName, 2, "%9dByte: %8d\n", 1 << a, m_Alignment[a]); - } - } - - template - ILINE T Allocate(size_t Size, size_t Align = 1) - { - m_AllocCount++; - m_Allocations[Bit(Size)]++; - m_Alignment[Bit(Align)]++; - T pData = TAllocator::template Allocate(Size, Align); - WriteOut(0, 0, "[A|%d|%d|%d]", (int)pData, Size, Align); - if (!pData) - { - m_FailAllocCount++; - WriteOut(0, 0, "[failed]", Size, Align); - } - return pData; - } - - - template - ILINE bool Free(T pData, bool ForceBoundsCheck = false) - { - m_FreeCount++; - const bool Ret = TAllocator::Free(pData, ForceBoundsCheck); - WriteOut(0, 0, "[F|%d|%d|%d]", (int)pData, (int)ForceBoundsCheck, (int)Ret); - m_FailFreeCount += !Ret; - return Ret; - } - //template - //ILINE bool Free(T pData) - // { - // m_FreeCount++; - // const bool Ret = TAllocator::Free(pData); - // WriteOut(0,0,"[F|%d|%d|%d]",(int)pData,(int)-1,(int)Ret); - // m_FailFreeCount+=!Ret; - // return Ret; - // } - - template - ILINE bool Resize(T** pData, size_t Size, size_t Alignment) - { - m_ResizeCount++; - const bool Ret = TAllocator::Resize(pData, Size, Alignment); - WriteOut(0, 0, "[R|%d|%d|%d]", (int)*pData, (int)-1, (int)Ret); - m_FailResizeCount += !Ret; - return Ret; - } - - template - ILINE size_t FindBiggest(const T* pItem) - { - size_t Biggest = 0; - while (pItem) - { - if (pItem->IsFree() && pItem->MemSize() > Biggest) - { - Biggest = pItem->MemSize(); - } - pItem = pItem->Next(); - } - return Biggest; - } - - ILINE size_t BiggestFreeBlock() - { - return FindBiggest(TAllocator::m_Items.First()); - } - - ILINE uint8* FirstItem() - { - return TAllocator::m_Items.First()->Data(); - } - }; -} - - - - -#endif // CRYINCLUDE_CRYPOOL_INSPECTOR_H - diff --git a/Code/CryEngine/CryCommon/CryPool/List.h b/Code/CryEngine/CryCommon/CryPool/List.h deleted file mode 100644 index 5c4588d40c..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/List.h +++ /dev/null @@ -1,366 +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_CRYPOOL_LIST_H -#define CRYINCLUDE_CRYPOOL_LIST_H -#pragma once - -namespace NCryPoolAlloc -{ - class CListItemInPlace; - class CListItemReference; - - template - class CListItem - { - TItem* m_pPrev; - TItem* m_pNext; - public: - - ILINE TItem* Prev(){return m_pPrev; } - ILINE TItem* Next(){return m_pNext; } - ILINE const TItem* Prev() const{return m_pPrev; } - ILINE const TItem* Next() const{return m_pNext; } - ILINE void Prev(TItem* pPrev){ m_pPrev = pPrev; } - ILINE void Next(TItem* pNext){ m_pNext = pNext; } - - //debugging - void Validate(); - }; - - template - class CListItemFlagged - : public CListItem - { - enum - { - ELIF_INUSE = (1 << 0), - ELIF_LOCKED = (1 << 1), - }; - uint32 m_Flags : 8; - uint32 m_Align : 24; - public: - ILINE CListItemFlagged() - : m_Flags(0) - { - } - ILINE bool IsFree() const{return (m_Flags & ELIF_INUSE) != ELIF_INUSE; } - ILINE void Free(){m_Flags &= ~ELIF_INUSE; } - ILINE void InUse(uint32 A){m_Flags |= ELIF_INUSE; m_Align = A; } - ILINE bool Locked() const{return ELIF_LOCKED == (m_Flags & ELIF_LOCKED); } - ILINE void Lock(){m_Flags |= ELIF_LOCKED; } - ILINE void Unlock(){m_Flags &= ~ELIF_LOCKED; } - ILINE uint32 Align() const{return m_Align; } - }; - - class CListItemInPlace - : public CListItemFlagged - { - public: - ILINE void Init([[maybe_unused]] uint8* pData, [[maybe_unused]] size_t Size, CListItemInPlace* pPrev, CListItemInPlace* pNext) - { - Prev(pPrev); - Next(pNext); - CPA_ASSERT(Size == MemSize()); - } - - ILINE bool Available(size_t Size, size_t Align) const - { - size_t Offset = reinterpret_cast(Data()); - if (Offset & (Align - 1)) //not aligned? - { - Size += sizeof(CListItemInPlace) + Align - 1; //then an intermedian node needs to fit - } - return Size <= MemSize() && IsFree(); - } - ILINE uint8* Data(){return reinterpret_cast(this) + sizeof(CListItemInPlace); } - ILINE const uint8* Data() const{return reinterpret_cast(this) + sizeof(CListItemInPlace); } - ILINE size_t MemSize() const - { - const uint8* pNext = reinterpret_cast(Next()); - const uint8* pThis = reinterpret_cast(this); - const size_t ESize = sizeof(CListItemInPlace); - size_t Delta = pNext - pThis; - Delta -= ESize; - return Delta; - } - }; - - class CListItemReference - : public CListItemFlagged - { - uint8* m_pData; - // size_t m_Size; - public: - ILINE void Init(uint8* pData, size_t Size, CListItemReference* pPrev, CListItemReference* pNext) - { - Data(pData); - Prev(pPrev); - Next(pNext); - MemSize(Size); - } - ILINE bool Available(size_t Size, size_t Align) const - { - size_t Offset = reinterpret_cast(Data()); - if ((Offset & (Align - 1))) - { - Size += Align - (Offset & (Align - 1)); - } - return Size <= MemSize() && IsFree(); - } - ILINE void Data(uint8* pData){m_pData = pData; } - ILINE uint8* Data(size_t Align) - { - Align--; - size_t Offset = reinterpret_cast(m_pData); - Offset = (Offset + Align) & ~Align; - return reinterpret_cast(Offset); - } - ILINE uint8* Data(){return m_pData; } - ILINE const uint8* Data() const{return m_pData; } - ILINE void MemSize([[maybe_unused]] size_t Size) { } - ILINE size_t MemSize() const - { - const size_t T = reinterpret_cast(Data()); - const size_t N = Next() ? reinterpret_cast(Next()->Data()) : T; - return N - T; - } - //ILINE void MemSize(size_t Size){m_Size=Size;} - //ILINE size_t MemSize()const{return m_Size;} - }; - - template - class CList - { - TItem* m_pFirst; - TItem* m_pLast; - size_t m_Count; - public: - ILINE CList() - : m_pFirst(0) - , m_pLast(0) - , m_Count(0) - { - } - - ILINE void First(TItem* pItem){m_pFirst = pItem; } - ILINE TItem* First(){return m_pFirst; } - ILINE void Last(TItem* pItem){m_pLast = pItem; } - ILINE TItem* Last(){return m_pLast; } - ILINE bool Empty() const{return m_pFirst == 0; } - - ILINE TItem* PopFirst() - { - Validate(); - - if (!m_pFirst) - { - return 0; - } - - TItem* pRet = m_pFirst; - - m_pFirst = m_pFirst->Next(); - - if (m_pFirst) //if any element exists - { - m_pFirst->Prev(0); //set prev ptr of this element to 0 - } - else - { - m_pLast = 0; //set ptr to last element to 0 if ptr to first is zero as well - } - Validate(); - m_Count--; - return pRet; - } - - ILINE TItem* PopLast() - { - Validate(); - - if (!m_pLast) - { - return 0; - } - - TItem* pRet = m_pLast; - - m_pLast = m_pLast->Prev(); - - if (m_pLast) //if any element exists - { - m_pLast->Next(0); //set prev ptr of this element to 0 - } - else - { - m_pFirst = 0; //set ptr to last element to 0 if ptr to first is zero as well - } - Validate(); - m_Count--; - return pRet; - } - - ILINE void AddFirst(TItem* pItem) - { - CPA_ASSERT(pItem); //ERROR AddFirst got 0 pointer - - Validate(); - - pItem->Prev(0); - pItem->Next(m_pFirst); - if (!m_pFirst) - { - m_pLast = pItem; - } - else - { - m_pFirst->Prev(pItem); - } - m_pFirst = pItem; - - m_Count++; - Validate(); - } - - ILINE void AddLast(TItem* pItem) - { - CPA_ASSERT(pItem); //ERROR AddLast got 0 pointer - - Validate(); - - pItem->Prev(m_pLast); - pItem->Next(0); - if (!m_pLast) - { - m_pFirst = pItem; - } - else - { - m_pLast->Next(pItem); - } - m_pLast = pItem; - - m_Count++; - Validate(); - } - ILINE void AddBefore(TItem* pItem, TItem* pItemSuccessor) - { - CPA_ASSERT(pItem); - CPA_ASSERT(pItemSuccessor); - - Validate(); - - pItem->Next(pItemSuccessor); - pItem->Prev(pItemSuccessor->Prev()); - pItemSuccessor->Prev(pItem); - - if (pItemSuccessor == m_pFirst) - { - m_pFirst = pItem; - } - else - { - pItem->Prev()->Next(pItem); - } - - m_Count++; - Validate(); - } - ILINE void AddBehind(TItem* pItem, TItem* pItemPredecessor) - { - CPA_ASSERT(pItem); - CPA_ASSERT(pItemPredecessor); - - Validate(); - - pItem->Next(pItemPredecessor->Next()); - pItem->Prev(pItemPredecessor); - pItemPredecessor->Next(pItem); - - if (pItemPredecessor == m_pLast) - { - m_pLast = pItem; - } - else - { - pItem->Next()->Prev(pItem); - } - - m_Count++; - Validate(); - } - - ILINE void Remove(TItem* pItem) - { - CPA_ASSERT(pItem); //ERROR releasing empty item - - if (pItem == m_pFirst) - { - PopFirst(); - return; - } - if (pItem == m_pLast) - { - PopLast(); - return; - } - - Validate(pItem); - - pItem->Prev()->Next(pItem->Next()); - pItem->Next()->Prev(pItem->Prev()); - - m_Count--; - Validate(); - } - - //debug - ILINE void Validate(TItem* pReferenceItem = 0) - { - if (!VALIDATE) - { - return; - } - - //one-sided empty? - CPA_ASSERT((!First() && !Last()) || (First() && Last())); //ERROR validating item-list, just one end is 0 - - // endles linking? - TItem* pPrev = 0; - TItem* pItem = First(); - while (pItem) - { - if (pReferenceItem == pItem) - { - pReferenceItem = 0; - } - CPA_ASSERT(pPrev == pItem->Prev()); //ERROR validating item-list, endless linking NULL - pPrev = pItem; - pItem = pItem->Next(); - } - - CPA_ASSERT(pPrev == Last()); //ERROR validating item-list, broken list, does not end at specified Last item - CPA_ASSERT(!pReferenceItem); //ERROR reference item not found in the item-list - } - ILINE size_t Count() const{return m_Count; } - }; -} - - - - - - -#endif // CRYINCLUDE_CRYPOOL_LIST_H - diff --git a/Code/CryEngine/CryCommon/CryPool/Memory.h b/Code/CryEngine/CryCommon/CryPool/Memory.h deleted file mode 100644 index 43daaaeada..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/Memory.h +++ /dev/null @@ -1,70 +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_CRYPOOL_MEMORY_H -#define CRYINCLUDE_CRYPOOL_MEMORY_H -#pragma once - -namespace NCryPoolAlloc -{ - class CMemoryDynamic - { - size_t m_Size; - uint8* m_pData; - - protected: - ILINE CMemoryDynamic() - : m_Size(0) - , m_pData(0){} - - public: - ILINE void InitMem(const size_t S, uint8* pData) - { - m_Size = S; - m_pData = pData; - CPA_ASSERT(S); - CPA_ASSERT(pData); - } - - ILINE size_t MemSize() const{return m_Size; } - ILINE uint8* Data(){return m_pData; } - ILINE const uint8* Data() const{return m_pData; } - }; - - template - class CMemoryStatic - { - uint8 m_Data[TSize]; - - protected: - ILINE CMemoryStatic() - { - } - public: - ILINE void InitMem(const size_t S, uint8* pData) - { - } - ILINE size_t MemSize() const{return TSize; } - ILINE uint8* Data(){return m_Data; } - ILINE const uint8* Data() const{return m_Data; } - }; -} - - - - - - - -#endif // CRYINCLUDE_CRYPOOL_MEMORY_H - diff --git a/Code/CryEngine/CryCommon/CryPool/PoolAlloc.h b/Code/CryEngine/CryCommon/CryPool/PoolAlloc.h deleted file mode 100644 index 23eda51a2a..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/PoolAlloc.h +++ /dev/null @@ -1,55 +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(POOLALLOCTESTSUIT) -//cheat just for unit testing on windows -#include "BaseTypes.h" -#define ILINE inline -#endif - -// Traits -#if defined(AZ_RESTRICTED_PLATFORM) - #include AZ_RESTRICTED_FILE(CryPool/PoolAlloc_h) -#elif defined(APPLE) || defined(LINUX) -#define POOLALLOC_H_TRAIT_USE_MEMALIGN 1 -#endif - - -#if POOLALLOC_H_TRAIT_USE_MEMALIGN -#define CPA_ALLOC memalign -#define CPA_FREE free -#else -#define CPA_ALLOC _aligned_malloc -#define CPA_FREE _aligned_free -#endif -#define CPA_ASSERT assert -#define CPA_ASSERT_STATIC(X) {uint8 assertdata[(X) ? 0 : 1]; } -#define CPA_BREAK __debugbreak() - -#include "List.h" -#include "Memory.h" -#include "Container.h" -#include "Allocator.h" -#include "Defrag.h" -#include "STLWrapper.h" -#include "Inspector.h" -#include "Fallback.h" -#if !defined(POOLALLOCTESTSUIT) -#include "ThreadSafe.h" -#endif - -#undef CPA_ASSERT -#undef CPA_ASSERT_STATIC -#undef CPA_BREAK diff --git a/Code/CryEngine/CryCommon/CryPool/STLWrapper.h b/Code/CryEngine/CryCommon/CryPool/STLWrapper.h deleted file mode 100644 index cb06ced1a4..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/STLWrapper.h +++ /dev/null @@ -1,148 +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_CRYPOOL_STLWRAPPER_H -#define CRYINCLUDE_CRYPOOL_STLWRAPPER_H -#pragma once - -namespace NCryPoolAlloc -{ - //namespace CSTLPoolAllocWrapperHelper - //{ - // inline void destruct(char *) {} - // inline void destruct(wchar_t*) {} - // template - // inline void destruct(T *t) {t->~T();} - //} - - //template - //struct CSTLPoolAllocWrapperStatic - //{ - // static PoolAllocator * allocator; - //}; - - //template - //struct CSTLPoolAllocWrapperKungFu : public CSTLPoolAllocWrapperStatic - //{ - //}; - - template - class CSTLPoolAllocWrapper - { - private: - static TCont* m_pContainer; - public: - typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef T* pointer; - typedef const T* const_pointer; - typedef T& reference; - typedef const T& const_reference; - typedef T value_type; - - static TCont* Container(){return m_pContainer; } - static void Container(TCont* pContainer){m_pContainer = pContainer; } - - - template - struct rebind - { - typedef CSTLPoolAllocWrapper other; - }; - - CSTLPoolAllocWrapper() throw() - { - } - - CSTLPoolAllocWrapper(const CSTLPoolAllocWrapper&) throw() - { - } - - template - CSTLPoolAllocWrapper(const CSTLPoolAllocWrapper&) throw() - { - } - - ~CSTLPoolAllocWrapper() throw() - { - } - - pointer address(reference x) const - { - return &x; - } - - const_pointer address(const_reference x) const - { - return &x; - } - - pointer allocate(size_type n = 1, const_pointer hint = 0) - { - TCont* pContainer = Container(); - uint8* pData = pContainer->TCont::template Allocate(n * sizeof(T), sizeof(T)); - return pContainer->TCont::template Resolve(pData); - // return Container()?Container()->Allocate(n*sizeof(T),sizeof(T)):0 - } - - void deallocate(pointer p, size_type n = 1) - { - if (Container()) - { - Container()->Free(p); - } - } - - size_type max_size() const throw() - { - return Container() ? Container()->MemSize() : 0; - } - - void construct(pointer p, const T& val) - { - new(static_cast(p))T(val); - } - - void construct(pointer p) - { - new(static_cast(p))T(); - } - - void destroy(pointer p) - { - p->~T(); - } - - pointer new_pointer() - { - return new(allocate())T(); - } - - pointer new_pointer(const T& val) - { - return new(allocate())T(val); - } - - void delete_pointer(pointer p) - { - p->~T(); - deallocate(p); - } - - bool operator==(const CSTLPoolAllocWrapper&) {return true; } - bool operator!=(const CSTLPoolAllocWrapper&) {return false; } - }; -} - -#endif // CRYINCLUDE_CRYPOOL_STLWRAPPER_H - diff --git a/Code/CryEngine/CryCommon/CryPool/ThreadSafe.h b/Code/CryEngine/CryCommon/CryPool/ThreadSafe.h deleted file mode 100644 index 5ae7dbd4bc..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/ThreadSafe.h +++ /dev/null @@ -1,58 +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_CRYPOOL_THREADSAFE_H -#define CRYINCLUDE_CRYPOOL_THREADSAFE_H -#pragma once - - -#include - -namespace NCryPoolAlloc -{ - template - class CThreadSafe - : public TAllocator - { - CryCriticalSection m_Mutex; - public: - - template - ILINE T Allocate(size_t Size, size_t Align = 1) - { - CryAutoLock lock(m_Mutex); - return TAllocator::template Allocate(Size, Align); - } - - - template - ILINE bool Free(T pData, bool ForceBoundsCheck = false) - { - CryAutoLock lock(m_Mutex); - return TAllocator::Free(pData, ForceBoundsCheck); - } - - template - ILINE bool Resize(T** pData, size_t Size, size_t Alignment) - { - CryAutoLock lock(m_Mutex); - return TAllocator::Resize(pData, Size, Alignment); - } - }; -} - - - - -#endif // CRYINCLUDE_CRYPOOL_THREADSAFE_H - diff --git a/Code/CryEngine/CryCommon/CryPool/example.h b/Code/CryEngine/CryCommon/CryPool/example.h deleted file mode 100644 index e17d5abee2..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/example.h +++ /dev/null @@ -1,287 +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_CRYPOOL_EXAMPLE_H -#define CRYINCLUDE_CRYPOOL_EXAMPLE_H -#pragma once - - -//The documentation is split up into 3 main parts, so strg+f for -// -Theory -// -Building blocks -// -Usage -// -FAQ -// -Realloc/Resize - -///////////////////////////////////////////////////////////////////////// -// -Theory -///////////////////////////////////////////////////////////////////////// - - -//this includes the 3 major parts of the allocate suite -//1. the memory location templates -//2. container types -//3. some allocator version -//addtional you get -//4. a simple stack based defragmentation template -//5. helper - -//1. memory location templates -// There are two types of them, static and dynamic -//1.1 CMemoryStatic allows you do define on compile time what size -// it should have, suitable for pool you know that they won't grow or -// shrink -//1.2 CMemoryDynamic, this one has no template parameter, it has just one -// indirection via ptr to the memory location and size, that you will -// set during initialization. - -//2. Container types -// We have also two container types, one so called "In Place" -// and one "Referenced". -//2.1 "In Place" means that a header is placed above every allocation, -// this is the usual way most allocators work. -//2.2 "Referenced", has an extra pool of headers that point to the actual -// memory. This is suitable for -// - external memory locations that are not directly accessable by the -// cpu. E.g. pools on disk, networks, rsx memory.. -// - defragmentation, because you don't save a ptr to the real memory -// location, just a "handle" of the referencing item. -// - big alignments, having 4kb of alignment would waste also -// - 4kb for ever "In Place" header, you might not want that. - -//3. Allocators -// This time we have 3 of them, "BestFit", "WorstFit" and "FirstFit" -//3.1 FirstFit just seeks for any location big enought to fit your -// requested size of memory. Internally it also saves the last used -// free memory area to speed up allocations. -// Use this also if you have just one particular allocation size. -//3.2 WorstFit, although it might sound illogical, WorstFit can reduce -// memory fragmentation in a cases with very random allocation sizes, -// because it gives smaller free blocks the chance to concatenate to -// bigger free blocks again while filling up those previously -// generated big blocks. The bad side is that it takes quite some time -// to find the biggest block as this needs to be done every time you -// allocate, so use this just when having a low amount of allocations -// or you're really desperately looking for mem. -//3.3 BestFit, it's best used if you don't have just one allocation size, -// but still very few varying sizes. Previously released blocks of -// the currently allocating sizes will be seeked and reused, this -// strongly helps to reduce fragmentation. While this might be slow -// in some cases, it can save you from doing any defragmentation. - -//4. Defragmentation -// At the moment just one defragmentation algorithm is implemented: -// "Stack defragmentator" -// If you don't want some block to be moved, "Lock" it using your -// memory handle. -//4.1 Stack based -// To reduce fragmentation, holes are filled up with the next used, -// memory area. This defragmentation sheme is useful when you have -// some long living locations as well as very short living ones. -// At some point all long live memory will end up at the bottom of -// the stack, while leaving empty memory areas at the top for short -// living allocations. - -//5. Helper -// this should be filled up with some handy helper tools for this -// pool suite. -// The first tool is a wrapper for the usage with stl -//5.1 Wrapper for STL -// As you know, you can pass your own allocator as the last -// parameter of stl containers, with this helper you can use a pool -// created with this suite and wrap it for the stl. - - -///////////////////////////////////////////////////////////////////////// -// -Building blocks -///////////////////////////////////////////////////////////////////////// - -//That's the theory, so how does it work? -//It's pretty simple, you compose the pool of your dreams by cascading -//templates. -//Lets start with an exmaple -//Per level you want to allocate a fixed amount of memory for your -//textures. -CMemoryDynamic -//- They are placed in some memory you can access directly with the cpu: -CInPlace -//- and you don't want to defragmentate, so you prefer an allocation -// sheme that reduces fragmentation. - CBestFit -//now you combine them -typedef CBestFit, CListItemInPlace> TMyOwnPool; - -//Yes, it's that simple. -//ok, ok, texture memory is usually nothing you want to access directly -//with your cpu, so let's create a referencing pool. Therefor you need -//to also specify how many nodes that can reference your pool will have. -//We won't have more than 4000 textures, so let's start with -{ - enum TEXTURE_NODE_COUNT = 4096 -}; -//and now our referencing pool -typedef CBestFit < CReferenced TMyOwnPool; - -//But yeah, you're right, texture memory has also a fixed size, lets -//assume it's 128MB. -{ - enum TEXTURE_MEMORY_SIZE = 128 * 1024 * 1024 -}; -//and our fixed sized memory pool -typedef CBestFit < CReferenced, TEXTURE_NODE_COUNT> TMyOwnPool; - -//ok, but you don't trust the best fit allocator in all cases, you prefer -//a fast one and you accept the slow down for defragmentation incase the -//allocation fails. -//So lets created a straight First Fit allocator with defragmentation: -typedef CDefragStacked < CFirstFit, TEXTURE_NODE_COUNT> > TMyOwnPool; - -//here you see how simple you can add defragmentation, but be careful, it -//works of course just on Reference based memory containers, if you have -//Direct pointers to In Place allocation, we cannot shuffle them around. - - -///////////////////////////////////////////////////////////////////////// -// -Usage -///////////////////////////////////////////////////////////////////////// - - -//it all starts by including the meain header -#include "PoolAlloc.h" - -//Define your dream allocator, preferably using a typedef (or macro) -typedef CBestFit, CListItemInPlace> TMyOwnPool; -//also typedef (or macro) your handle -typedef uint8* TMyHandle; //in case of "In Place" allocations -typedef uint32 TMyHandle; //in case of "Referenced" - -//Instantiate it -TMyOwnPool g_MyMemory; - -//now you need to initialize it, -g_MyMemory.InitMem(pMemoryArea, MemorySize); //in case you use "CMemoryDynamic" -g_MyMemory.InitMem(); //in case you use "CmemoryStatic, -//altough you could pass the same -//parameters, they'd be ignored. -//Use this also to flush the pool -//quickly - - -//now allocate -TMyHandle MemID = g_MyMemory.Allocate(Size); -//optionally alignment can be passed as 2nd parameter -TMyHandle MemID = g_MyMemory.Allocate(Size, Align); - -//free it simply by calling -g_Memory.Free(MemID); - -//you might want to call the beat function to defragment the memory -//on regular base -g_Memory.Beat(); -//you might also want to call it just when an allocation failed to -//defragmentate the memory as good as possible -if (!(MemID = g_Memoery.Allocate(Size))) -{ - while (g_Memory.Beat()) - { - ; - } - MemID = g_Memoery.Allocate(Size); -} - -//To acquire the pointer to your data, you need to resolve the handle -MyObject* pObject = g_Memory.Resolve(MemID); - -///////////////////////////////////////////////////////////////////////// -// -Realloc/Resize -///////////////////////////////////////////////////////////////////////// - -// The Containers provide a "resize" function. This one does nothing else -// than the name suggest, it is freeing some memory at the end of your -// allocation or, if free memory is available, allocates some memory to -// the end of your buffer. But it may also fail, if not enough memory -// available to allocate. -// "Realloc" on the other side requires an extra template that you wrap -// around your existing one like: -typedef CReallocator TMyOwnPoolWithReallocation; -// This one will first try to use resize, but in case it fails, it will -// allocate a seperate memory area, copy the data and free the old one. -// -// But this may fail as well, therefor the result is not a pointer to the -// allocation, but true/false. -// There for you need to pass a pointer to your pointer to the memory area -// or handle you deal with. -Handle = rMemory.Allocate(10, 1); -if (!rMemory.Reallocate(&Handles, 11, 1)) -{ - //handle realloc failure -} - - -///////////////////////////////////////////////////////////////////////// -// -FAQ -///////////////////////////////////////////////////////////////////////// - -//"DO I HAVE TO ALWAYS RESOLVE?" -//if you use "In Place" memory, not at all, all resolve does is to -//cast your handle to your object ptr and returns it. -//if you use "Referenced" memory and you don't defragmentate, you -//can do it once and keep the ptr, but you also need to keep the -//handle to free the memory later on. - -//"any reason I should resolve?" -//Yes, first of all, it makes it very easy to switch between various -//pool configuration for testing, you simply change some params of -//your typedef (or macro) and it should work out of the box. -//second, for defragmentation it's the only way to go and for future -//things it might be needed as well - -//"but isn't resolving just overhead?" -//in case of "In Place": no, the resolve function just returns the -//pointer, casting to your wanted type -//in case of "Referenced": it cost you one indirection. - - -//"How do I flush the whole pool without freeing all items?" -g_Memory.InitMem() -//yes, you can call "InitMem" once again, you need to pass the mem -//ptr and size if using CMemoryDynamic e.g. -g_Memory.Init(g_Memory.Size(), g_Memory.Data()); - -//"How do I lock the allocated memory to avoid any reallocation" -g_Memory.Item(ptr)->Lock(); - - -//"How do I get the size of a memory block?" -g_Memory.Item(ptr)->MemSize(); - - - - -//"Is there any example?" -//for a real life example check PAUnitTest.cpp used to validate all -//functions of this pool. - - -//bug reports? questions? support? -//just ask me :) (michael kopietz) - - - - - - - - -#endif // CRYINCLUDE_CRYPOOL_EXAMPLE_H - diff --git a/Code/CryEngine/CryCommon/GeomCacheFileFormat.h b/Code/CryEngine/CryCommon/GeomCacheFileFormat.h deleted file mode 100644 index a8328e8a14..0000000000 --- a/Code/CryEngine/CryCommon/GeomCacheFileFormat.h +++ /dev/null @@ -1,202 +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_GEOMCACHEFILEFORMAT_H -#define CRYINCLUDE_CRYCOMMON_GEOMCACHEFILEFORMAT_H -#pragma once - -#include "CryExtension/CryGUID.h" - -#if !defined(LINUX) -#pragma pack(push) -#pragma pack(1) -#define PACK_GCC -#else -#define PACK_GCC __attribute__ ((packed)) -#endif - -namespace GeomCacheFile -{ - // Important: The enums are serialized, don't change the values - // without increasing the file version, conversion code etc! - - typedef Vec3_tpl Position; - typedef Vec2_tpl Texcoords; - typedef Vec4_tpl QTangent; - typedef uint8 Color; - - // ASCII "CAXCACHE" - const uint64 kFileSignature = 0x4548434143584143ull; - - // The smallest 'UVmax' we'll support - this avoids division by zero when encoding/decoding UVs - const float kMinUVrange = .01f; - - // Bit Precision of tangents quaternions - const uint kTangentQuatPrecision = 10; - - // Current file version GUID. Files with other GUIDs will not be loaded by the engine. - const CryGUID kCurrentVersion = MAKE_CRYGUID(0x1641defe440af501, 0x7ec5e9164c8c2d1c); - - // Mesh prediction look back array size - const uint kMeshPredictorLookBackMaxDist = 4096; - - // Number of frames between index frames. Needs to be <= g_kMaxBufferedFrames. - const uint kMaxIFrameDistance = 30; - - enum EFileHeaderFlags - { - eFileHeaderFlags_PlaybackFromMemory = BIT(0), - eFileHeaderFlags_32BitIndices = BIT(1) - }; - - enum EBlockCompressionFormat - { - eBlockCompressionFormat_None = 0, - eBlockCompressionFormat_Deflate = 1, // zlib - eBlockCompressionFormat_LZ4HC = 2, // LZ4 HC - eBlockCompressionFormat_ZSTD = 3, //ZStandard - }; - - enum EStreams - { - eStream_Indices = BIT(0), - eStream_Positions = BIT(1), - eStream_Texcoords = BIT(2), - eStream_QTangents = BIT(3), - eStream_Colors = BIT(4) - }; - - enum ETransformType - { - eTransformType_Constant, - eTransformType_Animated - }; - - enum ENodeType - { - eNodeType_Transform = 0, // Transforms all sub nodes - eNodeType_Mesh = 1, - eNodeType_PhysicsGeometry = 2, - }; - - // Common frame - enum EFrameType - { - eFrameType_IFrame = 0, - eFrameType_BFrame = 1 - }; - - // Common frame flags - enum EFrameFlags - { - eFrameFlags_Hidden = BIT(0) - }; - - // Flags for mesh index frames - enum EMeshIFrameFlags - { - eMeshIFrameFlags_UsePredictor = BIT(1) - }; - - struct SHeader - { - SHeader() - : m_signature(0) - , m_version(kCurrentVersion) - , m_blockCompressionFormat(0) - , m_flags(0) - , m_numFrames(0) {} - - uint64 m_signature; - CryGUID m_version; - uint16 m_blockCompressionFormat; - uint32 m_flags; - uint32 m_numFrames; - uint64 m_totalUncompressedAnimationSize; - float m_aabbMin[3]; - float m_aabbMax[3]; - } PACK_GCC; - - struct SFrameInfo - { - uint32 m_frameType; - uint32 m_frameSize; - uint64 m_frameOffset; - float m_frameTime; - } PACK_GCC; - - struct SCompressedBlockHeader - { - uint32 m_uncompressedSize; - uint32 m_compressedSize; - } PACK_GCC; - - struct SFrameHeader - { - uint32 m_nodeDataOffset; - float m_frameAABBMin[3]; - float m_frameAABBMax[3]; - uint32 m_padding; - } PACK_GCC; - - struct STemporalPredictorControl - { - uint8 m_acceleration; - uint8 m_indexFrameLerpFactor; - uint8 m_combineFactor; - uint8 m_padding; - } PACK_GCC; - - struct SMeshFrameHeader - { - uint32 m_flags; - STemporalPredictorControl m_positionStreamPredictorControl; - STemporalPredictorControl m_texcoordStreamPredictorControl; - STemporalPredictorControl m_qTangentStreamPredictorControl; - STemporalPredictorControl m_colorStreamPredictorControl[4]; - } PACK_GCC; - - struct SMeshInfo - { - uint8 m_constantStreams; - uint8 m_animatedStreams; - uint8 m_positionPrecision[3]; - float m_uvMax; - uint8 m_padding; - uint16 m_numMaterials; - uint32 m_numVertices; - uint32 m_flags; - float m_aabbMin[3]; - float m_aabbMax[3]; - uint32 m_nameLength; - uint64 m_hash; - } PACK_GCC; - - struct SNodeInfo - { - uint8 m_type; - uint8 m_bVisible; - uint16 m_transformType; - uint32 m_meshIndex; - uint32 m_numChildren; - uint32 m_nameLength; - } PACK_GCC; -} - -#undef PACK_GCC - -#if !defined(LINUX) -#pragma pack(pop) -#endif - -#endif // CRYINCLUDE_CRYCOMMON_GEOMCACHEFILEFORMAT_H diff --git a/Code/CryEngine/CryCommon/IEngineModule.h b/Code/CryEngine/CryCommon/IEngineModule.h deleted file mode 100644 index 7835cde26e..0000000000 --- a/Code/CryEngine/CryCommon/IEngineModule.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. - -// Description : Defines the extension interface for the CryEngine modules. - - -#ifndef CRYINCLUDE_CRYCOMMON_IENGINEMODULE_H -#define CRYINCLUDE_CRYCOMMON_IENGINEMODULE_H -#pragma once - -#include -#include -#include -#include - -struct SSystemInitParams; - -// Base Interface for all engine module extensions -struct IEngineModule - : public ICryUnknown -{ - CRYINTERFACE_DECLARE(IEngineModule, 0xf899cf661df04f61, 0xa341a8a7ffdf9de4); - - // - // Retrieve name of the extension module. - virtual const char* GetName() const = 0; - - // Retrieve category for the extension module (CryEngine for standard modules). - virtual const char* GetCategory() const = 0; - - // This is called to initialize the new module. - virtual bool Initialize(SSystemGlobalEnvironment& env, const SSystemInitParams& initParams) = 0; - // - - // This is called to register any AZ console vars declared within this engine module - virtual void RegisterConsoleVars() - { - AZ::ConsoleFunctorBase*& deferredHead = AZ::ConsoleFunctorBase::GetDeferredHead(); - AZ::Interface::Get()->LinkDeferredFunctors(deferredHead); - } -}; - -#endif // CRYINCLUDE_CRYCOMMON_IENGINEMODULE_H diff --git a/Code/CryEngine/CryCommon/IRemoteCommand.h b/Code/CryEngine/CryCommon/IRemoteCommand.h deleted file mode 100644 index 03adb89b44..0000000000 --- a/Code/CryEngine/CryCommon/IRemoteCommand.h +++ /dev/null @@ -1,763 +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 : Service network interface - - -#ifndef CRYINCLUDE_CRYCOMMON_IREMOTECOMMAND_H -#define CRYINCLUDE_CRYCOMMON_IREMOTECOMMAND_H -#pragma once - -#include -#include - -//----------------------------------------------------------------------------- -// Helpers for writing/reading command data stream from network message packets. -// Those interfaces automatically handle byteswapping for big endian systems. -// The native format for data inside the messages is little endian. -//----------------------------------------------------------------------------- - -/// Write stream interface -struct IDataWriteStream -{ -public: - virtual ~IDataWriteStream() {}; - -public: - // Virtualized write method for general data buffer - virtual void Write(const void* pData, const uint32 size) = 0; - - // Virtualized write method for types with size 8 (support byteswapping, a little bit faster than general case) - virtual void Write8(const void* pData) = 0; - - // Virtualized write method for types with size 4 (support byteswapping, a little bit faster than general case) - virtual void Write4(const void* pData) = 0; - - // Virtualized write method for types with size 2 (support byteswapping, a little bit faster than general case) - virtual void Write2(const void* pData) = 0; - - // Virtualized write method for types with size 1 (a little bit faster than general case) - virtual void Write1(const void* pData) = 0; - - // Get number of bytes written - virtual const uint32 GetSize() const = 0; - - // Convert to service network message - virtual struct IServiceNetworkMessage* BuildMessage() const = 0; - - // Save the data from this writer stream to the provided buffer - virtual void CopyToBuffer(void* pData) const = 0; - - // Destroy object (if dynamically created) - virtual void Delete() = 0; - -public: - IDataWriteStream& operator<<(const uint8& val) - { - Write1(&val); - return *this; - } - - IDataWriteStream& operator<<(const uint16& val) - { - Write2(&val); - return *this; - } - - IDataWriteStream& operator<<(const uint32& val) - { - Write4(&val); - return *this; - } - - IDataWriteStream& operator<<(const uint64& val) - { - Write8(&val); - return *this; - } - - IDataWriteStream& operator<<(const int8& val) - { - Write1(&val); - return *this; - } - - IDataWriteStream& operator<<(const int16& val) - { - Write2(&val); - return *this; - } - - IDataWriteStream& operator<<(const int32& val) - { - Write4(&val); - return *this; - } - - IDataWriteStream& operator<<(const int64& val) - { - Write8(&val); - return *this; - } - - IDataWriteStream& operator<<(const float& val) - { - Write4(&val); - return *this; - } - - // Bool is saved by writing an 8 bit value to make it portable - IDataWriteStream& operator<<(const bool& val) - { - const uint8 uVal = val ? 1 : 0; - Write1(&uVal); - return *this; - } - -public: - // Write C string to stream - void WriteString(const char* str); - - // Write string to stream - void WriteString(const string& str); - - // Write int8 value to stream - void WriteInt8(const int8 val) - { - Write1(&val); - } - - // Write int16 value to stream - void WriteInt16(const int16 val) - { - Write2(&val); - } - - // Write int32 value to stream - void WriteInt32(const int32 val) - { - Write4(&val); - } - - // Write int64 value to stream - void WriteInt64(const int64 val) - { - Write8(&val); - } - - // Write uint8 value to stream - void WriteUint8(const uint8 val) - { - Write1(&val); - } - - // Write uint16 value to stream - void WriteUint16(const uint16 val) - { - Write2(&val); - } - - // Write uint32 value to stream - void WriteUint32(const uint32 val) - { - Write4(&val); - } - - // Write uint64 value to stream - void WriteUint64(const uint64 val) - { - Write8(&val); - } - - // Write float value to stream - void WriteFloat(const float val) - { - Write4(&val); - } -}; - -//----------------------------------------------------------------------------- - -/// Read stream interface -/// This interface should support endianess swapping -struct IDataReadStream -{ -public: - virtual ~IDataReadStream() {}; - -public: - // Destroy object (if dynamically created) - virtual void Delete() = 0; - - // Skip given amount of data without reading it - virtual void Skip(const uint32 size) = 0; - - // Virtualized read method (for general buffers) - virtual void Read(void* pData, const uint32 size) = 0; - - // Virtualized read method for types with size 8 (a little bit faster than general method, supports byte swapping for BE systems) - virtual void Read8(void* pData) = 0; - - // Virtualized read method for types with size 4 (a little bit faster than general method, supports byte swapping for BE systems) - virtual void Read4(void* pData) = 0; - - // Virtualized read method for types with size 2 (a little bit faster than general method, supports byte swapping for BE systems) - virtual void Read2(void* pData) = 0; - - // Virtualized read method for types with size 1 (a little bit faster than general method, supports byte swapping for BE systems) - virtual void Read1(void* pData) = 0; - - // Optimization case - get direct pointer to the underlying buffer - virtual const void* GetPointer() = 0; - -public: - IDataReadStream& operator<<(uint8& val) - { - Read1(&val); - return *this; - } - - IDataReadStream& operator<<(uint16& val) - { - Read2(&val); - return *this; - } - - IDataReadStream& operator<<(uint32& val) - { - Read4(&val); - return *this; - } - - IDataReadStream& operator<<(uint64& val) - { - Read8(&val); - return *this; - } - - IDataReadStream& operator<<(int8& val) - { - Read1(&val); - return *this; - } - - IDataReadStream& operator<<(int16& val) - { - Read2(&val); - return *this; - } - - IDataReadStream& operator<<(int32& val) - { - Read4(&val); - return *this; - } - - IDataReadStream& operator<<(int64& val) - { - Read8(&val); - return *this; - } - - IDataReadStream& operator<<(float& val) - { - Read4(&val); - return *this; - } - - // Bool is saved by writing an 8 bit value to make it portable - IDataReadStream& operator<<(bool& val) - { - uint8 uVal = 0; - Read1(&uVal); - val = (uVal != 0); - return *this; - } - -public: - // Read string from stream - string ReadString(); - - // Skip string data in a stream without loading the data - void SkipString(); - - // Read int8 from stream - int8 ReadInt8() - { - int8 val = 0; - Read1(&val); - return val; - } - - // Read int16 from stream - int16 ReadInt16() - { - int16 val = 0; - Read2(&val); - return val; - } - - // Read int32 from stream - int32 ReadInt32() - { - int32 val = 0; - Read4(&val); - return val; - } - - // Read int64 from stream - int64 ReadInt64() - { - int64 val = 0; - Read8(&val); - return val; - } - - // Read uint8 from stream - uint8 ReadUint8() - { - uint8 val = 0; - Read1(&val); - return val; - } - - // Read uint16 from stream - uint16 ReadUint16() - { - uint16 val = 0; - Read2(&val); - return val; - } - - // Read uint32 from stream - uint32 ReadUint32() - { - uint32 val = 0; - Read4(&val); - return val; - } - - // Read int64 from stream - uint64 ReadUint64() - { - uint64 val = 0; - Read8(&val); - return val; - } - - // Read float from stream - float ReadFloat() - { - float val = 0.0f; - Read4(&val); - return val; - } -}; - -//----------------------------------------------------------------------------- - -/// Remote command class info (simple RTTI) -struct IRemoteCommandClass -{ -public: - virtual ~IRemoteCommandClass() {}; - - // Get class name - virtual const char* GetName() const = 0; - - // Create command instance - virtual struct IRemoteCommand* CreateObject() = 0; -}; - -/// Remote command interface -struct IRemoteCommand -{ -protected: - virtual ~IRemoteCommand() {}; - -public: - // Get command class - virtual IRemoteCommandClass* GetClass() const = 0; - - // Save to data stream - virtual void SaveToStream(struct IDataWriteStream& writeStream) const = 0; - - // Load from data stream - virtual void LoadFromStream(struct IDataReadStream& readStream) = 0; - - // Execute (remote call) = 0; - virtual void Execute() = 0; - - // Delete the command object (can be allocated from different heap) - virtual void Delete() = 0; -}; - -//----------------------------------------------------------------------------- - -// This is a implementation of a synchronous listener (limited to the engine tick rate) -// that processes and responds to the raw messages received from clients. -struct IRemoteCommandListenerSync -{ -public: - virtual ~IRemoteCommandListenerSync() {}; - - // Process a raw message and optionally provide an answer to the request, return true if you have processed the message. - // Messages is accessible via the data reader. Response can be written to a data writer. - virtual bool OnRawMessageSync(const class ServiceNetworkAddress& remoteAddress, struct IDataReadStream& msg, struct IDataWriteStream& response) = 0; -}; - -//----------------------------------------------------------------------------- - -// This is a implementation of a asynchronous listener (called from network thread) -// that processes and responds to the raw messages received from clients. -struct IRemoteCommandListenerAsync -{ -public: - virtual ~IRemoteCommandListenerAsync() {}; - - // Process a raw message and optionally provide an answer to the request, return true if you have processed the message. - // Messages is accessible via the data reader. Response can be written to a data writer. - virtual bool OnRawMessageAsync(const class ServiceNetworkAddress& remoteAddress, struct IDataReadStream& msg, struct IDataWriteStream& response) = 0; -}; - -//----------------------------------------------------------------------------- - -/// Remote command server -struct IRemoteCommandServer -{ -protected: - virtual ~IRemoteCommandServer() {}; - -public: - // Execute all of the received pending commands - // This should be called from a safe place (main thread) - virtual void FlushCommandQueue() = 0; - - // Suppress command execution - virtual void SuppressCommands() = 0; - - // Resume command execution - virtual void ResumeCommands() = 0; - - // Register/Unregister synchronous message listener (limited to tick rate) - virtual void RegisterSyncMessageListener(IRemoteCommandListenerSync* pListener) = 0; - virtual void UnregisterSyncMessageListener(IRemoteCommandListenerSync* pListener) = 0; - - // Register/Unregister asynchronous message listener (called from network thread) - virtual void RegisterAsyncMessageListener(IRemoteCommandListenerAsync* pListener) = 0; - virtual void UnregisterAsyncMessageListener(IRemoteCommandListenerAsync* pListener) = 0; - - // Broadcast a message to all connected clients - virtual void Broadcast(IServiceNetworkMessage* pMessage) = 0; - - // Do we have any clients connected ? - virtual bool HasConnectedClients() const = 0; - - // Delete the client - virtual void Delete() = 0; -}; - -//----------------------------------------------------------------------------- - -/// Connection to remote command server -struct IRemoteCommandConnection -{ -protected: - virtual ~IRemoteCommandConnection() {}; - -public: - // Are we connected ? - // This returns false when the underlying network connection has failed (sockets error). - // Also, this returns false if the remote connection was closed by remote peer. - virtual bool IsAlive() const = 0; - - // Get address of remote command server - // This returns the full address of the endpoint (with valid port) - virtual const ServiceNetworkAddress& GetRemoteAddress() const = 0; - - // Send raw message to the other side of this connection. - // Raw messages are not buffer and are sent right away, - // they also have precedence over internal command traffic. - // The idea is that you need some kind of bidirectional signaling - // channel to extend the rather one-directional nature of commands. - // Returns true if message was added to the send queue. - virtual bool SendRawMessage(IServiceNetworkMessage* pMessage) = 0; - - // See if there's a raw message waiting for us and if it is, get it - // Be aware that messages are reference counted. - virtual IServiceNetworkMessage* ReceiveRawMessage() = 0; - - // Close connection - // - pending commands are not sent - // - pending raw messages are sent or not (depending on the flag) - virtual void Close(bool bFlushQueueBeforeClosing = false) = 0; - - // Add internal reference to object (Refcounting interface) - virtual void AddRef() = 0; - - // Release internal reference to object (Refcounting interface) - virtual void Release() = 0; -}; - -//----------------------------------------------------------------------------- - -/// Remote command client -struct IRemoteCommandClient -{ -protected: - virtual ~IRemoteCommandClient() {}; - -public: - // Connect to remote server, returns true on success, false on failure - virtual IRemoteCommandConnection* ConnectToServer(const class ServiceNetworkAddress& serverAddress) = 0; - - // Schedule command to be executed on the all of the remote servers - virtual bool Schedule(const IRemoteCommand& command) = 0; - - // Delete the client object - virtual void Delete() = 0; -}; - -//----------------------------------------------------------------------------- - -/// Remote command manager -struct IRemoteCommandManager -{ -public: - virtual ~IRemoteCommandManager() {}; - - // Set debug message verbose level - virtual void SetVerbosityLevel(const uint32 level) = 0; - - // Create local server for executing remote commands on given local port - virtual IRemoteCommandServer* CreateServer(uint16 localPort) = 0; - - // Create client interface for executing remote commands on remote servers - virtual IRemoteCommandClient* CreateClient() = 0; - - // Register command class (will be accessible by both clients and server) - virtual void RegisterCommandClass(IRemoteCommandClass& commandClass) = 0; -}; - -//----------------------------------------------------------------------------- - -/// Class RTTI wrapper for remote command classes -template< typename T > -class CRemoteCommandClass - : public IRemoteCommandClass -{ -private: - const char* m_szName; - -public: - CRemoteCommandClass(const char* szName) - : m_szName(szName) - {} - - virtual const char* GetName() const - { - return m_szName; - } - - virtual struct IRemoteCommand* CreateObject() - { - return new T(); - } -}; - -#define DECLARE_REMOTE_COMMAND(x) \ -public: static IRemoteCommandClass& GetStaticClass() { \ - static IRemoteCommandClass* theClass = new CRemoteCommandClass(#x); return *theClass; } \ -public: virtual IRemoteCommandClass* GetClass() const { return &GetStaticClass(); } \ -public: virtual void Delete() { delete this; } \ -public: virtual void SaveToStream(IDataWriteStream & writeStream) const { const_cast(this)->Serialize(writeStream); } \ -public: virtual void LoadFromStream(IDataReadStream & readStream) { Serialize(readStream); } - -//----------------------------------------------------------------------------- - -/// CryString serialization helper (read) -inline IDataReadStream& operator<<(IDataReadStream& stream, string& outString) -{ - const uint32 kMaxTempString = 256; - - // read length - uint32 length = 0; - stream << length; - - // load string - if (length > 0) - { - if (length < kMaxTempString) - { - // load the string into temporary buffer - char temp[kMaxTempString]; - stream.Read(&temp, length); - temp[length] = 0; - - // set the string with new value - outString = temp; - } - else - { - // allocate temporary memory and load the string - std::vector temp; - temp.resize(length + 1, 0); - stream.Read(&temp[0], length); - - // set the string with new value - outString = &temp[0]; - } - } - else - { - // empty string - outString.clear(); - } - - return stream; -} - -/// CryString serialization helper (write) -inline IDataWriteStream& operator<<(IDataWriteStream& stream, const string& str) -{ - // write length - const uint32 length = static_cast(str.length()); - stream << length; - - // write string data - if (length > 0) - { - stream.Write(str.c_str(), length); - } - - return stream; -} - -//------------------------------------------------------------------------ - -/// Vector serialization helper (reading) -template< class T > -IDataReadStream& operator<<(IDataReadStream& ar, std::vector& outVector) -{ - // Load item count - uint32 count = 0; - ar << count; - - // Adapt the vector size (exact fit) - outVector.resize(count); - - // Load items - for (uint32 i = 0; i < count; ++i) - { - ar << outVector[i]; - } - - return ar; -} - -/// Vector serialization helper (writing) -template< class T > -IDataWriteStream& operator<<(IDataWriteStream& ar, const std::vector& vec) -{ - // Save item count - const uint32 count = vec.size(); - ar << count; - - // Save items - for (uint32 i = 0; i < count; ++i) - { - ar << const_cast(vec[i]); - } - - return ar; -} - -//------------------------------------------------------------------------ - -inline void IDataWriteStream::WriteString(const char* str) -{ - string tempString(str); - *this << tempString; -} - -inline void IDataWriteStream::WriteString(const string& str) -{ - *this << str; -} - -inline string IDataReadStream::ReadString() -{ - string ret; - *this << ret; - return ret; -} - -inline void IDataReadStream::SkipString() -{ - // read length - uint32 length = 0; - *this << length; - Skip(length); -} - - -//------------------------------------------------------------------------ - -// Helper class for using the data reader and writer classes -// The only major differce betwen auto_ptr is that we call Delete() instead of operator delete -template -class TAutoDelete -{ -public: - T* m_ptr; - -public: - TAutoDelete(T* ptr) - : m_ptr(ptr) - { - } - - ~TAutoDelete() - { - if (NULL != m_ptr) - { - m_ptr->Delete(); - m_ptr = NULL; - } - } - - operator bool() - { - return (NULL != m_ptr); - } - - operator T& () - { - return *m_ptr; - } - - T* operator->() - { - return m_ptr; - } - -private: - TAutoDelete(const TAutoDelete& other) - : m_ptr(NULL){}; - TAutoDelete& operator=(const TAutoDelete& other) { return *this; } -}; - -//------------------------------------------------------------------------ - - -#endif // CRYINCLUDE_CRYCOMMON_IREMOTECOMMAND_H diff --git a/Code/CryEngine/CryCommon/IServiceNetwork.h b/Code/CryEngine/CryCommon/IServiceNetwork.h deleted file mode 100644 index 3df3f79abd..0000000000 --- a/Code/CryEngine/CryCommon/IServiceNetwork.h +++ /dev/null @@ -1,344 +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 : Service network interface - - -#ifndef CRYINCLUDE_CRYCOMMON_ISERVICENETWORK_H -#define CRYINCLUDE_CRYCOMMON_ISERVICENETWORK_H -#pragma once - - -#include -//----------------------------------------------------------------------------- -// -// Service network is a simple abstract interface for connecting between instances -// of the editor and game running on various platforms. It implements it's own -// small message based communication layer and shall not be used for raw communication -// with anything else. -// -// Features currently implemented by the service network: -// - Completely thread safe (so can be used from within other threads) -// - Completely asynchronous (only one thread) -// - Message based approach (both on the send and receive ends) -// - Automatic and transparent reconnection -// - Debug-friendly (will not time-out easily when one of the endpoints is being debugged) -// - Easy to use -// -// Usage case (server) -// - Create listener (IServiceListener) on some pre-defined port -// - Poll the incoming connections by calling Accept() method -// - Service the traffic by calling connection's ReceiveMessage()/SendMessage() methods -// - Close() and Release() connections -// - Close() and Release() listener -// -// Usage case (client) -// - Connect to a remote listener by calling Connect() method -// - Service the traffic by calling connection's ReceiveMessage()/SendMessage() methods -// - Close() and Release() connection -// -// Both sending and receiving is asynchronous. Calling the SendMessage()/ReceiveMessage() methods -// only pushes/pops the message buffers to/from the queue. -// NOTE: Message buffers are internally reference counted by the network system and they are kept around -// untill they are sent (in case of outgoing traffic) or untill they are polled by ReceiveMessage(). -// Be aware that this can cause memory spikes, especially when incoming traffic is not serviced fast enough. -// There are customizable limits (around 1MB) on the amount of data that can be buffered internally by -// the service network before the new messages are rejected. -// It's up to the higher layer to ensure damage control in such situation. -// -// NOTE: connection is also a reference counted object, make sure to call Close() before calling Release(). -// -//----------------------------------------------------------------------------- - -/// Network address abstraction -class ServiceNetworkAddress -{ -public: - struct StringAddress - { - char m_data[32]; - - ILINE const char* c_str() const - { - return m_data; - } - }; - - struct Address - { - uint8 m_ip0; - uint8 m_ip1; - uint8 m_ip2; - uint8 m_ip3; - uint16 m_port; - - ILINE Address() - : m_ip0(0) - , m_ip1(0) - , m_ip2(0) - , m_ip3(0) - , m_port(0) - {} - }; - -private: - Address m_address; - -public: - // By default creates ("invalid address") - ILINE ServiceNetworkAddress() - { - } - - // Copy (with optional port change) - ILINE ServiceNetworkAddress(const ServiceNetworkAddress& other, uint16 newPort = 0) - : m_address(other.m_address) - { - if (newPort != 0) - { - m_address.m_port = newPort; - } - } - - // Initialize from ip:host pattern (if you want to initialize from host name use the DebugNetwork interface) - ILINE ServiceNetworkAddress(uint8 ip0, uint8 ip1, uint8 ip2, uint8 ip3, uint16 port) - { - m_address.m_ip0 = ip0; - m_address.m_ip1 = ip1; - m_address.m_ip2 = ip2; - m_address.m_ip3 = ip3; - m_address.m_port = port; - } - - // Set new port value - ILINE void SetPort(uint16 port) - { - m_address.m_port = port; - } - - // Is this a valid address - ILINE bool IsValid() const - { - return (m_address.m_ip0 != 0) && - (m_address.m_ip1 != 1) && - (m_address.m_ip2 != 1) && - (m_address.m_ip3 != 1) && - (m_address.m_port != 0); - } - - // Convert to human readable string - ILINE StringAddress ToString() const - { - // format the string buffer - StringAddress ret; - sprintf_s(ret.m_data, sizeof(ret.m_data), - "%d.%d.%d.%d:%d", - m_address.m_ip0, m_address.m_ip1, m_address.m_ip2, m_address.m_ip3, - m_address.m_port); - - // return as managed string - return ret; - } - - // Get the literal data - ILINE const Address& GetAddress() const - { - return m_address; - } - -public: - // Compare base address (IP only) of two connections - static bool CompareBaseAddress(const ServiceNetworkAddress& a, const ServiceNetworkAddress& b) - { - return (a.m_address.m_ip0 == b.m_address.m_ip0) && - (a.m_address.m_ip1 == b.m_address.m_ip1) && - (a.m_address.m_ip2 == b.m_address.m_ip2) && - (a.m_address.m_ip3 == b.m_address.m_ip3); - } - - // Compare full address (IP+port) of two connections - static bool CompareFullAddress(const ServiceNetworkAddress& a, const ServiceNetworkAddress& b) - { - return (a.m_address.m_ip0 == b.m_address.m_ip0) && - (a.m_address.m_ip1 == b.m_address.m_ip1) && - (a.m_address.m_ip2 == b.m_address.m_ip2) && - (a.m_address.m_ip3 == b.m_address.m_ip3) && - (a.m_address.m_port == b.m_address.m_port); - } -}; - -//----------------------------------------------------------------------------- - -/// Message buffer used by the network system -struct IServiceNetworkMessage -{ -protected: - IServiceNetworkMessage() {}; - virtual ~IServiceNetworkMessage() {}; - -public: - // Get unique message ID (message ID is used just once) - virtual uint32 GetId() const = 0; - - // Get the size of message buffer - virtual uint32 GetSize() const = 0; - - // Get pointer to the message data - virtual void* GetPointer() = 0; - - // Get pointer to the message data - virtual const void* GetPointer() const = 0; - - // Create reader interface for reading message data, returned object is not - // reference counted but it will hold a reference to the message. - virtual struct IDataReadStream* CreateReader() const = 0; - - // Add reference (buffer is internally refcounted) - virtual void AddRef() = 0; - - // Release reference - virtual void Release() = 0; -}; - -//----------------------------------------------------------------------------- - -/// General network TCP/IP connection -struct IServiceNetworkConnection -{ -protected: - IServiceNetworkConnection() {}; - virtual ~IServiceNetworkConnection() {}; - -public: - static const uint32 kDefaultFlushTime = 10000; // ms - - // Get the unique connection ID (is shared between host and client) - virtual const CryGUID& GetGUID() const = 0; - - // Get remote endpoint address - virtual const ServiceNetworkAddress& GetRemoteAddress() const = 0; - - // Get local endpoint address - virtual const ServiceNetworkAddress& GetLocalAddress() const = 0; - - // Add a message buffer to the connection send queue. - // Connection can refuse to send the buffer if it's full or invalid. - // If a message is rejected this function returns false. - virtual bool SendMsg(IServiceNetworkMessage* message) = 0; - - // Get a message from connection receive queue. - // If there are no pending messages a NULL is returned. - // Since message is a ref-counted you need to call Release() when you are done with the buffer. - virtual IServiceNetworkMessage* ReceiveMsg() = 0; - - // Checks if connection is still alive. - // Returns false only if connection has been damaged beyond repair. - virtual bool IsAlive() const = 0; - - // Get number of messages sent by this connection so far - virtual uint32 GetMessageSendCount() const = 0; - - // Get number of messages received by this connection so far - virtual uint32 GetMessageReceivedCount() const = 0; - - // Get size of data sent by this connection so far - virtual uint64 GetMessageSendDataSize() const = 0; - - // Get size of data received by this connection so far - virtual uint64 GetMessageReceivedDataSize() const = 0; - - // Request connection to be closed but not before sending out all of the pending messages. Incoming messages are ignored. - // Processing and sending the messages is done on the networking thread so this function will not block. - // As an option, connection can be forcefully closed after given amount of time (in ms). - virtual void FlushAndClose(const uint32 timeoutMs = kDefaultFlushTime) = 0; - - // Synchronous wait for the connection to send all outgoing messages - virtual void FlushAndWait() = 0; - - // Request connection to be closed now. All pending messages are discarded. - virtual void Close() = 0; - - // Add reference (connection is an internally reference counted object) - virtual void AddRef() = 0; - - // Release reference - virtual void Release() = 0; -}; - -//----------------------------------------------------------------------------- - -/// General listening socket (async) -struct IServiceNetworkListener -{ -protected: - IServiceNetworkListener() {}; - virtual ~IServiceNetworkListener() {}; - -public: - // Get the local address - virtual const ServiceNetworkAddress& GetLocalAddress() const = 0; - - // Get number of active connections handled by this listener - virtual uint GetConnectionCount() const = 0; - - // Accept incoming connection (asynchronously) - // Will return NULL if there's nothing to accept - // Will return new IDebugNetworkConnection if something was received - virtual IServiceNetworkConnection* Accept() = 0; - - // Is listener able to accept connections ? - virtual bool IsAlive() const = 0; - - // Request listener to be closed (closes the socket) - virtual void Close() = 0; - - // Add reference (listener is an internally reference counted object) - virtual void AddRef() = 0; - - // Release reference - virtual void Release() = 0; -}; - -//----------------------------------------------------------------------------- - -/// General service (background) network interface -struct IServiceNetwork -{ -public: - virtual ~IServiceNetwork() {}; - - // Set verbosity level of debug messages that got printed to log, levels 0-3 are commonly used - virtual void SetVerbosityLevel(const uint32 level) = 0; - - // Allocate empty message buffer of given size, message buffer is a reference counted object - virtual IServiceNetworkMessage* AllocMessageBuffer(const uint32 size) = 0; - - // Create general message writer stream, object is not reference counted - virtual struct IDataWriteStream* CreateMessageWriter() = 0; - - // Create general message reader stream and initialize it with data - virtual struct IDataReadStream* CreateMessageReader(const void* pData, const uint32 dataSize) = 0; - - // Translate host address (string:port) to network address - virtual ServiceNetworkAddress GetHostAddress(const string& addressString, uint16 optionalPort = 0) const = 0; - - // Create network listener on given local port, listening and accepting connections is done on network thread - virtual IServiceNetworkListener* CreateListener(uint16 localPort) = 0; - - // Connect to remote address (will block until connection is made or refused) - virtual IServiceNetworkConnection* Connect(const ServiceNetworkAddress& remoteAddress) = 0; -}; - -//----------------------------------------------------------------------------- - -#endif // CRYINCLUDE_CRYCOMMON_ISERVICENETWORK_H diff --git a/Code/CryEngine/CryCommon/ISystem.h b/Code/CryEngine/CryCommon/ISystem.h index 93de0008b0..86c2b57464 100644 --- a/Code/CryEngine/CryCommon/ISystem.h +++ b/Code/CryEngine/CryCommon/ISystem.h @@ -91,7 +91,6 @@ struct IAVI_Reader; class CPNoise3; struct IVisualLog; struct ILocalizationManager; -struct ICryFactoryRegistry; struct ISoftCodeMgr; struct IZLibCompressor; struct IZLibDecompressor; @@ -99,8 +98,6 @@ struct ILZ4Decompressor; class IZStdDecompressor; struct IOutputPrintSink; struct IThreadManager; -struct IServiceNetwork; -struct IRemoteCommandManager; struct IWindowMessageHandler; struct IImageHandler; class IResourceCompilerHelper; @@ -798,8 +795,6 @@ struct SSystemGlobalEnvironment IRenderer* pRenderer; IMaterialEffects* pMaterialEffects; ISoftCodeMgr* pSoftCodeMgr; - IServiceNetwork* pServiceNetwork; - IRemoteCommandManager* pRemoteCommandManager; ILyShine* pLyShine; IResourceCompilerHelper* pResourceCompilerHelper; SharedEnvironmentInstance* pSharedEnvironment; @@ -1244,10 +1239,6 @@ struct ISystem // Retrieves access to XML utilities interface. virtual IXmlUtils* GetXmlUtils() = 0; - // Summary: - // Interface to access different implementations of Serialization::IArchive in a centralized way. - virtual Serialization::IArchiveHost* GetArchiveHost() const = 0; - virtual void SetViewCamera(CCamera& Camera) = 0; virtual CCamera& GetViewCamera() = 0; @@ -1368,10 +1359,6 @@ struct ISystem // Retrieves system update counter. virtual uint64 GetUpdateCounter() = 0; - // Summary: - // Gets access to all registered factories. - virtual ICryFactoryRegistry* GetCryFactoryRegistry() const = 0; - ////////////////////////////////////////////////////////////////////////// // Error callback handling @@ -1491,15 +1478,6 @@ struct ISystem virtual const IImageHandler* GetImageHandler() const = 0; - // Summary: - // Loads a dynamic library, creates and initializes an instance of the module class - - virtual bool InitializeEngineModule(const char* dllName, const char* moduleClassName, const SSystemInitParams& initParams) = 0; - - // Summary: - // Unloads a dynamic library as well as the corresponding instance of the module class - virtual bool UnloadEngineModule(const char* dllName, const char* moduleClassName) = 0; - // Summary: // Gets the root window message handler function // The returned pointer is platform-specific: diff --git a/Code/CryEngine/CryCommon/Mocks/IConsoleMock.h b/Code/CryEngine/CryCommon/Mocks/IConsoleMock.h index 31509ca6ba..3d4327116e 100644 --- a/Code/CryEngine/CryCommon/Mocks/IConsoleMock.h +++ b/Code/CryEngine/CryCommon/Mocks/IConsoleMock.h @@ -13,7 +13,6 @@ #define CRYINCLUDE_CRYCOMMON_ICONSOLEMOCK_H #pragma once -#include #include #include diff --git a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h index 9e5182ebcf..1e28937764 100644 --- a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h +++ b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h @@ -164,8 +164,6 @@ public: XmlNodeRef(const char*, bool)); MOCK_METHOD0(GetXmlUtils, IXmlUtils * ()); - MOCK_CONST_METHOD0(GetArchiveHost, - Serialization::IArchiveHost * ()); MOCK_METHOD1(SetViewCamera, void(CCamera & Camera)); MOCK_METHOD0(GetViewCamera, @@ -223,8 +221,6 @@ public: CPNoise3 * ()); MOCK_METHOD0(GetUpdateCounter, uint64()); - MOCK_CONST_METHOD0(GetCryFactoryRegistry, - ICryFactoryRegistry * ()); MOCK_METHOD1(RegisterErrorObserver, bool(IErrorObserver * errorObserver)); MOCK_METHOD1(UnregisterErrorObserver, @@ -287,10 +283,6 @@ public: bool()); MOCK_CONST_METHOD0(GetImageHandler, const IImageHandler * ()); - MOCK_METHOD3(InitializeEngineModule, - bool(const char* dllName, const char* moduleClassName, const SSystemInitParams&initParams)); - MOCK_METHOD2(UnloadEngineModule, - bool(const char* dllName, const char* moduleClassName)); MOCK_METHOD0(GetRootWindowMessageHandler, void*()); MOCK_METHOD1(RegisterWindowMessageHandler, diff --git a/Code/CryEngine/CryCommon/Serialization/Assert.h b/Code/CryEngine/CryCommon/Serialization/Assert.h deleted file mode 100644 index a1ce890dc8..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Assert.h +++ /dev/null @@ -1,46 +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_SERIALIZATION_ASSERT_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_ASSERT_H -#pragma once - -#ifdef SERIALIZATION_STANDALONE -#include -#else -#include -#endif - -#ifdef YASLI_ASSERT -# undef YASLI_ASSERT -#endif - -#ifdef YASLI_VERIFY -# undef YASLI_VERIFY -#endif - -#ifdef YASLI_ESCAPE -# undef YASLI_ESCAPE -#endif - -#ifdef SERIALIZATION_STANDALONE -#define YASLI_ASSERT(x) assert(x) -#define YASLI_ASSERT_STR(x, str) assert(x && str) -#define YASLI_ESCAPE(x, action) if (!(x)) { YASLI_ASSERT(0 && #x); action; }; -#else -#define YASLI_ASSERT(x) CRY_ASSERT(x) -#define YASLI_ASSERT_STR(x, str) CRY_ASSERT_MESSAGE(x, str) -#define YASLI_ESCAPE(x, action) if (!(x)) { YASLI_ASSERT(0 && #x); action; }; -#endif // SERIALIZATION_STANDALONE - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_ASSERT_H diff --git a/Code/CryEngine/CryCommon/Serialization/BitVector.h b/Code/CryEngine/CryCommon/Serialization/BitVector.h deleted file mode 100644 index 06cb3b956a..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/BitVector.h +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2012 Crytek GmbH -// Authors: Evgeny Andreeshchev, Alexander Kotliar -// Based on: Yasli - the serialization library. -// Modifications copyright Amazon.com, Inc. or its affiliates - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTOR_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTOR_H -#pragma once - - -namespace Serialization{ - -class IArchive; -template -class BitVector -{ -public: - BitVector(int value = 0) : value_(value) {} - - operator int&() { return value_; } - operator int() const { return value_; } - - BitVector& operator|= (Enum value) { value_ |= value; return *this; } - BitVector& operator|= (int value) { value_ |= value; return *this; } - BitVector& operator&= (int value) { value_ &= value; return *this; } - - void Serialize(IArchive& ar); -private: - int value_; -}; - -template -bool Serialize(Serialization::IArchive& ar, Serialization::BitVector& value, const char* name, const char* label); - -} - -#include "BitVectorImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTOR_H diff --git a/Code/CryEngine/CryCommon/Serialization/BitVectorImpl.h b/Code/CryEngine/CryCommon/Serialization/BitVectorImpl.h deleted file mode 100644 index 1d5c02342c..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/BitVectorImpl.h +++ /dev/null @@ -1,88 +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_SERIALIZATION_BITVECTORIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTORIMPL_H -#pragma once - -#include "Serialization/BitVector.h" -#include "Serialization/IArchive.h" -#include "Serialization/Enum.h" - -namespace Serialization { - struct BitVectorWrapper - { - int* valuePointer; - int value; - const CEnumDescription* description; - - explicit BitVectorWrapper(int* _value = 0, const CEnumDescription* _description = 0) - : valuePointer(_value) - , description(_description) - { - if (valuePointer) - { - value = *valuePointer; - } - } - BitVectorWrapper(const BitVectorWrapper& _rhs) - : value(_rhs.value) - , description(0) - , valuePointer(0) - { - } - - ~BitVectorWrapper() - { - if (valuePointer) - { - * valuePointer = value; - } - } - BitVectorWrapper& operator=(const BitVectorWrapper& rhs) - { - value = rhs.value; - return *this; - } - - - void Serialize(IArchive& ar) - { - ar(value, "value", "Value"); - } - }; - - template - void BitVector::Serialize(IArchive& ar) - { - ar(value_, "value", "Value"); - } -} - -template -bool Serialize(Serialization::IArchive& ar, Serialization::BitVector& value, const char* name, const char* label) -{ - using namespace Serialization; - CEnumDescription& desc = getEnumDescription(); - if (ar.IsEdit()) - { - return ar(BitVectorWrapper(&static_cast(value), &desc), name, label); - } - else - { - return desc.serializeBitVector(ar, static_cast(value), name, label); - } -} - - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTORIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/BlackBox.h b/Code/CryEngine/CryCommon/Serialization/BlackBox.h deleted file mode 100644 index 7efbbf7ece..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/BlackBox.h +++ /dev/null @@ -1,93 +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_SERIALIZATION_BLACKBOX_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_BLACKBOX_H -#pragma once - -#include // for malloc and free - -namespace Serialization -{ - // Black box is used to store opaque data blobs in a format internal to - // specific Archive. For example it can be used to store sections of the JSON - // or binary archive. - // - // This is useful for the Editor to store portions of files with unfamiliar - // structure. - // - // We store deallocation function here so we can safely pass the blob - // across DLLs with different memory allocators. - struct SBlackBox - { - const char* format; - void* data; - size_t size; - typedef void(* FreeFunction)(void*); - FreeFunction freeFunction; - - SBlackBox() - : format("") - , data(0) - , size(0) - , freeFunction(0) - { - } - - SBlackBox(const SBlackBox& rhs) - : format("") - , data(0) - , size(0) - , freeFunction(0) - { - *this = rhs; - } - - void set(const char* _format, const void* _data, size_t _size) - { - if (_data && freeFunction) - { - freeFunction(this->data); - this->data = 0; - this->size = 0; - freeFunction = 0; - } - this->format = _format; - if (_data && _size) - { - this->data = CryModuleMalloc(_size); - memcpy(this->data, _data, _size); - this->size = _size; - freeFunction = &Free; - } - } - - SBlackBox& operator=(const SBlackBox& rhs) - { - set(rhs.format, rhs.data, rhs.size); - return *this; - } - - ~SBlackBox() - { - set("", 0, 0); - } - - static void Free(void* ptr) - { - CryModuleFree(ptr); - } - }; -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_BLACKBOX_H diff --git a/Code/CryEngine/CryCommon/Serialization/BoostSharedPtr.h b/Code/CryEngine/CryCommon/Serialization/BoostSharedPtr.h deleted file mode 100644 index 7d1d8591d0..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/BoostSharedPtr.h +++ /dev/null @@ -1,102 +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 - -#include - -#include "ClassFactory.h" - -template -class BoostSharedPtrSerializer - : public Serialization::IPointer -{ -public: - BoostSharedPtrSerializer(AZStd::shared_ptr& ptr) - : m_ptr(ptr) - { - } - - const char* registeredTypeName() const override - { - if (m_ptr) - { - return factoryOverride().getRegisteredTypeName(m_ptr.get()); - } - else - { - return ""; - } - } - - void create(const char* registeredTypeName) const override - { - CRY_ASSERT(!m_ptr || m_ptr.use_count() == 1); - if (registeredTypeName && registeredTypeName[0] != '\0') - { - m_ptr.reset(factoryOverride().create(registeredTypeName)); - } - else - { - m_ptr.reset(); - } - } - - Serialization::TypeID baseType() const override - { - return Serialization::TypeID::get(); - } - - virtual Serialization::SStruct serializer() const override - { - return Serialization::SStruct(*m_ptr); - } - - void* get() const - { - return reinterpret_cast(m_ptr.get()); - } - - const void* handle() const - { - return &m_ptr; - } - - Serialization::TypeID pointerType() const override - { - return Serialization::TypeID::get >(); - } - - Serialization::ClassFactory* factory() const override - { - return &factoryOverride(); - } - - virtual Serialization::ClassFactory& factoryOverride() const - { - return Serialization::ClassFactory::the(); - } - -protected: - AZStd::shared_ptr& m_ptr; -}; - -namespace AZStd -{ - template - bool Serialize(Serialization::IArchive& ar, AZStd::shared_ptr& ptr, const char* name, const char* label) - { - BoostSharedPtrSerializer serializer(ptr); - return ar(static_cast(serializer), name, label); - } -} diff --git a/Code/CryEngine/CryCommon/Serialization/CRCRef.h b/Code/CryEngine/CryCommon/Serialization/CRCRef.h deleted file mode 100644 index b26195dd99..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/CRCRef.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_CRYCOMMON_SERIALIZATION_CRCREF_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREF_H -#pragma once - -template -struct SCRCRef; - -namespace Serialization -{ - class IArchive; -} - -template -bool Serialize(Serialization::IArchive& ar, SCRCRef& crcRef, const char* name, const char* label); - -#include "CRCRefImpl.h" -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREF_H diff --git a/Code/CryEngine/CryCommon/Serialization/CRCRefImpl.h b/Code/CryEngine/CryCommon/Serialization/CRCRefImpl.h deleted file mode 100644 index 28b0f4305b..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/CRCRefImpl.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREFIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREFIMPL_H -#pragma once - -#include "IArchive.h" -#include "Serializer.h" - -template -class CRCRefSerializer - : public Serialization::IString -{ -public: - CRCRefSerializer(TCRCRef& crcRef) - : m_crcRef(crcRef) - { - } - - virtual void set(const char* value) - { - m_crcRef.SetByString(value); - } - - virtual const char* get() const - { - return m_crcRef.c_str(); - } - - const void* handle() const - { - return &m_crcRef; - } - - Serialization::TypeID type() const - { - return Serialization::TypeID::get(); - } - - - TCRCRef& m_crcRef; -}; - - -template -class CCRCRefSerializerNoStrings -{ -public: - CCRCRefSerializerNoStrings(struct SCRCRef& crcRef) - : crc(crcRef.crc) - { - } - - bool Serialize(Serialization::IArchive& ar) - { - return ar(crc, "CRC", "CRC"); - } - - typedef typename THash::TInt TInt; - TInt& crc; -}; - - - -template -bool Serialize(Serialization::IArchive& ar, struct SCRCRef& crcRef, const char* name, const char* label) -{ - if (StoreStrings == 0) - { - if (ar.IsInput()) - { - SCRCRef crcCopy; - ar(CCRCRefSerializerNoStrings(crcCopy), name, label); - if (crcCopy.crc != THash::INVALID) - { - crcRef = crcCopy; - return true; - } - } - else if (ar.IsOutput()) - { - return ar(CCRCRefSerializerNoStrings(crcRef), name, label); - } - } - - CRCRefSerializer > crcRefSerializer(crcRef); - return ar(static_cast(crcRefSerializer), name, label); -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREFIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Callback.h b/Code/CryEngine/CryCommon/Serialization/Callback.h deleted file mode 100644 index 0a0ce2b7f8..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Callback.h +++ /dev/null @@ -1,184 +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_SERIALIZATION_CALLBACK_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CALLBACK_H -#pragma once - -#include - -namespace Serialization -{ - struct ICallback - { - virtual bool SerializeValue(IArchive& ar, const char* name, const char* value) = 0; - virtual ICallback* Clone() = 0; - virtual void Release() = 0; - virtual TypeID Type() const = 0; - - typedef AZStd::function ApplyFunction; - virtual void Call(const ApplyFunction&) = 0; - }; - - template - struct CallbackSimple - : ICallback - { - typedef AZStd::function CallbackFunction; - T* value; - T oldValue; - CallbackFunction callback; - - CallbackSimple(T* value, const T& oldValue, const AZStd::function& callback) - : value(value) - , oldValue(oldValue) - , callback(callback) - { - } - - ICallback* Clone() { return new CallbackSimple(0, oldValue, callback); } - void Release() { delete this; } - bool SerializeValue(IArchive& ar, const char* name, const char* label) { return ar(*value, name, label); } - TypeID Type() const{ return TypeID::get(); } - - void Call(const ApplyFunction& applyFunction) - { - T newValue; - applyFunction((void*)&newValue, TypeID::get()); - if (oldValue != newValue) - { - callback(newValue); - oldValue = newValue; - } - } - }; - - template - struct CallbackWithDecorator - : ICallback - { - typedef AZStd::function CallbackFunction; - typedef AZStd::function DecoratorFunction; - - T oldValue; - T* value; - CallbackFunction callback; - DecoratorFunction decorator; - - CallbackWithDecorator(T* value, - const T& oldValue, - const CallbackFunction& callback, - const DecoratorFunction& decorator) - : value(value) - , oldValue(oldValue) - , callback(callback) - , decorator(decorator) - { - } - - ICallback* Clone() { return new CallbackWithDecorator(0, oldValue, callback, decorator); } - void Release() { delete this; } - bool SerializeValue(IArchive& ar, const char* name, const char* label) { return ar(decorator(*value), name, label); } - TypeID Type() const{ return TypeID::get(); } - - void Call(const ApplyFunction& applyFunction) - { - T newValue; - Decorator dec = decorator(newValue); - applyFunction((void*)&dec, TypeID::get()); - if (oldValue != newValue) - { - callback(newValue); - oldValue = newValue; - } - } - }; - - - - namespace Detail - { - template - struct MethodReturnType - { - typedef void type; - }; - - template - struct MethodReturnType - { - typedef ReturnType type; - }; - - template - struct OperatorBracketsReturnType - { - typedef typename MethodReturnType::type Type; - }; - } - - template - CallbackSimple - Callback(T& value, const CallbackFunc& callback) - { - return CallbackSimple(&value, value, AZStd::function(callback)); - } - - - template - CallbackWithDecorator::Type> - Callback(T& value, const CallbackFunc& callback, const DecoratorFunc& decorator) - { - typedef typename Detail::OperatorBracketsReturnType::Type Decorator; - return CallbackWithDecorator(&value, value, - AZStd::function(callback), - AZStd::function(decorator)); - } - - - template - bool Serialize(IArchive& ar, CallbackSimple& callback, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(static_cast(callback), name, label); - } - else - { - if (!ar(*callback.value, name, label)) - { - return false; - } - return true; - } - } - - template - bool Serialize(IArchive& ar, CallbackWithDecorator& callback, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(static_cast(callback), name, label); - } - else - { - if (!ar(*callback.value, name, label)) - { - return false; - } - return true; - } - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CALLBACK_H diff --git a/Code/CryEngine/CryCommon/Serialization/ClassFactory.h b/Code/CryEngine/CryCommon/Serialization/ClassFactory.h deleted file mode 100644 index 4734a566eb..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/ClassFactory.h +++ /dev/null @@ -1,376 +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_SERIALIZATION_CLASSFACTORY_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CLASSFACTORY_H -#pragma once - -#include -#include - -#include "Serialization/Assert.h" -#include "Serialization/IClassFactory.h" -#include "Serialization/TypeID.h" - -namespace Serialization { - class IArchive; - - class ClassFactoryManager - { - public: - static ClassFactoryManager& the() - { - static ClassFactoryManager factoryManager; - return factoryManager; - } - - const IClassFactory* find(TypeID baseType) const - { - lazyRegisterFactories(); - Factories::const_iterator it = factories_.find(baseType); - if (it == factories_.end()) - { - return 0; - } - else - { - return it->second; - } - } - - void registerFactory([[maybe_unused]] TypeID type, IClassFactory* factory) - { - factory->m_next = m_head; - m_head = factory; - } - protected: - void lazyRegisterFactories() const - { - if (m_head) - { - IClassFactory* factory = m_head; - while (factory) - { - const_cast(this)->factories_[factory->baseType_] = factory; - factory = factory->m_next; - } - const_cast(this)->m_head = nullptr; - } - } - - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> Factories; - Factories factories_; - IClassFactory* m_head = nullptr; - }; - - template - class ClassFactory - : public IClassFactory - { - public: - static ClassFactory& the() - { - static AZStd::aligned_storage_for_t storage; - if (s_instance != (decltype(s_instance))&storage) - { - s_instance = new(&storage) ClassFactory(); - } - return *s_instance; - } - - static void destroy() - { - if (s_instance) - { - s_instance->~ClassFactory(); - s_instance = nullptr; - } - } - - class CreatorBase - { - public: - virtual ~CreatorBase() {} - virtual BaseType* create() const = 0; - virtual const TypeDescription& description() const{ return *description_; } - virtual void* vptr() const { return vptr_; } - virtual TypeID typeID() const = 0; - protected: - const TypeDescription* description_ = nullptr; - void* vptr_ = nullptr; - public: - CreatorBase* next; - }; - - static void* extractVPtr(BaseType* ptr) - { - return *((void**)ptr); - } - - template - struct Annotation - { - Annotation(IClassFactory* factory, const char* name, const char* value) { static_cast*>(factory)->addAnnotation(name, value); } - }; - - template - class Creator - : public CreatorBase - { - public: - Creator(const TypeDescription* description, ClassFactory* factory = nullptr) - { - this->description_ = description; - - if (!factory) - { - factory = &ClassFactory::the(); - } - - factory->registerCreator(this); - } - - void* vptr() const override - { - if (!this->vptr_) - { - Derived vptrProbe; - const_cast(this)->vptr_ = extractVPtr(&vptrProbe); - } - return this->vptr_; - } - - BaseType* create() const override { return new Derived(); } - TypeID typeID() const override { return Serialization::TypeID::get(); } - }; - - ClassFactory() - : IClassFactory(TypeID::get()) - { - ClassFactoryManager::the().registerFactory(baseType_, this); - } - - ~ClassFactory() - { - m_data->~Data(); - m_data = nullptr; - } - - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> TypeToCreatorMap; - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> VPtrToCreatorMap; - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> RegisteredNameToTypeID; - typedef AZStd::unordered_map >, AZStd::hash, AZStd::equal_to, AZ::StdLegacyAllocator> AnnotationMap; - - virtual BaseType* create(const char* registeredName) const - { - lazyRegisterCreators(); - if (!registeredName) - { - return 0; - } - if (registeredName[0] == '\0') - { - return 0; - } - typename TypeToCreatorMap::const_iterator it = m_data->typeToCreatorMap_.find(registeredName); - if (it != m_data->typeToCreatorMap_.end()) - { - return it->second->create(); - } - else - { - return 0; - } - } - - virtual const char* getRegisteredTypeName(BaseType* ptr) const - { - lazyRegisterCreators(); - if (ptr == 0) - { - return ""; - } - void* vptr = extractVPtr(ptr); - typename VPtrToCreatorMap::const_iterator it = m_data->vptrToCreatorMap_.find(vptr); - if (it == m_data->vptrToCreatorMap_.end()) - { - return ""; - } - return it->second->description().name(); - } - - BaseType* createByIndex(int index) const - { - lazyRegisterCreators(); - YASLI_ASSERT(size_t(index) < m_data->creators_.size()); - return m_data->creators_[index]->create(); - } - - void serializeNewByIndex(IArchive& ar, int index, const char* name, const char* label) - { - lazyRegisterCreators(); - YASLI_ESCAPE(size_t(index) < m_data->creators_.size(), return ); - BaseType* ptr = m_data->creators_[index]->create(); - ar(*ptr, name, label); - delete ptr; - } - // from ClassFactoryInterface: - size_t size() const{ return m_data->creators_.size(); } - const TypeDescription* descriptionByIndex(int index) const override - { - lazyRegisterCreators(); - if (size_t(index) >= int(m_data->creators_.size())) - { - return 0; - } - return &m_data->creators_[index]->description(); - } - - const TypeDescription* descriptionByRegisteredName(const char* name) const override - { - lazyRegisterCreators(); - const size_t numCreators = m_data->creators_.size(); - for (size_t i = 0; i < numCreators; ++i) - { - if (strcmp(m_data->creators_[i]->description().name(), name) == 0) - { - return &m_data->creators_[i]->description(); - } - } - return 0; - } - // ^^^ - - TypeID typeIDByRegisteredName(const char* registeredTypeName) const - { - lazyRegisterCreators(); - RegisteredNameToTypeID::const_iterator it = m_data->registeredNameToTypeID_.find(registeredTypeName); - if (it == m_data->registeredNameToTypeID_.end()) - { - return TypeID(); - } - return it->second; - } - - const char* findAnnotation(const char* registeredTypeName, const char* name) const - { - lazyRegisterCreators(); - TypeID typeID = typeIDByRegisteredName(registeredTypeName); - AnnotationMap::const_iterator it = m_data->annotations_.find(typeID); - if (it == m_data->annotations_.end()) - { - return ""; - } - for (size_t i = 0; i < it->second.size(); ++i) - { - if (strcmp(it->second[i].first, name) == 0) - { - return it->second[i].second; - } - } - return ""; - } - void unregisterCreator(const TypeDescription& typeDescription) - { - auto creator = m_data->typeToCreatorMap_.find(typeDescription.name()); - if (creator != m_data->typeToCreatorMap_.end()) - { - m_data->creators_.erase(std::find(m_data->creators_.begin(), m_data->creators_.end(), m_data->creator->second)); - m_data->vptrToCreatorMap_.erase(m_data->vptrToCreatorMap_.find(creator->second->vptr())); - m_data->typeToCreatorMap_.erase(creator); - } - } - - protected: - virtual void registerCreator(CreatorBase* creator) - { - creator->next = creatorsList; - creatorsList = creator; - } - - void lazyRegisterCreators() const - { - if (!m_data) - { - const_cast(this)->m_data = ::new((void*)&m_dataStorage) Data(); - for (CreatorBase* creator = creatorsList; creator; creator = creator->next) - { - if (!const_cast(this)->m_data->typeToCreatorMap_.insert(AZStd::make_pair(creator->description().name(), creator)).second) - { - YASLI_ASSERT(0 && "Type registered twice in the same factory. Was SERIALIZATION_CLASS_NAME put into header file by mistake?"); - } - const_cast(this)->m_data->creators_.push_back(creator); - const_cast(this)->m_data->registeredNameToTypeID_[creator->description().name()] = creator->typeID(); - const_cast(this)->m_data->vptrToCreatorMap_[creator->vptr()] = creator; - } - } - } - - template - void addAnnotation(const char* name, const char* value) - { - addAnnotation(Serialization::TypeID::get(), name, value); - } - - virtual void addAnnotation(const Serialization::TypeID& id, const char* name, const char* value) - { - lazyRegisterCreators(); - m_data->annotations_[id].push_back(std::make_pair(name, value)); - } - - CreatorBase* creatorsList = nullptr; - static ClassFactory* s_instance; - - struct Data - { - TypeToCreatorMap typeToCreatorMap_; - AZStd::vector creators_; - VPtrToCreatorMap vptrToCreatorMap_; - RegisteredNameToTypeID registeredNameToTypeID_; - AnnotationMap annotations_; - }; - Data* m_data = nullptr; - AZStd::aligned_storage_for_t m_dataStorage; - }; - - template - ClassFactory* ClassFactory::s_instance = nullptr; -} - -#define SERIALIZATION_CLASS_NULL(BaseType, name) \ - namespace { \ - bool BaseType##_NullRegistered = Serialization::ClassFactory::the().setNullLabel(name); \ - } - -#define SERIALIZATION_CLASS_NAME(BaseType, Type, name, label) \ - static const Serialization::TypeDescription Type##BaseType##_DerivedDescription(name, label); \ - static Serialization::ClassFactory::Creator Type##BaseType##_Creator(&Type##BaseType##_DerivedDescription); \ - int dummyForType_##Type##BaseType; - -#define SERIALIZATION_CLASS_NAME_FOR_FACTORY(Factory, BaseType, Type, name, label) \ - static const Serialization::TypeDescription Type##BaseType##_DerivedDescription(name, label); \ - static Serialization::ClassFactory::Creator Type##BaseType##_Creator(&Type##BaseType##_DerivedDescription, &(Factory)); - -#define SERIALIZATION_CLASS_ANNOTATION(BaseType, Type, attributeName, attributeValue) \ - static Serialization::ClassFactory::Annotation Type##BaseType##_Annotation(&Serialization::ClassFactory::the(), attributeName, attributeValue); - -#define SERIALIZATION_CLASS_ANNOTATION_FOR_FACTORY(factory, BaseType, Type, attributeName, attributeValue) \ - static Serialization::ClassFactory::Annotation Type##BaseType##_Annotation(&factory, attributeName, attributeValue); - -#define SERIALIZATION_FORCE_CLASS(BaseType, Type) \ - extern int dummyForType_##Type##BaseType; \ - int* dummyForTypePtr_##Type##BaseType = &dummyForType_##Type##BaseType + 1; - -#include "ClassFactoryImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CLASSFACTORY_H diff --git a/Code/CryEngine/CryCommon/Serialization/ClassFactoryImpl.h b/Code/CryEngine/CryCommon/Serialization/ClassFactoryImpl.h deleted file mode 100644 index f3d034fb51..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/ClassFactoryImpl.h +++ /dev/null @@ -1,47 +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_SERIALIZATION_CLASSFACTORYIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CLASSFACTORYIMPL_H -#pragma once - -#include "IArchive.h" -#include "IClassFactory.h" -#include "STL.h" -#include "ClassFactory.h" -#include "Strings.h" - -namespace Serialization { - inline bool Serialize(Serialization::IArchive& ar, Serialization::TypeNameWithFactory& value, const char* name, [[maybe_unused]] const char* label) - { - if (!ar(value.registeredName, name)) - { - return false; - } - - if (ar.IsInput()) - { - const TypeDescription* desc = value.factory->descriptionByRegisteredName(value.registeredName.c_str()); - if (!desc) - { - ar.Error(value, "Unable to read TypeID: unregistered type name: \'%s\'", value.registeredName.c_str()); - value.registeredName.clear(); - return false; - } - } - return true; - } -} - - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CLASSFACTORYIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Color.h b/Code/CryEngine/CryCommon/Serialization/Color.h deleted file mode 100644 index 1b4f612bcd..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Color.h +++ /dev/null @@ -1,55 +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_SERIALIZATION_COLOR_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_COLOR_H -#pragma once - -#include -#include - -template -inline bool Serialize(Serialization::IArchive& ar, Color_tpl& c, const char* name, const char* label); - -namespace Serialization -{ - struct Vec3AsColor - { - Vec3& v; - Vec3AsColor(Vec3& v) - : v(v) {} - - void Serialize(Serialization::IArchive& ar) - { - ar(Range(v.x, 0.0f, 1.0f), "r", "^"); - ar(Range(v.y, 0.0f, 1.0f), "g", "^"); - ar(Range(v.z, 0.0f, 1.0f), "b", "^"); - } - }; - - inline bool Serialize(Serialization::IArchive& ar, Vec3AsColor& c, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct(c), name, label); - } - else - { - typedef float (* Array)[3]; - return ar(*((Array) & c.v.x), name, label); - } - } -} - -#include "ColorImpl.h" -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_COLOR_H diff --git a/Code/CryEngine/CryCommon/Serialization/ColorImpl.h b/Code/CryEngine/CryCommon/Serialization/ColorImpl.h deleted file mode 100644 index cf7f5886d7..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/ColorImpl.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_SERIALIZATION_COLORIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_COLORIMPL_H -#pragma once - -#include "Color.h" - -////////////////////////////////////////////////////////////////////////// -template -struct SerializableColor_tpl - : Color_tpl -{ - static float ColorRangeMin(float) { return 0.0f; } - static float ColorRangeMax(float) { return 1.0f; } - static unsigned char ColorRangeMin(unsigned char) { return 0; } - static unsigned char ColorRangeMax(unsigned char) { return 255; } - - void Serialize(Serialization::IArchive& ar) - { - ar(Serialization::Range(Color_tpl::r, ColorRangeMin(Color_tpl::r), ColorRangeMax(Color_tpl::r)), "r", "^"); - ar(Serialization::Range(Color_tpl::g, ColorRangeMin(Color_tpl::g), ColorRangeMax(Color_tpl::g)), "g", "^"); - ar(Serialization::Range(Color_tpl::b, ColorRangeMin(Color_tpl::b), ColorRangeMax(Color_tpl::b)), "b", "^"); - ar(Serialization::Range(Color_tpl::a, ColorRangeMin(Color_tpl::a), ColorRangeMax(Color_tpl::a)), "a", "^"); - } -}; - -template -bool Serialize(Serialization::IArchive& ar, Color_tpl& c, const char* name, const char* label) -{ - if (ar.IsEdit()) - { - return Serialize(ar, static_cast&>(c), name, label); - } - else - { - typedef T (& Array)[4]; - return ar((Array)c, name, label); - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_COLORIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/CryExtension.h b/Code/CryEngine/CryCommon/Serialization/CryExtension.h deleted file mode 100644 index ed4e99fba1..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/CryExtension.h +++ /dev/null @@ -1,44 +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_SERIALIZATION_CRYEXTENSION_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYEXTENSION_H -#pragma once - -#ifdef GetClassName -#undef GetClassName -#endif -#include - -namespace Serialization -{ - // Allows to have AZStd::shared_ptr but serialize it by - // interface-casting to TSerializable, i.e. implementing Serialization through - // separate interface. - template - struct CryExtensionPointer - { - AZStd::shared_ptr& ptr; - - CryExtensionPointer(AZStd::shared_ptr& _ptr) - : ptr(_ptr) {} - void Serialize(Serialization::IArchive& ar); - }; -} - -// This function treats T as a type derived from CryUnknown type. -template -bool Serialize(Serialization::IArchive& ar, AZStd::shared_ptr& ptr, const char* name, const char* label); - -#include "CryExtensionImpl.h" -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYEXTENSION_H diff --git a/Code/CryEngine/CryCommon/Serialization/CryExtensionImpl.h b/Code/CryEngine/CryCommon/Serialization/CryExtensionImpl.h deleted file mode 100644 index e976163d55..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/CryExtensionImpl.h +++ /dev/null @@ -1,281 +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_SERIALIZATION_CRYEXTENSIONIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYEXTENSIONIMPL_H -#pragma once - -#include -#include -#include -#include - -namespace Serialization { - // Generate user-friendly class name, e.g. convert - // "AnimationPoseModifier_FootStore" -> "Foot Store" - inline string MakePrettyClassName(const char* className) - { - const char* firstSep = strchr(className, '_'); - if (!firstSep) - { - // name doesn't follow expected convention, return as is - return className; - } - - const char* start = firstSep + 1; - string result; - result.reserve(strlen(start) + 4); - - const char* p = start; - while (*p != '\0') - { - if (*p >= 'A' && *p <= 'Z' && - *(p - 1) >= 'a' && *(p - 1) <= 'z') - { - result += ' '; - } - if (*p == '_') - { - result += ' '; - } - else - { - result += *p; - } - ++p; - } - - return result; - } - - // Provides Serialization::IClassFactory interface for classes - // registered with CryExtension to IArchive. - // - // TSerializable can be used to expose Serialize method through - // a separate interface, rathern than TBase. Safe to missing - // as QueryInterface is used to check its presence. - template - class CryExtensionClassFactory - : public Serialization::IClassFactory - { - public: - size_t size() const override - { - return m_types.size(); - } - - static CryExtensionClassFactory& the() - { - static CryExtensionClassFactory instance; - return instance; - } - - CryExtensionClassFactory() - : IClassFactory(Serialization::TypeID::get()) - { - setNullLabel("[ None ]"); - ICryFactoryRegistry* factoryRegistry = gEnv->pSystem->GetCryFactoryRegistry(); - - size_t factoryCount = 0; - factoryRegistry->IterateFactories(cryiidof(), 0, factoryCount); - - if (factoryCount) - { - string sharedPrefix; - bool hasSharedPrefix = true; - AZStd::unique_ptr factories(new ICryFactory*[factoryCount]); - factoryRegistry->IterateFactories(cryiidof(), factories.get(), factoryCount); - - for (size_t i = 0; i < factoryCount; ++i) - { - ICryFactory* factory = factories[i]; - if (factory->ClassSupports(cryiidof())) - { - m_factories.push_back(factory); - if (hasSharedPrefix) - { - // make sure that shared prefix is the same for all the names - const char* name = factory->GetName(); - const char* lastPrefixCharacter = strchr(name, '_'); - if (lastPrefixCharacter == 0) - { - hasSharedPrefix = false; - } - else - { - if (!sharedPrefix.empty()) - { - if (strncmp(name, sharedPrefix.c_str(), sharedPrefix.size()) != 0) - { - hasSharedPrefix = false; - } - } - else - { - sharedPrefix.assign(name, lastPrefixCharacter + 1); - } - } - } - } - } - - size_t usableFactoriesCount = m_factories.size(); - m_types.reserve(usableFactoriesCount); - m_labels.reserve(usableFactoriesCount); - - for (size_t i = 0; i < usableFactoriesCount; ++i) - { - ICryFactory* factory = m_factories[i]; - m_classIds.push_back(factory->GetClassID()); - const char* name = factory->GetName(); - m_labels.push_back(MakePrettyClassName(name)); - if (hasSharedPrefix) - { - name += sharedPrefix.size(); - } - m_types.push_back(Serialization::TypeDescription(name, m_labels.back().c_str())); - } - } - } - - const Serialization::TypeDescription* descriptionByIndex(int index) const override - { - if (size_t(index) >= m_types.size()) - { - return 0; - } - return &m_types[index]; - } - - const Serialization::TypeDescription* descriptionByRegisteredName(const char* registeredName) const override - { - size_t count = m_types.size(); - for (size_t i = 0; i < m_types.size(); ++i) - { - if (strcmp(m_types[i].name(), registeredName) == 0) - { - return &m_types[i]; - } - } - return 0; - } - - const char* findAnnotation(const char* typeName, const char* name) const override { return ""; } - - void serializeNewByIndex(IArchive& ar, int index, const char* name, const char* label) override - { - if (size_t(index) >= m_types.size()) - { - return; - } - AZStd::shared_ptr ptr(create(m_types[index].name())); - if (TSerializable* ser = cryinterface_cast(ptr.get())) - { - ar(*ser, name, label); - } - } - - AZStd::shared_ptr create(const char* registeredName) - { - size_t count = m_types.size(); - for (size_t i = 0; i < count; ++i) - { - if (strcmp(m_types[i].name(), registeredName) == 0) - { - return AZStd::static_pointer_cast(m_factories[i]->CreateClassInstance()); - } - } - return AZStd::shared_ptr(); - } - - const char* getRegisteredTypeName(const AZStd::shared_ptr& ptr) const - { - if (!ptr.get()) - { - return ""; - } - CryInterfaceID id = AZStd::static_pointer_cast(ptr)->GetFactory()->GetClassID(); - size_t count = m_classIds.size(); - for (size_t i = 0; i < count; ++i) - { - if (m_classIds[i] == id) - { - return m_types[i].name(); - } - } - return ""; - } - - private: - std::vector m_types; - std::vector m_labels; - std::vector m_factories; - std::vector m_classIds; - }; - - // Exposes CryExtension shared_ptr<> as serializeable type for Serialization::IArchive - template - class CryExtensionSharedPtr - : public Serialization::IPointer - { - public: - CryExtensionSharedPtr(AZStd::shared_ptr& ptr) - : m_ptr(ptr) - {} - - const char* registeredTypeName() const override - { - if (m_ptr) - { - return factory()->getRegisteredTypeName(m_ptr); - } - else - { - return ""; - } - } - - void create(const char* registeredTypeName) const override - { - if (registeredTypeName[0] != '\0') - { - m_ptr = factory()->create(registeredTypeName); - } - else - { - m_ptr.reset((T*)0); - } - } - - Serialization::TypeID baseType() const{ return Serialization::TypeID::get(); } - virtual Serialization::SStruct serializer() const override - { - if (TSerializable* ser = cryinterface_cast(m_ptr.get())) - { - return Serialization::SStruct(*ser); - } - else - { - return Serialization::SStruct(); - } - } - void* get() const override { return reinterpret_cast(m_ptr.get()); } - const void* handle() const override { return &m_ptr; } - Serialization::TypeID pointerType() const override { return Serialization::TypeID::get >(); } - CryExtensionClassFactory* factory() const override { return &CryExtensionClassFactory::the(); } - protected: - AZStd::shared_ptr& m_ptr; - }; -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYEXTENSIONIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/CryName.h b/Code/CryEngine/CryCommon/Serialization/CryName.h deleted file mode 100644 index 978af33379..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/CryName.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYNAME_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYNAME_H -#pragma once - -namespace Serialization { - class IArchive; -} - -inline bool Serialize(Serialization::IArchive & ar, class CCryName & cryName, const char* name, const char* label); - -#include "CryNameImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYNAME_H diff --git a/Code/CryEngine/CryCommon/Serialization/CryNameImpl.h b/Code/CryEngine/CryCommon/Serialization/CryNameImpl.h deleted file mode 100644 index e307892fd3..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/CryNameImpl.h +++ /dev/null @@ -1,61 +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_SERIALIZATION_CRYNAMEIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYNAMEIMPL_H -#pragma once - -#include "CryName.h" -#include "IArchive.h" - -class CryNameSerializer - : public Serialization::IString -{ -public: - CryNameSerializer(CCryName& s) - : m_s(s) - { - } - - virtual void set(const char* value) - { - m_s = value; - } - - virtual const char* get() const - { - return m_s.c_str(); - } - - virtual const void* handle() const - { - return &m_s; - } - - virtual Serialization::TypeID type() const - { - return Serialization::TypeID::get(); - } - - CCryName& m_s; -}; - - -inline bool Serialize(Serialization::IArchive& ar, CCryName& cryName, const char* name, const char* label) -{ - CryNameSerializer serializer(cryName); - return ar(static_cast(serializer), name, label); -} - - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYNAMEIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/CryStrings.h b/Code/CryEngine/CryCommon/Serialization/CryStrings.h deleted file mode 100644 index 560f64c045..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/CryStrings.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include "CryFixedString.h" - -#include "Serialization/Serializer.h" - -namespace Serialization -{ - class IArchive; -} - -// Note : if you are looking for the CryStringT serialization, it is handled in Serialization/STL.h - -template< size_t N > -bool Serialize(Serialization::IArchive& ar, CryFixedStringT< N >& value, const char* name, const char* label); - -template< size_t N > -bool Serialize(Serialization::IArchive& ar, CryStackStringT< char, N >& value, const char* name, const char* label); - -template< size_t N > -bool Serialize(Serialization::IArchive& ar, CryStackStringT< wchar_t, N >& value, const char* name, const char* label); - -#include "Serialization/CryStringsImpl.h" diff --git a/Code/CryEngine/CryCommon/Serialization/CryStringsImpl.h b/Code/CryEngine/CryCommon/Serialization/CryStringsImpl.h deleted file mode 100644 index 41de581b36..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/CryStringsImpl.h +++ /dev/null @@ -1,74 +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 - -#include "Serialization/IArchive.h" -#include "Serialization/CryStrings.h" - -namespace Serialization -{ - template< class TFixedStringClass > - class CFixedStringSerializer - : public IString - { - public: - CFixedStringSerializer(TFixedStringClass& str) - : str_(str) { } - - void set(const char* value) { str_ = value; } - const char* get() const { return str_.c_str(); } - const void* handle() const { return &str_; } - TypeID type() const { return TypeID::get(); } - private: - TFixedStringClass& str_; - }; - - template< class TFixedStringClass > - class CFixedWStringSerializer - : public IWString - { - public: - CFixedWStringSerializer(TFixedStringClass& str) - : str_(str) { } - - void set(const wchar_t* value) { str_ = value; } - const wchar_t* get() const { return str_.c_str(); } - const void* handle() const { return &str_; } - TypeID type() const { return TypeID::get(); } - private: - TFixedStringClass& str_; - }; -} - -template< size_t N > -inline bool Serialize(Serialization::IArchive& ar, CryFixedStringT< N >& value, const char* name, const char* label) -{ - Serialization::CFixedStringSerializer< CryFixedStringT< N > > str(value); - return ar(static_cast(str), name, label); -} - -template< size_t N > -inline bool Serialize(Serialization::IArchive& ar, CryStackStringT< char, N >& value, const char* name, const char* label) -{ - Serialization::CFixedStringSerializer< CryStackStringT< char, N > > str(value); - return ar(static_cast(str), name, label); -} - -template< size_t N > -inline bool Serialize(Serialization::IArchive& ar, CryStackStringT< wchar_t, N >& value, const char* name, const char* label) -{ - Serialization::CFixedWStringSerializer< CryStackStringT< wchar_t, N > > str(value); - return ar(static_cast(str), name, label); -} - diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ActionButton.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ActionButton.h deleted file mode 100644 index 2e8e07f597..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ActionButton.h +++ /dev/null @@ -1,89 +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 - -#include -#include -#include - -namespace Serialization -{ - struct IActionButton; - - DECLARE_SMART_POINTERS(IActionButton) - - struct IActionButton - { - virtual ~IActionButton() {} - - virtual void Callback() const = 0; - virtual const char* Icon() const = 0; - virtual IActionButtonPtr Clone() const = 0; - }; - - typedef AZStd::function FunctorActionButtonCallback; - - struct FunctorActionButton - : public IActionButton - { - FunctorActionButtonCallback callback; - string icon; - - explicit FunctorActionButton(const FunctorActionButtonCallback& callback, const char* icon = "") - : callback(callback) - , icon(icon) - { - } - - // IActionButton - - virtual void Callback() const override - { - if (callback) - { - callback(); - } - } - - virtual const char* Icon() const override - { - return icon.c_str(); - } - - virtual IActionButtonPtr Clone() const override - { - return IActionButtonPtr(new FunctorActionButton(callback, icon.c_str())); - } - - // ~IActionButton - }; - - inline bool Serialize(Serialization::IArchive& ar, FunctorActionButton& button, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(static_cast(button)), name, label); - } - else - { - return false; - } - } - - inline FunctorActionButton ActionButton(const FunctorActionButtonCallback& callback, const char* icon = "") - { - return FunctorActionButton(callback, icon); - } -} - diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/BitFlags.h b/Code/CryEngine/CryCommon/Serialization/Decorators/BitFlags.h deleted file mode 100644 index 1e23ecee27..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/BitFlags.h +++ /dev/null @@ -1,64 +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_SERIALIZATION_DECORATORS_BITFLAGS_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_BITFLAGS_H -#pragma once - -#include - -namespace Serialization { - class IArchive; - - struct BitFlagsWrapper - { - int* variable; - unsigned int visibleMask; - const CEnumDescription* description; - - void Serialize(IArchive& ar); - }; - - template - BitFlagsWrapper BitFlags(Enum& value) - { - BitFlagsWrapper wrapper; - wrapper.variable = (int*)&value; - wrapper.visibleMask = ~0U; - wrapper.description = &getEnumDescription(); - return wrapper; - } - - template - BitFlagsWrapper BitFlags(int& value, int visibleMask = ~0) - { - BitFlagsWrapper wrapper; - wrapper.variable = &value; - wrapper.visibleMask = visibleMask; - wrapper.description = &getEnumDescription(); - return wrapper; - } - - template - BitFlagsWrapper BitFlags(unsigned int& value, unsigned int visibleMask = ~0) - { - BitFlagsWrapper wrapper; - wrapper.variable = (int*)&value; - wrapper.visibleMask = visibleMask; - wrapper.description = &getEnumDescription(); - return wrapper; - } -} - -#include "BitFlagsImpl.h" -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_BITFLAGS_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/BitFlagsImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/BitFlagsImpl.h deleted file mode 100644 index 77b48fd1f0..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/BitFlagsImpl.h +++ /dev/null @@ -1,67 +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_SERIALIZATION_DECORATORS_BITFLAGSIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_BITFLAGSIMPL_H -#pragma once - -#include "Serialization/IArchive.h" - -namespace Serialization { - inline void BitFlagsWrapper::Serialize(IArchive& ar) - { - const Serialization::CEnumDescription& desc = *description; - int count = desc.count(); - if (ar.IsInput()) - { - int previousValue = *variable; - for (int i = 0; i < count; ++i) - { - int flagValue = desc.valueByIndex(i); - if (!(flagValue & visibleMask)) - { - continue; - } - bool flag = (previousValue & flagValue) == flagValue; - bool previousFlag = flag; - ar(flag, desc.nameByIndex(i), desc.labelByIndex(i)); - if (flag != previousFlag) - { - if (flag) - { - *variable |= flagValue; - } - else - { - *variable &= ~flagValue; - } - } - } - } - else - { - for (int i = 0; i < count; ++i) - { - int flagValue = desc.valueByIndex(i); - if (!(flagValue & visibleMask)) - { - continue; - } - bool flag = (*variable & flagValue) == flagValue; - ar(flag, desc.nameByIndex(i), desc.labelByIndex(i)); - } - } - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_BITFLAGSIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ColorPicker.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ColorPicker.h deleted file mode 100644 index 146e7bf42f..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ColorPicker.h +++ /dev/null @@ -1,43 +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_CRYCOMMON_SERIALIZATION_DECORATORS_COLORPICKER_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_COLORPICKER_H -#pragma once - -#include -#include - -#include - -namespace Serialization -{ - class IArchive; - - struct ColorPicker - { - ColorF* color; - - explicit ColorPicker(ColorF& color_) - : color(&color_) - { - } - - // the function should stay virtual to ensure cross-dll calls are using right heap - virtual void SetColor(const ColorF* color_){* color = *color_; } - }; - - bool Serialize(Serialization::IArchive& ar, Serialization::ColorPicker& value, const char* name, const char* label); -} // namespace Serialization - -#include "ColorPickerImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_COLORPICKER_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ColorPickerImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ColorPickerImpl.h deleted file mode 100644 index 6585f40a91..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ColorPickerImpl.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. -* -*/ -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_COLORPICKERIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_COLORPICKERIMPL_H -#pragma once - -#include "../Color.h" - -namespace Serialization -{ - inline bool Serialize(Serialization::IArchive& ar, Serialization::ColorPicker& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(value), name, label); - } - else - { - return ar(*value.color, name, label); - } - } -} // namespace Serialization - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_COLORPICKERIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/JointName.h b/Code/CryEngine/CryCommon/Serialization/Decorators/JointName.h deleted file mode 100644 index 69195c20bf..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/JointName.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_JOINTNAME_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_JOINTNAME_H -#pragma once - -#include -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_JOINTNAME_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/JointNameImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/JointNameImpl.h deleted file mode 100644 index ad168a92a3..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/JointNameImpl.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_JOINTNAMEIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_JOINTNAMEIMPL_H -#pragma once - - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_JOINTNAMEIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/LocalFrame.h b/Code/CryEngine/CryCommon/Serialization/Decorators/LocalFrame.h deleted file mode 100644 index 39841623f9..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/LocalFrame.h +++ /dev/null @@ -1,117 +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_SERIALIZATION_DECORATORS_LOCALFRAME_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_LOCALFRAME_H -#pragma once - -#include -#include "Serialization/Math.h" - -namespace Serialization -{ - class IArchive; - - struct LocalPosition - { - Vec3* value; - int space; - const char* parentName; - const void* handle; - - LocalPosition(Vec3& _vec, int _space, const char* _parentName, const void* _handle) - : value(&_vec) - , space(_space) - , parentName(_parentName) - , handle(_handle) - { - } - - void Serialize(IArchive& ar); - }; - - struct LocalOrientation - { - Quat* value; - int space; - const char* parentName; - const void* handle; - - LocalOrientation(Quat& _vec, int _space, const char* _parentName, const void* _handle) - : value(&_vec) - , space(_space) - , parentName(_parentName) - , handle(_handle) - { - } - - void Serialize(IArchive& ar); - }; - - struct LocalFrame - { - Quat* rotation; - Vec3* position; - const char* parentName; - int rotationSpace; - int positionSpace; - const void* handle; - - LocalFrame(Quat* _rotation, int _rotationSpace, Vec3* _position, int _positionSpace, const char* _parentName, const void* _handle) - : rotation(_rotation) - , position(_position) - , parentName(_parentName) - , rotationSpace(_rotationSpace) - , positionSpace(_positionSpace) - , handle(_handle) - { - } - - void Serialize(IArchive& ar); - }; - - enum - { - SPACE_JOINT, - SPACE_ENTITY, - SPACE_JOINT_WITH_PARENT_ROTATION, - SPACE_JOINT_WITH_CHARACTER_ROTATION, - SPACE_SOCKET_RELATIVE_TO_JOINT, - SPACE_SOCKET_RELATIVE_TO_BINDPOSE - }; - - - - //position - inline LocalPosition LocalToEntity(Vec3& position, const void* handle = 0) - { - return LocalPosition(position, SPACE_ENTITY, "", handle ? handle : &position); - } - inline LocalPosition LocalToJoint(Vec3& position, const string& jointName, const void* handle = 0) - { - return LocalPosition(position, SPACE_JOINT, jointName.c_str(), handle ? handle : &position); - } - - inline LocalPosition LocalToJointCharacterRotation(Vec3& position, const string& jointName, const void* handle = 0) - { - return LocalPosition(position, SPACE_JOINT_WITH_CHARACTER_ROTATION, jointName.c_str(), handle ? handle : &position); - } - - bool Serialize(Serialization::IArchive& ar, Serialization::LocalPosition& value, const char* name, const char* label); - bool Serialize(Serialization::IArchive& ar, Serialization::LocalOrientation& value, const char* name, const char* label); - bool Serialize(Serialization::IArchive& ar, Serialization::LocalFrame& value, const char* name, const char* label); -} - -#include "LocalFrameImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_LOCALFRAME_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/LocalFrameImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/LocalFrameImpl.h deleted file mode 100644 index 774cc06852..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/LocalFrameImpl.h +++ /dev/null @@ -1,89 +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_SERIALIZATION_DECORATORS_LOCALFRAMEIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_LOCALFRAMEIMPL_H -#pragma once - -#include "LocalFrame.h" -#include "Serialization/IArchive.h" -#include "Serialization/MathImpl.h" - -namespace Serialization -{ - inline void LocalPosition::Serialize(Serialization::IArchive& ar) - { - ar(value->x, "x", "^"); - ar(value->y, "y", "^"); - ar(value->z, "z", "^"); - } - - inline void LocalOrientation::Serialize(Serialization::IArchive& ar) - { - ar(Serialization::AsAng3(*value), "q", "^"); - } - - inline void LocalFrame::Serialize(Serialization::IArchive& ar) - { - ar(*position, "t", "m_path = path; } - }; - - bool Serialize(Serialization::IArchive& ar, Serialization::OutputFilePath& value, const char* name, const char* label); -} - -#include "OutputFilePathImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_OUTPUTFILEPATH_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/OutputFilePathImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/OutputFilePathImpl.h deleted file mode 100644 index 29d64fcff7..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/OutputFilePathImpl.h +++ /dev/null @@ -1,32 +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_SERIALIZATION_DECORATORS_OUTPUTFILEPATHIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_OUTPUTFILEPATHIMPL_H -#pragma once - -namespace Serialization -{ - inline bool Serialize(Serialization::IArchive& ar, Serialization::OutputFilePath& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(value), name, label); - } - else - { - return ar(*value.m_path, name, label); - } - } -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_OUTPUTFILEPATHIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/Range.h b/Code/CryEngine/CryCommon/Serialization/Decorators/Range.h deleted file mode 100644 index 7966c579dd..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/Range.h +++ /dev/null @@ -1,63 +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_SERIALIZATION_DECORATORS_RANGE_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RANGE_H -#pragma once - -namespace Serialization -{ - template - struct RangeDecorator - { - T* value; - T softMin; - T softMax; - T hardMin; - T hardMax; - }; - - template - RangeDecorator Range(T& value, T hardMin, T hardMax) - { - RangeDecorator r; - r.value = &value; - r.softMin = hardMin; - r.softMax = hardMax; - r.hardMin = hardMin; - r.hardMax = hardMax; - return r; - } - - template - RangeDecorator Range(T& value, T softMin, T softMax, T hardMin, T hardMax) - { - RangeDecorator r; - r.value = &value; - r.softMin = softMin; - r.softMax = softMax; - r.hardMin = hardMin; - r.hardMax = hardMax; - return r; - } - - namespace Decorators - { - // Obsolete name, will be removed. Please use Serialization::Range instead. - using Serialization::Range; - } -} - -#include "RangeImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RANGE_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/RangeImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/RangeImpl.h deleted file mode 100644 index bc0508f3cb..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/RangeImpl.h +++ /dev/null @@ -1,50 +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_SERIALIZATION_DECORATORS_RANGEIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RANGEIMPL_H -#pragma once - -namespace Serialization -{ - template - bool Serialize(IArchive& ar, RangeDecorator& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - if (!ar(SStruct::ForEdit(value), name, label)) - { - return false; - } - } - else if (!ar(*value.value, name, label)) - { - return false; - } - - if (ar.IsInput()) - { - if (*value.value < value.hardMin) - { - *value.value = value.hardMin; - } - if (*value.value > value.hardMax) - { - *value.value = value.hardMax; - } - } - return true; - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RANGEIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFilePath.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFilePath.h deleted file mode 100644 index 0f0c6dc34e..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFilePath.h +++ /dev/null @@ -1,59 +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_SERIALIZATION_DECORATORS_RESOURCEFILEPATH_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFILEPATH_H -#pragma once - -#include "Serialization/Strings.h" - -namespace Serialization -{ - class IArchive; - - struct ResourceFilePath - { - enum - { - STRIP_EXTENSION = 1 << 0 - }; - - string* m_path; - string filter; - bool group; - int flags; - - // filters are defined in the following format: - // "All Images (bmp, jpg, tga)|*.bmp;*.jpg;*.tga|Targa (tga)|*.tga" - explicit ResourceFilePath(string& path, const char* filter = "", bool group = false, int flags = 0) - : m_path(&path) - , filter(filter) - , group(group) - , flags(flags) - { - } - - // the function should stay virtual to ensure cross-dll calls are using right heap - virtual void SetPath(const char* path) { *this->m_path = path; } - }; - - inline ResourceFilePath MaterialPath(string& path) - { - return ResourceFilePath(path, "Material", false, ResourceFilePath::STRIP_EXTENSION); - } - - bool Serialize(Serialization::IArchive& ar, Serialization::ResourceFilePath& value, const char* name, const char* label); -} - -#include "ResourceFilePathImpl.h" -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFILEPATH_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFilePathImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFilePathImpl.h deleted file mode 100644 index 66c9140236..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFilePathImpl.h +++ /dev/null @@ -1,32 +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_SERIALIZATION_DECORATORS_RESOURCEFILEPATHIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFILEPATHIMPL_H -#pragma once - -namespace Serialization -{ - inline bool Serialize(Serialization::IArchive& ar, Serialization::ResourceFilePath& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(value), name, label); - } - else - { - return ar(*value.m_path, name, label); - } - } -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFILEPATHIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFolderPath.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFolderPath.h deleted file mode 100644 index 327f668e43..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFolderPath.h +++ /dev/null @@ -1,43 +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_SERIALIZATION_DECORATORS_RESOURCEFOLDERPATH_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFOLDERPATH_H -#pragma once - -#include "Serialization/Strings.h" - -namespace Serialization -{ - class IArchive; - - struct ResourceFolderPath - { - string* m_path; - string startFolder; - - explicit ResourceFolderPath(string& path, const char* startFolder = "") - : m_path(&path) - , startFolder(startFolder) - { - } - - // the function should stay virtual to ensure cross-dll calls are using right heap - virtual void SetPath(const char* path) { *this->m_path = path; } - }; - - bool Serialize(Serialization::IArchive& ar, Serialization::ResourceFolderPath& value, const char* name, const char* label); -} - -#include "ResourceFolderPathImpl.h" -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFOLDERPATH_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFolderPathImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFolderPathImpl.h deleted file mode 100644 index 33ceacbe10..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFolderPathImpl.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_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFOLDERPATHIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFOLDERPATHIMPL_H -#pragma once - -#include "Serialization/IArchive.h" - -namespace Serialization -{ - inline bool Serialize(Serialization::IArchive& ar, Serialization::ResourceFolderPath& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(value), name, label); - } - else - { - return ar(*value.m_path, name, label); - } - } -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFOLDERPATHIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceSelector.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceSelector.h deleted file mode 100644 index 3b9920be6c..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceSelector.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -namespace Serialization -{ - struct IResourceSelector - { - const char* resourceType; - - virtual ~IResourceSelector() {} - virtual const char* GetValue() const = 0; - virtual void SetValue(const char* s) = 0; - virtual int GetId() const{ return -1; } - virtual const void* GetHandle() const = 0; - virtual Serialization::TypeID GetType() const = 0; - }; - - // Provides a way to annotate resource reference so different UI can be used - // for them. See IResourceSelector.h to see how selectors for specific types - // are registered. - // - // TString could be SCRCRef or CCryName as well. - // - // Do not use this class directly, instead use function that wraps it for - // specific type, see Resources.h for example. - template - struct ResourceSelector - : IResourceSelector - { - TString& value; - - const char* GetValue() const { return value.c_str(); } - void SetValue(const char* s) { value = s; } - const void* GetHandle() const { return &value; } - Serialization::TypeID GetType() const { return Serialization::TypeID::get(); } - - ResourceSelector(TString& _value, const char* _resourceType) - : value(_value) - { - this->resourceType = _resourceType; - } - }; - - struct ResourceSelectorWithId - : IResourceSelector - { - string& value; - int id; - - const char* GetValue() const { return value.c_str(); } - void SetValue(const char* s) { value = s; } - int GetId() const { return id; } - const void* GetHandle() const { return &value; } - Serialization::TypeID GetType() const { return Serialization::TypeID::get(); } - - ResourceSelectorWithId(string& _value, const char* _resourceType, int _id) - : value(_value) - , id(_id) - { - this->resourceType = _resourceType; - } - }; - - template - bool Serialize(IArchive& ar, ResourceSelector& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(static_cast(value)), name, label); - } - else - { - return ar(value.value, name, label); - } - } - - inline bool Serialize(IArchive& ar, ResourceSelectorWithId& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(static_cast(value)), name, label); - } - else - { - return ar(value.value, name, label); - } - } -} diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/Resources.h b/Code/CryEngine/CryCommon/Serialization/Decorators/Resources.h deleted file mode 100644 index 637fc937ed..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/Resources.h +++ /dev/null @@ -1,67 +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_SERIALIZATION_DECORATORS_RESOURCES_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCES_H -#pragma once -#include "ResourceSelector.h" - -namespace Serialization -{ - // animation resources - template - ResourceSelector AnimationAlias(T& s) { return ResourceSelector(s, "AnimationAlias"); } // "name" from animation set - template - ResourceSelector AnimationPath(T& s) { return ResourceSelector(s, "Animation"); } - inline ResourceSelectorWithId AnimationPathWithId(string& s, int id) { return ResourceSelectorWithId(s, "Animation", id); } - template - ResourceSelector CharacterPath(T& s) { return ResourceSelector(s, "Character"); } - template - ResourceSelector CharacterPhysicsPath(T& s) { return ResourceSelector(s, "CharacterPhysics"); } - template - ResourceSelector CharacterRigPath(T& s) { return ResourceSelector(s, "CharacterRig"); } - template - ResourceSelector SkeletonPath(T& s) { return ResourceSelector(s, "Skeleton"); } - template - ResourceSelector SkeletonParamsPath(T& s) { return ResourceSelector(s, "SkeletonParams"); } // CHRParams - template - ResourceSelector JointName(T& s) { return ResourceSelector(s, "Joint"); } - template - ResourceSelector AttachmentName(T& s) { return ResourceSelector(s, "Attachment"); } - - // miscelaneous resources - template - ResourceSelector SoundName(T& s) { return ResourceSelector(s, "Sound"); } - template - ResourceSelector DialogName(T& s) { return ResourceSelector(s, "Dialog"); } - template - ResourceSelector ForceFeedbackIdName(T& s) { return ResourceSelector(s, "ForceFeedbackId"); } - template - ResourceSelector ModelFilename(T& s) { return ResourceSelector(s, "Model"); } - template - ResourceSelector ParticleName(T& s) { return ResourceSelector(s, "Particle"); } - - namespace Decorators - { - // Decorators namespace is obsolete now, SHOULD NOT BE USED. - template - ResourceSelector AnimationName(T& s) { return ResourceSelector(s, "Animation"); } - using Serialization::SoundName; - using Serialization::AttachmentName; - template - ResourceSelector ObjectFilename(T& s) { return ResourceSelector(s, "Model"); } - using Serialization::JointName; - using Serialization::ForceFeedbackIdName; - } -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCES_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourcesAudio.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ResourcesAudio.h deleted file mode 100644 index 9e10be6c3b..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourcesAudio.h +++ /dev/null @@ -1,31 +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 -#include "ResourceSelector.h" - -namespace Serialization -{ - template - ResourceSelector AudioTrigger(T& s) { return ResourceSelector(s, "AudioTrigger"); } - template - ResourceSelector AudioSwitch(T& s) { return ResourceSelector(s, "AudioSwitch"); } - template - ResourceSelector AudioSwitchState(T& s) { return ResourceSelector(s, "AudioSwitchState"); } - template - ResourceSelector AudioRTPC(T& s) { return ResourceSelector(s, "AudioRTPC"); } - template - ResourceSelector AudioEnvironment(T& s) { return ResourceSelector(s, "AudioEnvironment"); } - template - ResourceSelector AudioPreloadRequest(T& s) { return ResourceSelector(s, "AudioPreloadRequest"); } -}; diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourcesImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ResourcesImpl.h deleted file mode 100644 index dde4e1ae0c..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourcesImpl.h +++ /dev/null @@ -1,44 +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_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCESIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCESIMPL_H -#pragma once - -namespace Serialization -{ - template - bool Serialize(IArchive& ar, ResourceSelector& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(static_cast(value)), name, label); - } - else - { - return ar(value.value, name, label); - } - } - - inline bool Serialize(IArchive& ar, ResourceSelectorWithId& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(static_cast(value)), name, label); - } - else - { - return ar(value.value, name, label); - } - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCESIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/Slider.h b/Code/CryEngine/CryCommon/Serialization/Decorators/Slider.h deleted file mode 100644 index 8be5086660..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/Slider.h +++ /dev/null @@ -1,88 +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_SERIALIZATION_DECORATORS_SLIDER_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SLIDER_H -#pragma once - -namespace Serialization -{ - class IArchive; - - struct SSliderF - { - SSliderF(float* value, float _minLimit, float _maxLimit) - : valuePointer(value) - , minLimit(_minLimit) - , maxLimit(_maxLimit) - { - } - - SSliderF() - : valuePointer(0) - , minLimit(0.0f) - , maxLimit(1.0f) - { - } - - - float* valuePointer; - float minLimit; - float maxLimit; - }; - - struct SSliderI - { - SSliderI(int* value, int minLimit, int maxLimit) - : valuePointer(value) - , minLimit(minLimit) - , maxLimit(maxLimit) - { - } - - SSliderI() - : valuePointer(0) - , minLimit(0) - , maxLimit(1) - { - } - - int* valuePointer; - int minLimit; - int maxLimit; - }; - - - inline SSliderF Slider(float& value, float minLimit, float maxLimit) - { - return SSliderF(&value, minLimit, maxLimit); - } - - inline SSliderI Slider(int& value, int minLimit, int maxLimit) - { - return SSliderI(&value, minLimit, maxLimit); - } - - bool Serialize(IArchive& ar, SSliderF& slider, const char* name, const char* label); - bool Serialize(IArchive& ar, SSliderI& slider, const char* name, const char* label); - - namespace Decorators - { - // OBSOLETE NAME, please use Serialization::Slider instead (without Decorators namespace) - using Serialization::Slider; - } -} - -#include "SliderImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SLIDER_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/SliderImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/SliderImpl.h deleted file mode 100644 index c9e0dfc891..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/SliderImpl.h +++ /dev/null @@ -1,47 +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_SERIALIZATION_DECORATORS_SLIDERIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SLIDERIMPL_H -#pragma once - -#include "Slider.h" -#include "Serialization/IArchive.h" - -namespace Serialization -{ - inline bool Serialize(IArchive& ar, SSliderF& slider, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(SStruct::ForEdit(slider), name, label); - } - else - { - return ar(*slider.valuePointer, name, label); - } - } - - inline bool Serialize(IArchive& ar, SSliderI& slider, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(SStruct::ForEdit(slider), name, label); - } - else - { - return ar(*slider.valuePointer, name, label); - } - } -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SLIDERIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/Sprite.h b/Code/CryEngine/CryCommon/Serialization/Decorators/Sprite.h deleted file mode 100644 index 0eeefd7536..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/Sprite.h +++ /dev/null @@ -1,44 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SPRITE_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SPRITE_H -#pragma once - -namespace Serialization -{ -class IArchive; - -struct Sprite -{ - string* m_path; - string m_filter; - string m_startFolder; - - // filters are defined in the following format: - // "All Images (bmp, jpg, tga)|*.bmp;*.jpg;*.tga|Targa (tga)|*.tga" - explicit Sprite(string& path, const char* filter = "All files|*.*", const char* startFolder = "") - : m_path(&path) - , m_filter(filter) - , m_startFolder(startFolder) - { - } -}; - -bool Serialize(IArchive& ar, Sprite& value, const char* name, const char* label); - -} // namespace Serialization - -#include "SpriteImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SPRITE_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/SpriteImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/SpriteImpl.h deleted file mode 100644 index 6d0075fafc..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/SpriteImpl.h +++ /dev/null @@ -1,35 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SPRITEIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SPRITEIMPL_H -#pragma once - -namespace Serialization -{ - -inline bool Serialize(IArchive& ar, Sprite& value, const char* name, const char* label) -{ - if (ar.IsEdit()) - { - return ar(SStruct::ForEdit(value), name, label); - } - else - { - return ar(*value.m_path, name, label); - } -} - -} // namespace Serialization - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SPRITEIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/TagList.h b/Code/CryEngine/CryCommon/Serialization/Decorators/TagList.h deleted file mode 100644 index 4c4ad81ebf..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/TagList.h +++ /dev/null @@ -1,49 +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_SERIALIZATION_DECORATORS_TAGLIST_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_TAGLIST_H -#pragma once - -#include -#include "Serialization/Strings.h" - -namespace Serialization { - class IArchive; -} - -struct ITagSource -{ - virtual void AddRef() = 0; - virtual void Release() = 0; - virtual unsigned int TagCount(unsigned int group) const = 0; - virtual const char* TagValue(unsigned int group, unsigned int index) const = 0; - virtual const char* TagDescription(unsigned int group, unsigned int index) const = 0; - virtual const char* GroupName(unsigned int group) const = 0; - virtual unsigned int GroupCount() const = 0; -}; - -struct TagList -{ - std::vector* tags; - - TagList(std::vector& tags) - : tags(&tags) - { - } -}; - -bool Serialize(Serialization::IArchive& ar, TagList& tagList, const char* name, const char* label); - -#include "TagListImpl.h" -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_TAGLIST_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/TagListImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/TagListImpl.h deleted file mode 100644 index 2ee6e1769b..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/TagListImpl.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_CRYCOMMON_SERIALIZATION_DECORATORS_TAGLISTIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_TAGLISTIMPL_H -#pragma once - -#include -#include "Serialization/IArchive.h" -#include "Serialization/Strings.h" -#include "Serialization/STL.h" - -struct TagListContainer - : Serialization::ContainerSTL, Serialization::string> -{ - TagListContainer(TagList& tagList) - : ContainerSTL(tagList.tags) - { - } - - Serialization::TypeID containerType() const override { return Serialization::TypeID::get(); }; -}; - -inline bool Serialize(Serialization::IArchive& ar, TagList& tagList, const char* name, const char* label) -{ - TagListContainer container(tagList); - return ar(static_cast(container), name, label); -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_TAGLISTIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/DynArray.h b/Code/CryEngine/CryCommon/Serialization/DynArray.h deleted file mode 100644 index 1904cf4ac3..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/DynArray.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DYNARRAY_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DYNARRAY_H -#pragma once - -namespace Serialization { - class IArchive; -} - -template -bool Serialize(Serialization::IArchive& ar, DynArray& container, const char* name, const char* label); - -#include "DynArrayImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DYNARRAY_H diff --git a/Code/CryEngine/CryCommon/Serialization/DynArrayImpl.h b/Code/CryEngine/CryCommon/Serialization/DynArrayImpl.h deleted file mode 100644 index c437604f67..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/DynArrayImpl.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DYNARRAYIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DYNARRAYIMPL_H -#pragma once - -#include "IArchive.h" -#include "STLImpl.h" - -template -bool Serialize(Serialization::IArchive& ar, DynArray& container, const char* name, const char* label) -{ - Serialization::ContainerSTL, T> ser(&container); - return ar(static_cast(ser), name, label); -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DYNARRAYIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Enum.h b/Code/CryEngine/CryCommon/Serialization/Enum.h deleted file mode 100644 index e377269013..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Enum.h +++ /dev/null @@ -1,170 +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_SERIALIZATION_ENUM_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_ENUM_H -#pragma once - - -#include -#include - -#include "StringList.h" -#include "Serialization/TypeID.h" - -namespace Serialization { - class IArchive; - - struct LessStrCmp - { - bool operator()(const char* l, const char* r) const - { - return strcmp(l, r) < 0; - } - }; - - class CEnumDescription - { - public: - struct NameValue - { - NameValue* m_next; - const char* m_name; - const int m_value; - const char* m_label; - - NameValue(CEnumDescription& desc, const char* name, int value, const char* label="") - : m_next(desc.m_regListHead) - , m_name(name) - , m_value(value) - , m_label(label) - { - desc.m_regListHead = this; - } - }; - - NameValue* m_regListHead = nullptr; - - CEnumDescription(const Serialization::TypeID& type) - : type_(type) {} - inline int value(const char* name) const; - inline int valueByIndex(int index) const; - inline int valueByLabel(const char* label) const; - inline const char* name(int value) const; - inline const char* nameByIndex(int index) const; - inline const char* labelByIndex(int index) const; - inline const char* label(int value) const; - inline const char* indexByName(const char* name) const; - inline int indexByValue(int value) const; - - inline bool Serialize(IArchive& ar, int& value, const char* name, const char* label) const; - inline bool serializeBitVector(IArchive& ar, int& value, const char* name, const char* label) const; - - void add(int value, const char* name, const char* label = ""); - int count() const{ return int(values_.size()); } - const StringListStatic& names() const{ return names_; } - const StringListStatic& labels() const{ return labels_; } - inline StringListStatic nameCombination(int bitVector) const; - inline StringListStatic labelCombination(int bitVector) const; - bool registered() const { return !names_.empty(); } - TypeID type() const{ return type_; } - private: - void lazyRegister() const; - - StringListStatic names_; - StringListStatic labels_; - - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> NameToValue; - NameToValue nameToValue_; - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> LabelToValue; - LabelToValue labelToValue_; - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> ValueToIndex; - ValueToIndex valueToIndex_; - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> ValueToName; - ValueToName valueToName_; - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> ValueToLabel; - ValueToName valueToLabel_; - AZStd::vector values_; - TypeID type_; - }; - - template - class EnumDescriptionImpl - : public CEnumDescription - { - EnumDescriptionImpl() - : CEnumDescription(Serialization::TypeID::get()) {} - public: - static CEnumDescription& the() - { - static EnumDescriptionImpl description; - return description; - } - }; - - template - CEnumDescription& getEnumDescription() - { - return EnumDescriptionImpl::the(); - } - - inline bool serializeEnum(const CEnumDescription& desc, IArchive& ar, int& value, const char* name, const char* label) - { - return desc.Serialize(ar, value, name, label); - } -} - -#define SERIALIZATION_ENUM_BEGIN(Type, label) \ - namespace { \ - bool registerEnum_##Type(); \ - bool Type##_enum_registered = registerEnum_##Type(); \ - bool registerEnum_##Type(){ \ - Serialization::CEnumDescription& description = Serialization::EnumDescriptionImpl::the(); - -#define SERIALIZATION_ENUM_BEGIN_NESTED(Class, Enum, label) \ - namespace { \ - bool registerEnum_##Class##_##Enum(); \ - bool Class##_##Enum##_enum_registered = registerEnum_##Class##_##Enum(); \ - bool registerEnum_##Class##_##Enum(){ \ - Serialization::CEnumDescription& description = Serialization::EnumDescriptionImpl::the(); - -#define SERIALIZATION_ENUM_BEGIN_NESTED2(Class, Class1, Enum, label) \ - namespace { \ - bool registerEnum_##Class##Class1##_##Enum(); \ - bool Class##Class1##_##Enum##_enum_registered = registerEnum_##Class##Class1##_##Enum(); \ - bool registerEnum_##Class##Class1##_##Enum(){ \ - Serialization::CEnumDescription& description = Serialization::EnumDescriptionImpl::the(); - - -#define SERIALIZATION_ENUM_VALUE(value, label) \ - static Serialization::CEnumDescription::NameValue AZ_JOIN(enumValue, __LINE__)(description, label, (int)value); - -#define SERIALIZATION_ENUM(value, name, label) \ - static Serialization::CEnumDescription::NameValue AZ_JOIN(enumValue, __LINE__)(description, name, (int)value, label); - -#define SERIALIZATION_ENUM_VALUE_NESTED(Class, value, label) \ - static Serialization::CEnumDescription::NameValue AZ_JOIN(enumValue, __LINE__)(description, #value, (int)Class::value, label); - -#define SERIALIZATION_ENUM_VALUE_NESTED2(Class, Class1, value, label) \ - static Serialization::CEnumDescription::NameValue AZ_JOIN(enumValue, __LINE__)(description, #value, (int)Class::Class1::value, label); - - -#define SERIALIZATION_ENUM_END() \ - return true; \ - }; \ - }; - -#include "EnumImpl.h" -// vim:ts=4 sw=4: - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_ENUM_H diff --git a/Code/CryEngine/CryCommon/Serialization/EnumImpl.h b/Code/CryEngine/CryCommon/Serialization/EnumImpl.h deleted file mode 100644 index e5af93e43c..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/EnumImpl.h +++ /dev/null @@ -1,248 +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_SERIALIZATION_ENUMIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_ENUMIMPL_H -#pragma once - -#pragma once -#include "IArchive.h" -#include "STL.h" -#include "Enum.h" -#include "StringList.h" -#ifndef SERIALIZATION_STANDALONE -#include -#endif - -namespace Serialization { - inline void CEnumDescription::add(int value, const char* name, const char* label) - { - YASLI_ESCAPE(name && label, return ); - // Filter for dupes in case enum description included in a shared header - NameToValue::iterator nameIt = nameToValue_.find(name); - if (nameIt != nameToValue_.end() && nameIt->second == value) - { LabelToValue::iterator labelIt = labelToValue_.find(label); - if (labelIt != labelToValue_.end() && labelIt->second == value) - { - return; - } - } - nameToValue_[name] = value; - labelToValue_[label] = value; - valueToName_[value] = name; - valueToLabel_[value] = label; - valueToIndex_[value] = int(names_.size()); - names_.push_back(name); - labels_.push_back(label); - values_.push_back(value); - } - - inline bool CEnumDescription::Serialize(IArchive& ar, int& value, const char* name, const char* label) const - { - lazyRegister(); - if (!ar.IsInPlace()) - { - if (count() == 0) - { -#ifdef SERIALIZATION_STANDALONE - assert(0 && "Attempt to serialize enum type that is not registered with SERIALIZATION_ENUM macro"); -#else - CryFatalError("Attempt to serialize enum type that is not registered with SERIALIZATION_ENUM macro: %s", type().name()); -#endif - return false; - } - - int index = StringListStatic::npos; - if (ar.IsOutput()) - { - index = indexByValue(value); - } - StringListStaticValue stringListValue(ar.IsEdit() ? labels() : names(), index, &value, type()); - ar(stringListValue, name, label); - if (ar.IsInput()) - { - if (stringListValue.index() == StringListStatic::npos) - { - return false; - } - value = ar.IsEdit() ? valueByLabel(stringListValue.c_str()) : this->value(stringListValue.c_str()); - } - else if (index == StringListStatic::npos) - { - ar.Error(&value, type(), "Unregistered or uninitialized enumeration value."); - } - } - else - { - return ar(value, name, label); - } - return true; - } - - inline bool CEnumDescription::serializeBitVector(IArchive& ar, int& value, const char* name, const char* label) const - { - lazyRegister(); - if (ar.IsOutput()) - { - StringListStatic names = nameCombination(value); - string str; - joinStringList(&str, names, '|'); - return ar(str, name, label); - } - else - { - string str; - if (!ar(str, name, label)) - { - return false; - } - StringList values; - splitStringList(&values, str.c_str(), '|'); - StringList::iterator it; - value = 0; - for (it = values.begin(); it != values.end(); ++it) - { - if (!it->empty()) - { - value |= this->value(it->c_str()); - } - } - return true; - } - } - - - inline const char* CEnumDescription::name(int value) const - { - lazyRegister(); - ValueToName::const_iterator it = valueToName_.find(value); - YASLI_ESCAPE(it != valueToName_.end(), return ""); - return it->second; - } - inline const char* CEnumDescription::label(int value) const - { - lazyRegister(); - ValueToLabel::const_iterator it = valueToLabel_.find(value); - YASLI_ESCAPE(it != valueToLabel_.end(), return ""); - return it->second; - } - - inline StringListStatic CEnumDescription::nameCombination(int bitVector) const - { - lazyRegister(); - StringListStatic strings; - for (ValueToName::const_iterator i = valueToName_.begin(); i != valueToName_.end(); ++i) - { - if ((bitVector & i->first) == i->first) - { - bitVector &= ~i->first; - strings.push_back(i->second); - } - } - YASLI_ASSERT(!bitVector && "Unregistered enum value"); - return strings; - } - - inline StringListStatic CEnumDescription::labelCombination(int bitVector) const - { - lazyRegister(); - StringListStatic strings; - for (ValueToLabel::const_iterator i = valueToLabel_.begin(); i != valueToLabel_.end(); ++i) - { - if (i->second && (bitVector & i->first) == i->first) - { - bitVector &= ~i->first; - strings.push_back(i->second); - } - } - YASLI_ASSERT(!bitVector && "Unregistered enum value"); - return strings; - } - - - inline int CEnumDescription::indexByValue(int value) const - { - lazyRegister(); - ValueToIndex::const_iterator it = valueToIndex_.find(value); - if (it == valueToIndex_.end()) - { - return -1; - } - else - { - return it->second; - } - } - - inline int CEnumDescription::valueByIndex(int index) const - { - lazyRegister(); - if (size_t(index) < values_.size()) - { - return values_[index]; - } - return 0; - } - - inline const char* CEnumDescription::nameByIndex(int index) const - { - lazyRegister(); - if (size_t(index) < size_t(names_.size())) - { - return names_[size_t(index)]; - } - return 0; - } - - inline const char* CEnumDescription::labelByIndex(int index) const - { - lazyRegister(); - if (size_t(index) < size_t(labels_.size())) - { - return labels_[size_t(index)]; - } - return 0; - } - - inline int CEnumDescription::value(const char* name) const - { - lazyRegister(); - NameToValue::const_iterator it = nameToValue_.find(name); - YASLI_ESCAPE(it != nameToValue_.end(), return 0); - return it->second; - } - inline int CEnumDescription::valueByLabel(const char* label) const - { - lazyRegister(); - LabelToValue::const_iterator it = labelToValue_.find(label); - YASLI_ESCAPE(it != labelToValue_.end(), return 0); - return it->second; - } - - inline void CEnumDescription::lazyRegister() const - { - if (m_regListHead) - { - NameValue* val = m_regListHead; - while (val) - { - const_cast(this)->add(val->m_value, val->m_name, val->m_label); - val = val->m_next; - } - const_cast(this)->m_regListHead = nullptr; - } - } -} -// vim:ts=4 sw=4: - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_ENUMIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/IArchive.h b/Code/CryEngine/CryCommon/Serialization/IArchive.h deleted file mode 100644 index 30de83ccc1..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/IArchive.h +++ /dev/null @@ -1,446 +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_SERIALIZATION_IARCHIVE_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_IARCHIVE_H -#pragma once - - -#include -#include - -#include "Serializer.h" -#include "KeyValue.h" -#include "TypeID.h" - -namespace Serialization { - class IArchive; - - template - bool Serialize(Serialization::IArchive& ar, T& object, const char* name, const char* label); - - class CEnumDescription; - template - CEnumDescription& getEnumDescription(); - bool serializeEnum(const CEnumDescription& desc, IArchive& ar, int& value, const char* name, const char* label); - - // SContextLink should not be used directly. See SContext<> below. - struct SContextLink - { - SContextLink* outer; - TypeID type; - void* contextObject; - - SContextLink() - : outer() - , contextObject() - { - } - }; - - struct SBlackBox; - struct ICallback; - - class IArchive - { - public: - enum ArchiveCaps - { - INPUT = 1 << 0, - OUTPUT = 1 << 1, - TEXT = 1 << 2, - BINARY = 1 << 3, - EDIT = 1 << 4, - INPLACE = 1 << 5, - NO_EMPTY_NAMES = 1 << 6, - VALIDATION = 1 << 7, - DOCUMENTATION = 1 << 8 - }; - - IArchive(int caps) - : caps_(caps) - , filter_(0) - , innerContext_(0) - { - } - virtual ~IArchive() {} - - bool IsInput() const{ return caps_ & INPUT ? true : false; } - bool IsOutput() const{ return caps_ & OUTPUT ? true : false; } - bool IsEdit() const - { -#if !defined(CONSOLE) && !defined(RELEASE) - return (caps_ & EDIT) != 0; -#else - return false; -#endif - } - bool IsInPlace() const{ return caps_ & INPLACE ? true : false; } - bool GetCaps(int caps) const { return (caps_ & caps) == caps; } - - void SetFilter(int filter) - { - filter_ = filter; - } - int GetFilter() const{ return filter_; } - bool Filter(int flags) const - { - YASLI_ASSERT(flags != 0 && "flags is supposed to be a bit mask"); - YASLI_ASSERT(filter_ && "Filter is not set!"); - return (filter_ & flags) != 0; - } - - virtual bool operator()([[maybe_unused]] bool& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] char& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] uint8& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] int8& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] int16& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] uint16& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] int32& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] uint32& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] int64& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] uint64& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] float& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] double& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - - virtual bool operator()([[maybe_unused]] IString& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] IWString& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] const SStruct& ser, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] IContainer& ser, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { return false; } - virtual bool operator()(IPointer& ptr, const char* name = "", const char* label = 0); - virtual bool operator()(IKeyValue& keyValue, const char* name = "", const char* label = 0) { return operator()(SStruct(keyValue), name, label); } - virtual bool operator()([[maybe_unused]] const SBlackBox& blackBox, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { return false; } - virtual bool operator()([[maybe_unused]] ICallback& callback, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { return false; } - - template - bool operator()(const T& value, const char* name = "", const char* label = 0); - - // Error and Warning calls are used for diagnostics and validation of the - // values. Output depends on the specific implementation of IArchive, - // for example PropertyTree uses it to show bubbles with errors in UI - // next to the mentioned property. - template - void Error(T& value, const char* format, ...); - template - void Warning(T& value, const char* format, ...); - - void Error(const void* value, const Serialization::TypeID& type, const char* format, ...); - // Used to add tooltips in PropertyTree - void Doc(const char* docString); - - virtual bool OpenBlock([[maybe_unused]] const char* name, [[maybe_unused]] const char* label) { return true; } - virtual void CloseBlock() {} - - // long, unsigned long and long double are intentionally omitted - - template - T* FindContext() const { return (T*)FindContextByType(TypeID::get()); } - - void* FindContextByType(const TypeID& type) const - { - SContextLink* context = innerContext_; - while (context) - { - if (context->type == type) - { - return context->contextObject; - } - context = context->outer; - } - return 0; - } - - SContextLink* SetInnerContext(SContextLink* context) - { - SContextLink* result = innerContext_; - innerContext_ = context; - return result; - } - SContextLink* GetInnerContext() const{ return innerContext_; } - protected: - virtual void ValidatorMessage([[maybe_unused]] bool error, [[maybe_unused]] const void* handle, [[maybe_unused]] const TypeID& type, [[maybe_unused]] const char* message) {} - virtual void DocumentLastField([[maybe_unused]] const char* text) {} - - void notImplemented() { YASLI_ASSERT(0 && "Not implemented!"); } - - int caps_; - int filter_; - - SContextLink* innerContext_; - }; - - - // IArchive::SContext can be used to establish access to outer objects in serialization stack. - // - // Example: - // void Scene::Serialize(...) { - // IArchive::SContext context(ar, this); - // ar(rootNode, ...); - // } - // - // void Node::Serialize(...) { - // Scene* scene = ar.FindContext(); - // } - template - struct SContext - : SContextLink - { - SContext(IArchive& ar, T* context) - : ar_(&ar) - { - outer = ar_->SetInnerContext(this); - type = TypeID::get(); - contextObject = (void*)context; - } - SContext(T* context) - : ar_(0) - { - outer = 0; - type = TypeID::get(); - contextObject = (void*)context; - } - ~SContext() - { - if (ar_) - { - ar_->SetInnerContext(outer); - } - } - private: - IArchive* ar_; - }; - - namespace detail { - template - struct Selector{}; - - template - struct Selector - { - typedef T2 type; - }; - - template - struct Selector - { - typedef T1 type; - }; - - template - struct Select - { - typedef typename Selector::type selected_type; - typedef typename selected_type::type type; - }; - - template - struct Identity - { - typedef T type; - }; - - - template - struct IsArray - { - enum - { - value = false - }; - }; - - template - struct IsArray< T[Size] > - { - enum - { - value = true - }; - }; - - template - struct ArraySize - { - enum - { - value = true - }; - }; - - template - struct SerializeStruct - { - static bool invoke(IArchive& ar, T& value, const char* name, const char* label) - { - SStruct ser(value); - return ar(ser, name, label); - }; - }; - - template - struct SerializeEnum - { - static bool invoke(IArchive& ar, Enum& value, const char* name, const char* label) - { - const CEnumDescription& enumDescription = getEnumDescription(); - return serializeEnum(enumDescription, ar, reinterpret_cast(value), name, label); - }; - }; - - template - struct SerializeArray{}; - - template - struct SerializeArray - { - static bool invoke(IArchive& ar, T value[Size], const char* name, const char* label) - { - ContainerArray ser(value, Size); - return ar(static_cast(ser), name, label); - } - }; - - - template - struct IsClass - { - private: - struct NoType - { - char dummy; - }; - struct YesType - { - char dummy[100]; - }; - - template - static YesType function_helper(void(U::*)(void)); - - template - static NoType function_helper(...); - public: - enum - { - value = (sizeof(function_helper(0)) == sizeof(YesType)) - }; - }; - } - - template - bool IArchive::operator()(const T& value, const char* name, const char* label) - { - return Serialize(*this, const_cast(value), name, label); - } - - inline bool IArchive::operator()(IPointer& ptr, const char* name, const char* label) - { - return (*this)(SStruct(const_cast(ptr)), name, label); - } - - inline void IArchive::Doc([[maybe_unused]] const char* docString) - { -#if !defined(CONSOLE) && !defined(RELEASE) - if (caps_ & DOCUMENTATION) - { - DocumentLastField(docString); - } -#endif - } - - template - void IArchive::Error([[maybe_unused]] T& value, [[maybe_unused]] const char* format, ...) - { -#if !defined(CONSOLE) && !defined(RELEASE) - if ((caps_ & VALIDATION) == 0) - { - return; - } - va_list args; - va_start(args, format); - char buf[1024]; - azvsnprintf(buf, sizeof(buf), format, args); - va_end(args); - ValidatorMessage(true, &value, TypeID::get(), buf); -#endif - } - - inline void IArchive::Error([[maybe_unused]] const void* handle, [[maybe_unused]] const Serialization::TypeID& type, [[maybe_unused]] const char* format, ...) - { -#if !defined(CONSOLE) && !defined(RELEASE) - if ((caps_ & VALIDATION) == 0) - { - return; - } - va_list args; - va_start(args, format); - char buf[1024]; - azvsnprintf(buf, sizeof(buf), format, args); - va_end(args); - ValidatorMessage(true, handle, type, buf); -#endif - } - - template - void IArchive::Warning([[maybe_unused]] T& value, [[maybe_unused]] const char* format, ...) - { -#if !defined(CONSOLE) && !defined(RELEASE) - if ((caps_ & VALIDATION) == 0) - { - return; - } - va_list args; - va_start(args, format); - char buf[1024]; - azvsnprintf(buf, sizeof(buf), format, args); - va_end(args); - ValidatorMessage(false, &value, TypeID::get(), buf); -#endif - } - - template - bool Serialize(Serialization::IArchive& ar, T object[Size], const char* name, const char* label) - { - YASLI_ASSERT(0); - return false; - } - - template - bool Serialize(Serialization::IArchive& ar, const T& object, const char* name, const char* label) - { - T::unable_to_serialize_CONST_object(); - YASLI_ASSERT(0); - return false; - } - - template - bool Serialize(Serialization::IArchive& ar, T& object, const char* name, const char* label) - { - using namespace Serialization::detail; - - return - Select< IsClass, - Identity< SerializeStruct >, - Select< IsArray, - Identity< SerializeArray >, - Identity< SerializeEnum > - > - >::type::invoke(ar, object, name, label); - } -} - -#include "Serialization/SerializerImpl.h" - -// vim: ts=4 sw=4: - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_IARCHIVE_H diff --git a/Code/CryEngine/CryCommon/Serialization/IArchiveHost.h b/Code/CryEngine/CryCommon/Serialization/IArchiveHost.h deleted file mode 100644 index c2afc1778f..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/IArchiveHost.h +++ /dev/null @@ -1,153 +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 -// IArchiveHost serves a purpose of sharing IArchive implementations among -// diffferent modules. -// -// Example of usage: -// -// struct SType -// { -// void Serialize(Serialization::IArchive& ar); -// }; -// -// SType instanceToSave; -// bool saved = Serialization::SaveJsonFile("Scripts/instance.json", instanceToSave); -// -// SType instanceToLoad; -// bool loaded = Serialization::LoadJsonFile(instanceToLoad, "Scripts/instance.json"); -// -#include -#include - -namespace Serialization -{ - struct IArchiveHost - { - virtual ~IArchiveHost() {} - virtual bool LoadJsonFile(const SStruct& outObj, const char* filename) = 0; - virtual bool SaveJsonFile(const char* filename, const SStruct& obj) = 0; - virtual bool LoadJsonBuffer(const SStruct& outObj, const char* buffer, size_t bufferLength) = 0; - virtual bool SaveJsonBuffer(DynArray& outBuffer, const SStruct& obj) = 0; - - virtual bool LoadBinaryFile(const SStruct& outObj, const char* filename) = 0; - virtual bool SaveBinaryFile(const char* filename, const SStruct& obj) = 0; - virtual bool LoadBinaryBuffer(const SStruct& outObj, const char* buffer, size_t bufferLength) = 0; - virtual bool SaveBinaryBuffer(DynArray& outBuffer, const SStruct& obj) = 0; - virtual bool CloneBinary(const SStruct& dest, const SStruct& source) = 0; - // Compares two instances in serialized form through binary archive - virtual bool CompareBinary(const SStruct& lhs, const SStruct& rhs) = 0; - - virtual bool LoadXmlFile(const SStruct& outObj, const char* filename) = 0; - virtual bool SaveXmlFile(const char* filename, const SStruct& obj, const char* rootNodeName) = 0; - virtual bool LoadXmlNode(const SStruct& outObj, const XmlNodeRef& node) = 0; - virtual XmlNodeRef SaveXmlNode(const SStruct& obj, const char* nodeName) = 0; - virtual bool SaveXmlNode(XmlNodeRef& node, const SStruct& obj) = 0; - }; - - // Syntactic sugar - template - bool LoadJsonFile(T& instance, const char* filename) - { - return gEnv->pSystem->GetArchiveHost()->LoadJsonFile(Serialization::SStruct(instance), filename); - } - - template - bool SaveJsonFile(const char* filename, const T& instance) - { - return gEnv->pSystem->GetArchiveHost()->SaveJsonFile(filename, Serialization::SStruct(instance)); - } - - template - bool LoadJsonBuffer(T& instance, const char* buffer, size_t bufferLength) - { - return gEnv->pSystem->GetArchiveHost()->LoadJsonBuffer(Serialization::SStruct(instance), buffer, bufferLength); - } - - template - bool SaveJsonBuffer(DynArray& outBuffer, const T& instance) - { - return gEnv->pSystem->GetArchiveHost()->SaveJsonBuffer(outBuffer, Serialization::SStruct(instance)); - } - - // --------------------------------------------------------------------------- - - template - bool LoadBinaryFile(T& outInstance, const char* filename) - { - return gEnv->pSystem->GetArchiveHost()->LoadBinaryFile(Serialization::SStruct(outInstance), filename); - } - - template - bool SaveBinaryFile(const char* filename, const T& instance) - { - return gEnv->pSystem->GetArchiveHost()->SaveBinaryFile(filename, Serialization::SStruct(instance)); - } - - template - bool LoadBinaryBuffer(T& outInstance, const char* buffer, size_t bufferLength) - { - return gEnv->pSystem->GetArchiveHost()->LoadBinaryBuffer(Serialization::SStruct(outInstance), buffer, bufferLength); - } - - template - bool SaveBinaryBuffer(DynArray& outBuffer, const T& instance) - { - return gEnv->pSystem->GetArchiveHost()->SaveBinaryBuffer(outBuffer, Serialization::SStruct(instance)); - } - - template - bool CloneBinary(T& outInstance, const T& inInstance) - { - return gEnv->pSystem->GetArchiveHost()->CloneBinary(Serialization::SStruct(outInstance), Serialization::SStruct(inInstance)); - } - - template - bool CompareBinary(const T& lhs, const T& rhs) - { - return gEnv->pSystem->GetArchiveHost()->CompareBinary(Serialization::SStruct(lhs), Serialization::SStruct(rhs)); - } - - // --------------------------------------------------------------------------- - - template - bool LoadXmlFile(T& outInstance, const char* filename) - { - return gEnv->pSystem->GetArchiveHost()->LoadXmlFile(Serialization::SStruct(outInstance), filename); - } - - template - bool SaveXmlFile(const char* filename, const T& instance, const char* rootNodeName) - { - return gEnv->pSystem->GetArchiveHost()->SaveXmlFile(filename, Serialization::SStruct(instance), rootNodeName); - } - - template - bool LoadXmlNode(T& outInstance, const XmlNodeRef& node) - { - return gEnv->pSystem->GetArchiveHost()->LoadXmlNode(Serialization::SStruct(outInstance), node); - } - - template - XmlNodeRef SaveXmlNode(const T& instance, const char* nodeName) - { - return gEnv->pSystem->GetArchiveHost()->SaveXmlNode(Serialization::SStruct(instance), nodeName); - } - - template - bool SaveXmlNode(XmlNodeRef& node, const T& instance) - { - return gEnv->pSystem->GetArchiveHost()->SaveXmlNode(node, Serialization::SStruct(instance)); - } -} diff --git a/Code/CryEngine/CryCommon/Serialization/IClassFactory.h b/Code/CryEngine/CryCommon/Serialization/IClassFactory.h deleted file mode 100644 index bf50b17acd..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/IClassFactory.h +++ /dev/null @@ -1,85 +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_SERIALIZATION_ICLASSFACTORY_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_ICLASSFACTORY_H -#pragma once - -#include - -#include "Serialization/Assert.h" -#include "Serialization/TypeID.h" - -namespace Serialization { - class IArchive; - class TypeDescription - { - public: - TypeDescription(const char* name, const char* label) - : name_(name) - , label_(label) - { - } - const char* name() const{ return name_; } - const char* label() const{ return label_; } - - protected: - const char* name_; - const char* label_; - }; - - class IClassFactory - { - friend class ClassFactoryManager; - public: - IClassFactory(TypeID baseType) - : baseType_(baseType) - , nullLabel_(0) - { - } - - virtual ~IClassFactory() { } - - virtual size_t size() const = 0; - virtual const TypeDescription* descriptionByIndex(int index) const = 0; - virtual const TypeDescription* descriptionByRegisteredName(const char* typeName) const = 0; - virtual const char* findAnnotation(const char* registeredTypeName, const char* annotationName) const = 0; - virtual void serializeNewByIndex(IArchive& ar, int index, const char* name, const char* label) = 0; - - bool setNullLabel(const char* label){ nullLabel_ = label ? label : ""; return true; } - const char* nullLabel() const{ return nullLabel_; } - protected: - TypeID baseType_; - const char* nullLabel_; - IClassFactory* m_next = nullptr; - }; - - - struct TypeNameWithFactory - { - string registeredName; - IClassFactory* factory; - - TypeNameWithFactory(const char* _registeredName, IClassFactory* _factory = 0) - : registeredName(_registeredName) - , factory(_factory) - { - } - }; - - bool Serialize(Serialization::IArchive& ar, Serialization::TypeNameWithFactory& value, const char* name, const char* label); -} - -// vim:ts=4 sw=4: - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_ICLASSFACTORY_H diff --git a/Code/CryEngine/CryCommon/Serialization/ITextInputArchive.h b/Code/CryEngine/CryCommon/Serialization/ITextInputArchive.h deleted file mode 100644 index c9f268d9a4..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/ITextInputArchive.h +++ /dev/null @@ -1,46 +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_SERIALIZATION_ITEXTINPUTARCHIVE_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_ITEXTINPUTARCHIVE_H -#pragma once -#include "Serialization/IArchive.h" -#include "CryExtension/ICryUnknown.h" -#include "CryExtension/CryCreateClassInstance.h" - -namespace Serialization { - class ITextInputArchive - : public ICryUnknown - , public IArchive - { - public: - CRYINTERFACE_DECLARE(ITextInputArchive, 0x1845738b1dcc4168, 0xb440dba776b460c9) - - using IArchive::operator(); - - virtual bool LoadFileUsingCRT(const char* filename) = 0; - virtual bool AttachMemory(const char* buffer, size_t size) = 0; - - protected: - ITextInputArchive(int caps) - : IArchive(caps) {} - }; - - inline AZStd::shared_ptr CreateTextInputArchive() - { - AZStd::shared_ptr pArchive; - CryCreateClassInstance(MAKE_CRYGUID(0x7a83a1c890054608, 0x9f8447a4b0ad6c3b), pArchive); - return pArchive; - } -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_ITEXTINPUTARCHIVE_H diff --git a/Code/CryEngine/CryCommon/Serialization/ITextOutputArchive.h b/Code/CryEngine/CryCommon/Serialization/ITextOutputArchive.h deleted file mode 100644 index e87b819404..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/ITextOutputArchive.h +++ /dev/null @@ -1,55 +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_SERIALIZATION_ITEXTOUTPUTARCHIVE_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_ITEXTOUTPUTARCHIVE_H -#pragma once -#include "Serialization/IArchive.h" -#include "CryExtension/ICryUnknown.h" -#include "CryExtension/CryCreateClassInstance.h" - -namespace Serialization { - class ITextOutputArchive - : public ICryUnknown - , public IArchive - { - CRYINTERFACE_DECLARE(ITextOutputArchive, 0xa273d6157a8b4f0d, 0x80ad6c8031bbfbf3) - public: - virtual bool SaveFileUsingCRT(const char* filename) = 0; - - // use precise but less readable way to write float/double types - virtual void SetExponentFloatRepresentation(bool) = 0; - - // buffer is a null-terminated string - virtual const char* GetBuffer() const = 0; - virtual size_t GetBufferLength() const = 0; - - // by default nested structres are put in one line, unless the line length is - // longer than 'textWidth' - virtual void SetTextWidth(int textWidth) = 0; - - using IArchive::operator(); - protected: - ITextOutputArchive(int caps) - : IArchive(caps) {} - }; - - inline AZStd::shared_ptr CreateTextOutputArchive() - { - AZStd::shared_ptr pArchive; - CryCreateClassInstance(MAKE_CRYGUID(0xd1f14adbc4e74e49, 0x9cea55d80a55cbdb), pArchive); - return pArchive; - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_ITEXTOUTPUTARCHIVE_H diff --git a/Code/CryEngine/CryCommon/Serialization/IXmlArchive.h b/Code/CryEngine/CryCommon/Serialization/IXmlArchive.h deleted file mode 100644 index 07d4438d92..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/IXmlArchive.h +++ /dev/null @@ -1,175 +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_CRYCOMMON_SERIALIZATION_IXMLARCHIVE_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_IXMLARCHIVE_H -#pragma once - - -#include "Serialization/IArchive.h" -#include "CryExtension/ICryUnknown.h" -#include "CryExtension/CryCreateClassInstance.h" - -namespace Serialization -{ - struct IXmlArchive - : public ICryUnknown - , public IArchive - { - public: - CRYINTERFACE_DECLARE(IXmlArchive, 0x1386c94ded174f96, 0xab14d20e1b616588); - - using IArchive::operator(); - - virtual void SetXmlNode(XmlNodeRef pRootNode) = 0; - virtual XmlNodeRef GetXmlNode() const = 0; - - protected: - IXmlArchive(int caps) - : IArchive(caps | IArchive::NO_EMPTY_NAMES) {} - }; - - - typedef AZStd::shared_ptr< IXmlArchive > IXmlArchivePtr; - - - inline IXmlArchivePtr CreateXmlInputArchive() - { - IXmlArchivePtr pArchive; - CryCreateClassInstance("CXmlIArchive", pArchive); - return pArchive; - } - - - inline IXmlArchivePtr CreateXmlInputArchive(XmlNodeRef pXmlNode) - { - if (pXmlNode) - { - IXmlArchivePtr pArchive = CreateXmlInputArchive(); - if (pArchive) - { - pArchive->SetXmlNode(pXmlNode); - } - return pArchive; - } - return IXmlArchivePtr(); - } - - - inline IXmlArchivePtr CreateXmlInputArchive(const char* const filename) - { - XmlNodeRef pXmlNode = gEnv->pSystem->LoadXmlFromFile(filename); - return CreateXmlInputArchive(pXmlNode); - } - - - inline IXmlArchivePtr CreateXmlOutputArchive() - { - IXmlArchivePtr pArchive; - CryCreateClassInstance("CXmlOArchive", pArchive); - return pArchive; - } - - - inline IXmlArchivePtr CreateXmlOutputArchive(XmlNodeRef pXmlNode) - { - if (pXmlNode) - { - IXmlArchivePtr pArchive = CreateXmlOutputArchive(); - if (pArchive) - { - pArchive->SetXmlNode(pXmlNode); - } - return pArchive; - } - return IXmlArchivePtr(); - } - - - inline IXmlArchivePtr CreateXmlOutputArchive(const char* const xmlRootElementName) - { - XmlNodeRef pXmlNode = gEnv->pSystem->CreateXmlNode(xmlRootElementName); - return CreateXmlOutputArchive(pXmlNode); - } - - - template< typename T > - bool StructFromXml(const char* const filename, T& dataOut) - { - Serialization::IXmlArchivePtr pXmlArchive = Serialization::CreateXmlInputArchive(filename); - if (pXmlArchive) - { - Serialization::SStruct serializer = Serialization::SStruct(dataOut); - const bool success = serializer(*pXmlArchive); - return success; - } - return false; - } - - - template< typename T > - bool StructFromXml(XmlNodeRef pXmlNode, T& dataOut) - { - Serialization::IXmlArchivePtr pXmlArchive = Serialization::CreateXmlInputArchive(pXmlNode); - if (pXmlArchive) - { - Serialization::SStruct serializer = Serialization::SStruct(dataOut); - const bool success = serializer(*pXmlArchive); - return success; - } - return false; - } - - - template< typename T > - XmlNodeRef StructToXml(const char* const xmlRootElementName, const T& dataIn) - { - Serialization::IXmlArchivePtr pXmlArchive = Serialization::CreateXmlOutputArchive(xmlRootElementName); - if (pXmlArchive) - { - Serialization::SStruct serializer = Serialization::SStruct(const_cast< T& >(dataIn)); - const bool success = serializer(*pXmlArchive); - if (success) - { - return pXmlArchive->GetXmlNode(); - } - } - return XmlNodeRef(); - } - - - template< typename T > - bool StructToXml(XmlNodeRef pXmlNode, const T& dataIn) - { - Serialization::IXmlArchivePtr pXmlArchive = Serialization::CreateXmlOutputArchive(pXmlNode); - if (pXmlArchive) - { - Serialization::SStruct serializer = Serialization::SStruct(const_cast< T& >(dataIn)); - const bool success = serializer(*pXmlArchive); - return success; - } - return false; - } - - - template< typename T > - bool StructToXml(const char* const filename, const char* const xmlRootElementName, const T& dataIn) - { - XmlNodeRef pXmlNode = Serialization::StructToXml(xmlRootElementName, dataIn); - if (pXmlNode) - { - return pXmlNode->saveToFile(filename); - } - return false; - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_IXMLARCHIVE_H diff --git a/Code/CryEngine/CryCommon/Serialization/IntrusiveFactory.h b/Code/CryEngine/CryCommon/Serialization/IntrusiveFactory.h deleted file mode 100644 index dcd92d51a9..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/IntrusiveFactory.h +++ /dev/null @@ -1,99 +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_SERIALIZATION_INTRUSIVEFACTORY_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_INTRUSIVEFACTORY_H -#pragma once - -#include - -template -class CIntrusiveFactory -{ -private: - struct ICreator - { - virtual TBase* Create() const = 0; - }; - -public: - template - struct SCreator - : ICreator - { - SCreator() { CIntrusiveFactory::Instance().RegisterType(this); } - - TBase* Create() const override { return new TDerived(); } - }; - - static CIntrusiveFactory& Instance() { static CIntrusiveFactory instance; return instance; } - - TBase* Create(const char* keyType) const - { - TCreatorByType::const_iterator it = m_creators.find(keyType); - if (it == m_creators.end() || it->second == 0) - { - return 0; - } - else - { - return it->second->Create(); - } - } - - struct SSerializer - { - _smart_ptr& pointer; - - SSerializer(_smart_ptr& pointer) - : pointer(pointer) {} - - void Serialize(Serialization::IArchive& ar); - }; - -private: - template - void RegisterType(ICreator* creator) - { - const char* type = TDerived::GetType(); - m_creators[type] = creator; - } - - typedef std::map > TCreatorByType; - TCreatorByType m_creators; -}; - -template -void CIntrusiveFactory::SSerializer::Serialize(Serialization::IArchive & ar) -{ - string type = pointer.get() ? pointer->GetInstanceType() : ""; - string oldType = type; - ar(type, "type", "Type"); - if (ar.IsInput()) - { - if (oldType != type) - { - pointer.reset(CIntrusiveFactory::Instance().Create(type.c_str())); - } - } - if (pointer) - { - pointer->Serialize(ar); - } -} - - - -#define REGISTER_IN_INTRUSIVE_FACTORY(BaseType, DerivedType) namespace { CIntrusiveFactory::SCreator baseType##DerivedType##_Creator; } - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_INTRUSIVEFACTORY_H diff --git a/Code/CryEngine/CryCommon/Serialization/KeyValue.h b/Code/CryEngine/CryCommon/Serialization/KeyValue.h deleted file mode 100644 index afe74927df..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/KeyValue.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_KEYVALUE_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_KEYVALUE_H -#pragma once -namespace Serialization { - class IArchive; - - class IKeyValue - : IString - { - public: - virtual const char* get() const = 0; - virtual void set(const char* key) = 0; - virtual bool serializeValue(IArchive& ar, const char* name, const char* label) = 0; - template - void Serialize(TArchive& ar) - { - ar(*(IString*)this, "", "^"); - serializeValue(ar, "", "^"); - } - }; -} - - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_KEYVALUE_H diff --git a/Code/CryEngine/CryCommon/Serialization/Math.h b/Code/CryEngine/CryCommon/Serialization/Math.h deleted file mode 100644 index c7d86935e0..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Math.h +++ /dev/null @@ -1,166 +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. - -// This header extends serialization to support common geometrical types. -// It allows serialization of mentioned below types simple passing them to archive. -// For example: -// -// #include -// #include -// -// Serialization::IArchive& ar; -// -// Vec3 v; -// ar(v, "v"); -// -// QuatT q; -// ar(q, "q"); -// - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_MATH_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_MATH_H -#pragma once -namespace Serialization { - class IArchive; -} - -template -bool Serialize(Serialization::IArchive& ar, struct Vec2_tpl& v, const char* name, const char* label); - -template -bool Serialize(Serialization::IArchive& ar, struct Vec3_tpl& v, const char* name, const char* label); - -template -bool Serialize(Serialization::IArchive& ar, struct Vec4_tpl& v, const char* name, const char* label); - -template -bool Serialize(Serialization::IArchive& ar, struct Quat_tpl& q, const char* name, const char* label); - -template -bool Serialize(Serialization::IArchive& ar, struct QuatT_tpl& qt, const char* name, const char* label); - -template -bool Serialize(Serialization::IArchive& ar, struct Ang3_tpl& a, const char* name, const char* label); - -template -bool Serialize(Serialization::IArchive& ar, struct Matrix34_tpl& value, const char* name, const char* label); - -bool Serialize(Serialization::IArchive& ar, struct AABB& aabb, const char* name, const char* label); - -// --------------------------------------------------------------------------- -// RadiansAsDeg allows to present radian values as degrees to the user in the -// editor. -// -// Example: -// ... -// float radians; -// ar(RadiansAsDeg(radians), "degrees", "Degrees"); -// -// Ang3 euler; -// ar(RadiansAsDeg(euler), "eulerDegrees", "Euler Degrees"); -// -namespace Serialization -{ - template - struct SRadianAng3AsDeg - { - Ang3_tpl* ang3; - SRadianAng3AsDeg(Ang3_tpl* _ang3) - : ang3(_ang3) {} - }; - - template - SRadianAng3AsDeg RadiansAsDeg(Ang3_tpl& radians) - { - return SRadianAng3AsDeg(&radians); - } - - template - struct SRadiansAsDeg - { - T* radians; - SRadiansAsDeg(T* _radians) - : radians(_radians) {} - }; - - template - SRadiansAsDeg RadiansAsDeg(T& radians) - { - return SRadiansAsDeg(&radians); - } - - template - bool Serialize(Serialization::IArchive& ar, Serialization::SRadiansAsDeg& value, const char* name, const char* label); - template - bool Serialize(Serialization::IArchive& ar, Serialization::SRadianAng3AsDeg& value, const char* name, const char* label); - - // --------------------------------------------------------------------------- - // QuatAsAng3 provides a wrapper that allows editing of quaternions as Ang3 (in degrees). - // - // Example: - // ... - // Quat q; - // ar(QuatAsAng3(q), "orientation", "Orientation"); - // - - template - struct QuatAsAng3 - { - Quat_tpl* quat; - QuatAsAng3(Quat_tpl& _quat) - : quat(&_quat) {} - }; - - template - bool Serialize(Serialization::IArchive& ar, Serialization::QuatAsAng3& value, const char* name, const char* label); - - // --------------------------------------------------------------------------- - // QuatTAsVec3Ang3 provides a wrapper that allows editing of transforms as Vec3 and Ang3 (in degrees). - // - // Example: - // ... - // QuatT trans; - // ar(QuatTAsVec3Ang3(trans), "transform", "Transform"); - // - - template - struct QuatTAsVec3Ang3 - { - QuatT_tpl* trans; - QuatTAsVec3Ang3(QuatT_tpl& _trans) - : trans(&_trans) {} - }; - - template - bool Serialize(Serialization::IArchive& ar, Serialization::QuatTAsVec3Ang3& value, const char* name, const char* label); - - // --------------------------------------------------------------------------- - // Helper functions for Ang3 - // - // Example: - // ... - // Quat q; - // QuatT trans; - // ar(AsAng3(q),"orientation","Orientation"); - // ar(AsAnge(trans),"transform", "Transform"); - // - - template - inline QuatAsAng3 AsAng3(Quat_tpl& q){ return QuatAsAng3(q); } - template - inline QuatTAsVec3Ang3 AsAng3(QuatT_tpl& trans){ return QuatTAsVec3Ang3(trans); } -} - -#include "MathImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_MATH_H diff --git a/Code/CryEngine/CryCommon/Serialization/MathImpl.h b/Code/CryEngine/CryCommon/Serialization/MathImpl.h deleted file mode 100644 index 95ff63e179..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/MathImpl.h +++ /dev/null @@ -1,207 +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_SERIALIZATION_MATHIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_MATHIMPL_H -#pragma once - -#include "Serialization/IArchive.h" - -#include "Cry_Vector2.h" -#include "Cry_Vector3.h" -#include "Cry_Vector4.h" -#include "Cry_Quat.h" -#include "Cry_Matrix34.h" -#include "Cry_Geo.h" - - -template -bool Serialize(Serialization::IArchive& ar, Vec2_tpl& value, const char* name, const char* label) -{ - typedef T (& Array)[2]; - return ar((Array)value, name, label); -} - -template -bool Serialize(Serialization::IArchive& ar, Vec3_tpl& value, const char* name, const char* label) -{ - typedef T (& Array)[3]; - return ar((Array)value, name, label); -} - -template -inline bool Serialize(Serialization::IArchive& ar, struct Vec4_tpl& v, const char* name, const char* label) -{ - typedef T (& Array)[4]; - return ar((Array)v, name, label); -} - - -template -bool Serialize(Serialization::IArchive& ar, struct Quat_tpl& value, const char* name, const char* label) -{ - typedef T (& Array)[4]; - return ar((Array)value, name, label); -} - -template -struct SerializableQuatT - : QuatT_tpl -{ - void Serialize(Serialization::IArchive& ar) - { - ar(this->q, "q", "Quaternion"); - ar(this->t, "t", "Translation"); - } -}; - -template -bool Serialize(Serialization::IArchive& ar, struct QuatT_tpl& value, const char* name, const char* label) -{ - return Serialize(ar, static_cast&>(value), name, label); -} - -struct SerializableAABB - : AABB -{ - void Serialize(Serialization::IArchive& ar) - { - ar(this->min, "min", "Min"); - ar(this->max, "max", "Max"); - } -}; - -inline bool Serialize(Serialization::IArchive& ar, struct AABB& value, const char* name, const char* label) -{ - return Serialize(ar, static_cast(value), name, label); -} - -template -bool Serialize(Serialization::IArchive& ar, Matrix34_tpl& value, const char* name, const char* label) -{ - typedef T (& Array)[3][4]; - return ar((Array)value, name, label); -} - -////////////////////////////////////////////////////////////////////////// - - -namespace Serialization -{ - template - bool Serialize(Serialization::IArchive& ar, Serialization::SRadiansAsDeg& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - float degrees = RAD2DEG(*value.radians); - float oldDegrees = degrees; - if (!ar(degrees, name, label)) - { - return false; - } - if (oldDegrees != degrees) - { - *value.radians = DEG2RAD(degrees); - } - return true; - } - else - { - return ar(*value.radians, name, label); - } - } - - template - bool Serialize(Serialization::IArchive& ar, Serialization::SRadianAng3AsDeg& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - Ang3 degrees(RAD2DEG(value.ang3->x), RAD2DEG(value.ang3->y), RAD2DEG(value.ang3->z)); - Ang3 oldDegrees = degrees; - if (!ar(degrees, name, label)) - { - return false; - } - if (oldDegrees != degrees) - { - *value.ang3 = Ang3(DEG2RAD(degrees.x), DEG2RAD(degrees.y), DEG2RAD(degrees.z)); - } - return true; - } - else - { - return ar(*value.ang3, name, label); - } - } -} - -////////////////////////////////////////////////////////////////////////// - -template -bool Serialize(Serialization::IArchive& ar, Ang3_tpl& value, const char* name, const char* label) -{ - typedef T (& Array)[3]; - return ar((Array)value, name, label); -} - -////////////////////////////////////////////////////////////////////////// - -namespace Serialization -{ - template - bool Serialize(Serialization::IArchive& ar, Serialization::QuatAsAng3& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - Ang3 ang3(*value.quat); - Ang3 oldAng3 = ang3; - if (!ar(Serialization::RadiansAsDeg(ang3), name, label)) - { - return false; - } - if (ang3 != oldAng3) - { - *value.quat = Quat(ang3); - } - return true; - } - else - { - return ar(*value.quat, name, label); - } - } - - template - bool Serialize(Serialization::IArchive& ar, Serialization::QuatTAsVec3Ang3& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - if (!ar.OpenBlock(name, label)) - { - return false; - } - - ar(QuatAsAng3((value.trans)->q), "rot", "Rotation"); - ar.Doc("Euler Angles in degrees"); - ar((value.trans)->t, "t", "Translation"); - ar.CloseBlock(); - return true; - } - else - { - return ar(*(value.trans), name, label); - } - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_MATHIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/NetScriptSerialize.h b/Code/CryEngine/CryCommon/Serialization/NetScriptSerialize.h deleted file mode 100644 index 8c66452419..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/NetScriptSerialize.h +++ /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. -* -*/ -#ifndef CRYINCLUDE_CRYCOMMON_CRYSCRIPTSYSTEM_NETSCRIPTSERIALIZE_H -#define CRYINCLUDE_CRYCOMMON_CRYSCRIPTSYSTEM_NETSCRIPTSERIALIZE_H - -namespace Serialization -{ - class INetScriptMarshaler - { - public: - virtual TSerialize FindSerializer(const char* name) = 0; - virtual bool CommitSerializer(const char* name, TSerialize serializer) = 0; - - virtual int GetMaxServerProperties() const = 0; - }; -} - -#endif diff --git a/Code/CryEngine/CryCommon/Serialization/Object.h b/Code/CryEngine/CryCommon/Serialization/Object.h deleted file mode 100644 index d304883452..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Object.h +++ /dev/null @@ -1,153 +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_SERIALIZATION_OBJECT_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_OBJECT_H -#pragma once - -#include "Serializer.h" - -// --------------------------------------------------------------------------- - -namespace Serialization { - typedef int(* AddRefFunc)(void*); - typedef int(* DecRefFunc)(void*); - - // represents a reference to the persistent object - class Object - { - public: - Object() - : address_(0) - , addRefFunc_(0) - , decRefFunc_(0) - , serializeFunc_(0) - { - } - - Object(const Object& o) - : address_(o.address_) - , type_(o.type_) - , addRefFunc_(o.addRefFunc_) - , decRefFunc_(o.decRefFunc_) - , serializeFunc_(o.serializeFunc_) - { - addRef(); - } - - Object(const SStruct& ser) - : address_(ser.pointer()) - , type_(ser.type()) - , addRefFunc_(0) - , decRefFunc_(0) - , serializeFunc_(ser.serializeFunc()) - { - } - - Object(void* address, const TypeID& type, AddRefFunc addRefFunc, DecRefFunc decRefFunc, SerializeStructFunc serializeFunc) - : address_(address) - , type_(type) - , addRefFunc_(addRefFunc) - , decRefFunc_(decRefFunc) - , serializeFunc_(serializeFunc) - { - addRef(); - } - - ~Object() - { - if (address_) - { - decRef(); - address_ = 0; - } - } - - void* address() const{ return address_; } - const TypeID& type() const{ return type_; } - bool isSet() { return serializeFunc_ != 0; } - - int addRef() - { - if (!addRefFunc_) - { - return 1; - } - if (!address_) - { - return -1; - } - return addRefFunc_(address_); - } - - int decRef() - { - if (!decRefFunc_) - { - return 1; - } - if (!address_) - { - return -1; - } - return decRefFunc_(address_); - } - - bool operator()(IArchive& ar) const - { - if (!serializeFunc_ || !address_) - { - return false; - } - return serializeFunc_(address_, ar); - } - - SStruct serializer() const - { - return SStruct(type_, address_, 0, serializeFunc_); - } - - Object& operator=(const Object& o) - { - if (this == &o) - { - return *this; - } - - if (address_) - { - decRef(); - } - - address_ = o.address_; - type_ = o.type_; - addRefFunc_ = o.addRefFunc_; - decRefFunc_ = o.decRefFunc_; - serializeFunc_ = o.serializeFunc_; - - addRef(); - return *this; - } - - private: - void* address_; - TypeID type_; - AddRefFunc addRefFunc_; - DecRefFunc decRefFunc_; - SerializeStructFunc serializeFunc_; - }; -} - -// --------------------------------------------------------------------------- - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_OBJECT_H diff --git a/Code/CryEngine/CryCommon/Serialization/STL.h b/Code/CryEngine/CryCommon/Serialization/STL.h deleted file mode 100644 index 357a8937a4..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/STL.h +++ /dev/null @@ -1,52 +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_SERIALIZATION_STL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_STL_H -#pragma once - - -#include -#include -#include - -#include "Serialization/Serializer.h" - -namespace Serialization { - class IArchive; -} - -namespace std -{ - template - bool Serialize(Serialization::IArchive& ar, std::pair& pair, const char* name, const char* label); - - template - bool Serialize(Serialization::IArchive& ar, std::vector& container, const char* name, const char* label); - - template - bool Serialize(Serialization::IArchive& ar, std::list& container, const char* name, const char* label); - - template - bool Serialize(Serialization::IArchive& ar, std::map& container, const char* name, const char* label); -} - -namespace Serialization -{ - bool Serialize(Serialization::IArchive& ar, Serialization::string& value, const char* name, const char* label); - bool Serialize(Serialization::IArchive& ar, Serialization::wstring& value, const char* name, const char* label); -} - -#include "STLImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_STL_H diff --git a/Code/CryEngine/CryCommon/Serialization/STLImpl.h b/Code/CryEngine/CryCommon/Serialization/STLImpl.h deleted file mode 100644 index b03d877b55..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/STLImpl.h +++ /dev/null @@ -1,251 +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_SERIALIZATION_STLIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_STLIMPL_H -#pragma once - - -#include "Serialization/IArchive.h" -#include "Serialization/Serializer.h" - -namespace Serialization { - template - class ContainerSTL - : public IContainer /*{{{*/ - { - public: - explicit ContainerSTL(Container* container = 0) - : container_(container) - , it_(container->begin()) - , size_(container->size()) - { - YASLI_ASSERT(container_ != 0); - } - - template - void resizeHelper(size_t _size, std::vector* _v) const - { - _v->resize(_size); - } - - void resizeHelper(size_t _size, ...) const - { - while (size_t(container_->size()) > _size) - { - typename Container::iterator it = container_->end(); - --it; - container_->erase(it); - } - while (size_t(container_->size()) < _size) - { - container_->insert(container_->end(), Element()); - } - } - - // from ContainerSerializationInterface - size_t size() const - { - YASLI_ESCAPE(container_ != 0, return 0); - return container_->size(); - } - size_t resize(size_t size) - { - YASLI_ESCAPE(container_ != 0, return 0); - resizeHelper(size, container_); - it_ = container_->begin(); - size_ = size; - return size; - } - - void* pointer() const{ return reinterpret_cast(container_); } - TypeID elementType() const{ return TypeID::get(); } - TypeID containerType() const{ return TypeID::get(); } - - - bool next() - { - YASLI_ESCAPE(container_ && it_ != container_->end(), return false); - ++it_; - return it_ != container_->end(); - } - - void* elementPointer() const { return &*it_; } - size_t elementSize() const { return sizeof(typename Container::value_type); } - - bool operator()(IArchive& ar, const char* name, const char* label) - { - YASLI_ESCAPE(container_, return false); - if (it_ == container_->end()) - { - it_ = container_->insert(container_->end(), Element()); - return ar(*it_, name, label); - } - else - { - return ar(*it_, name, label); - } - } - operator bool() const{ - return container_ != 0; - } - void serializeNewElement(IArchive& ar, const char* name = "", const char* label = 0) const - { - Element element; - ar(element, name, label); - } - // ^^^ - protected: - Container* container_; - typename Container::iterator it_; - size_t size_; - };/*}}}*/ -} - -namespace std -{ - template - bool Serialize(Serialization::IArchive& ar, std::vector& container, const char* name, const char* label) - { - Serialization::ContainerSTL, T> ser(&container); - return ar(static_cast(ser), name, label); - } - - template - bool Serialize(Serialization::IArchive& ar, std::list& container, const char* name, const char* label) - { - Serialization::ContainerSTL, T> ser(&container); - return ar(static_cast(ser), name, label); - } - - template - bool Serialize(Serialization::IArchive& ar, std::map& container, const char* name, const char* label) - { - std::vector > temp; - if (ar.IsOutput()) - { - temp.assign(container.begin(), container.end()); - } - if (!ar(temp, name, label)) - { - return false; - } - if (ar.IsInput()) - { - container.clear(); - container.insert(temp.begin(), temp.end()); - } - return true; - } -} - -// --------------------------------------------------------------------------- -namespace Serialization { - class StringSTL - : public IString - { - public: - StringSTL(string& str) - : str_(str) { } - - void set(const char* value) { str_ = value; } - const char* get() const { return str_.c_str(); } - const void* handle() const { return &str_; } - TypeID type() const { return TypeID::get(); } - private: - string& str_; - }; - - inline bool Serialize(Serialization::IArchive& ar, Serialization::string& value, const char* name, const char* label) - { - Serialization::StringSTL str(value); - return ar(static_cast(str), name, label); - } - - // --------------------------------------------------------------------------- - - class WStringSTL - : public IWString - { - public: - WStringSTL(Serialization::wstring& str) - : str_(str) { } - - void set(const wchar_t* value) { str_ = value; } - const wchar_t* get() const { return str_.c_str(); } - const void* handle() const { return &str_; } - TypeID type() const { return TypeID::get(); } - private: - wstring& str_; - }; - - inline bool Serialize(Serialization::IArchive& ar, Serialization::wstring& value, const char* name, const char* label) - { - Serialization::WStringSTL str(value); - return ar(static_cast(str), name, label); - } - - // --------------------------------------------------------------------------- - - template - struct StdPair - { - StdPair(std::pair& pair) - : pair_(pair) {} - void Serialize(Serialization::IArchive& ar) - { - ar(pair_.first, "key", "Key"); - ar(pair_.second, "value", "Value"); - } - std::pair& pair_; - }; - - template - struct StdStringPair - : Serialization::IKeyValue - { - const char* get() const { return pair_.first.c_str(); } - void set(const char* key) { pair_.first.assign(key); } - const void* handle() const { return &pair_; } - Serialization::TypeID type() const { return Serialization::TypeID::get(); } - bool serializeValue(Serialization::IArchive& ar, const char* name, const char* label) - { - return ar(pair_.second, name, label); - } - - StdStringPair(std::pair& pair) - : pair_(pair) - { - } - - std::pair& pair_; - }; -} - -namespace std -{ - template - bool Serialize(Serialization::IArchive& ar, std::pair& pair, const char* name, const char* label) - { - Serialization::StdPair keyValue(pair); - return ar(keyValue, name, label); - } - - template - bool Serialize(Serialization::IArchive& ar, std::pair& pair, const char* name, const char* label) - { - Serialization::StdStringPair keyValue(pair); - return ar(static_cast(keyValue), name, label); - } -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_STLIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Serializer.h b/Code/CryEngine/CryCommon/Serialization/Serializer.h deleted file mode 100644 index 13acc57cec..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Serializer.h +++ /dev/null @@ -1,268 +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_SERIALIZATION_SERIALIZER_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_SERIALIZER_H -#pragma once - - -#include -#include "Assert.h" -#include "TypeID.h" - -namespace Serialization { - class IArchive; - class IClassFactory; - - typedef bool(* SerializeStructFunc)(void*, IArchive&); - - typedef bool(* SerializeContainerFunc)(void*, IArchive&, size_t index); - typedef size_t(* ContainerResizeFunc)(void*, size_t size); - typedef size_t(* ContainerSizeFunc)(void*); - - // Struct serializer. - // - // This type is used to pass needed struct/class type information through abstract interface. - // Most importantly it captures: - // - pointer to object - // - reference to serialize method (indirectly through pointer to static func.) - // - TypeID - struct SStruct/*{{{*/ - { - friend class IArchive; - public: - SStruct() - : object_(0) - , size_(0) - , serializeFunc_(0) - { - } - - SStruct(TypeID type, void* object, size_t size, SerializeStructFunc Serialize) - : type_(type) - , object_(object) - , size_(size) - , serializeFunc_(Serialize) - { - YASLI_ASSERT(object != 0); - } - - SStruct(const SStruct& _original) - : type_(_original.type_) - , object_(_original.object_) - , size_(_original.size_) - , serializeFunc_(_original.serializeFunc_) - { - } - - template - explicit SStruct(const T& object) - { - type_ = TypeID::get(); - object_ = (void*)(&object); - size_ = sizeof(T); - serializeFunc_ = &SStruct::serializeRaw; - } - - template - explicit SStruct(const T& object, TypeID type) - { - type_ = type; - object_ = (void*)(&object); - size_ = sizeof(T); - serializeFunc_ = &SStruct::serializeRaw; - } - - // This constructs SStruct from an object that doesn't have Serialize method. - // Such SStruct can not be serialized but conveys object reference and type - // information that is needed for Property-archives. Used for decorators. - template - static SStruct ForEdit(const T& object) - { - SStruct r; - r.type_ = TypeID::get(); - r.object_ = (void*)&object; - r.size_ = sizeof(T); - r.serializeFunc_ = 0; - return r; - } - - bool operator()(IArchive& ar, const char* name, const char* label) const; - bool operator()(IArchive& ar) const; - operator bool() const{ - return object_ != 0; - } - bool operator==(const SStruct& rhs) const{ return object_ == rhs.object_ && serializeFunc_ == rhs.serializeFunc_; } - bool operator!=(const SStruct& rhs) const{ return !operator==(rhs); } - void* pointer() const{ return object_; } - void setPointer(void* p) { object_ = p; } - TypeID type() const{ return type_; } - void setType(const TypeID& type) { type_ = type; } - size_t size() const{ return size_; } - SerializeStructFunc serializeFunc() const{ return serializeFunc_; } - - template - static bool serializeRaw(void* rawPointer, IArchive& ar) - { - YASLI_ESCAPE(rawPointer, return false); - // If you're getting compile error here, most likely, you have one of the following situations: - // - The type you're trying to serialize doesn't have Serialize _method_ implemented. - // - Type is supposed to be serialized with non-member Serialize function and this function is out of scope. - ((T*)(rawPointer))->Serialize(ar); - return true; - } - - template - T* cast() const - { - if (type_ == Serialization::TypeID::get()) - { - return (T*)object_; - } - else - { - return 0; - } - } - private: - - TypeID type_; - void* object_; - size_t size_; - SerializeStructFunc serializeFunc_; - };/*}}}*/ - typedef std::vector SStructs; - - // --------------------------------------------------------------------------- - - // This type is used to generalize access to specific container types. - // It is used by concrete IArchive implementations. - class IContainer - { - public: - virtual ~IContainer() { } - - virtual size_t size() const = 0; - virtual size_t resize(size_t size) = 0; - virtual bool isFixedSize() const{ return false; } - - virtual void* pointer() const = 0; - virtual bool next() = 0; - virtual TypeID containerType() const = 0; - - virtual TypeID elementType() const = 0; - virtual void* elementPointer() const = 0; - virtual size_t elementSize() const = 0; - - virtual bool operator()(IArchive& ar, const char* name, const char* label) = 0; - virtual operator bool() const = 0; - virtual void serializeNewElement(IArchive& ar, const char* name = "", const char* label = 0) const = 0; - }; - - template - class ContainerArray - : public IContainer /*{{{*/ - { - friend class IArchive; - public: - explicit ContainerArray(T* array = 0, int size = 0) - : array_(array) - , index_(0) - , size_(size) - { - } - - // from ContainerSerializationInterface: - size_t size() const{ return size_; } - size_t resize([[maybe_unused]] size_t size) - { - index_ = 0; - return size_; - } - - void* pointer() const{ return reinterpret_cast(array_); } - TypeID containerType() const{ return TypeID::get(); } - TypeID elementType() const{ return TypeID::get(); } - void* elementPointer() const { return &array_[index_]; } - size_t elementSize() const { return sizeof(T); } - virtual bool isFixedSize() const{ return true; } - - bool operator()(IArchive& ar, const char* name, const char* label) - { - YASLI_ESCAPE(size_t(index_) < size_, return false); - return ar(array_[index_], name, label); - } - operator bool() const{ - return array_ != 0; - } - bool next() - { - ++index_; - return size_t(index_) < size_; - } - void serializeNewElement(IArchive& ar, const char* name, const char* label) const - { - T element; - ar(element, name, label); - } - // ^^^ - - private: - T* array_; - int index_; - size_t size_; - };/*}}}*/ - - // Generialized interface over owning polymorphic pointers. - // Used by concrete IArchive implementations. - class IPointer - { - public: - virtual ~IPointer() { } - - virtual const char* registeredTypeName() const = 0; - virtual void create(const char* registedTypeName) const = 0; - virtual TypeID baseType() const = 0; - virtual SStruct serializer() const = 0; - virtual void* get() const = 0; - virtual const void* handle() const = 0; - virtual TypeID pointerType() const = 0; - virtual IClassFactory* factory() const = 0; - - void Serialize(IArchive& ar) const; - }; - - class IString - { - public: - virtual ~IString() { } - - virtual void set(const char* value) = 0; - virtual const char* get() const = 0; - virtual const void* handle() const = 0; - virtual TypeID type() const = 0; - }; - class IWString - { - public: - virtual ~IWString() { } - - virtual void set(const wchar_t* value) = 0; - virtual const wchar_t* get() const = 0; - virtual const void* handle() const = 0; - virtual TypeID type() const = 0; - }; -} -// vim:ts=4 sw=4: - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_SERIALIZER_H diff --git a/Code/CryEngine/CryCommon/Serialization/SerializerImpl.h b/Code/CryEngine/CryCommon/Serialization/SerializerImpl.h deleted file mode 100644 index f4e89c185d..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/SerializerImpl.h +++ /dev/null @@ -1,95 +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_SERIALIZATION_SERIALIZERIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_SERIALIZERIMPL_H -#pragma once - -#include "Serializer.h" -#include "IClassFactory.h" -#include "ClassFactory.h" - -// IArchive.h is supposed to be pre-included - -namespace Serialization { - inline bool SStruct::operator()(IArchive& ar) const - { - YASLI_ESCAPE(serializeFunc_ && object_, return false); - return serializeFunc_(object_, ar); - } - - inline bool SStruct::operator()(IArchive& ar, const char* name, const char* label) const - { - return ar(*this, name, label); - } - - - inline void IPointer::Serialize(IArchive& ar) const - { - const bool noEmptyNames = ar.GetCaps(IArchive::NO_EMPTY_NAMES); - const char* const typePropertyName = noEmptyNames ? "type" : ""; - const char* const dataPropertyName = noEmptyNames ? "data" : ""; - - TypeID baseTypeID = baseType(); - const char* oldRegisteredName = registeredTypeName(); - if (!oldRegisteredName) - { - oldRegisteredName = ""; - } - IClassFactory* factory = this->factory(); - - if (ar.IsOutput()) - { - if (oldRegisteredName[0] != '\0') - { - TypeNameWithFactory pair(oldRegisteredName, factory); - if (ar(pair, typePropertyName)) - { - ar(serializer(), dataPropertyName); - } - else - { - ar.Warning(pair, "Unable to write typeID!"); - } - } - } - else - { - TypeNameWithFactory pair("", factory); - if (!ar(pair, typePropertyName)) - { - if (oldRegisteredName[0] != '\0') - { - create(""); // 0 - } - return; - } - - if (oldRegisteredName[0] != '\0' && (pair.registeredName.empty() || (pair.registeredName != oldRegisteredName))) - { - create(""); // 0 - } - if (!pair.registeredName.empty()) - { - if (!get()) - { - create(pair.registeredName.c_str()); - } - ar(serializer(), dataPropertyName); - } - } - } -} -// vim:sw=4 ts=4: - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_SERIALIZERIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/SmartPtr.h b/Code/CryEngine/CryCommon/Serialization/SmartPtr.h deleted file mode 100644 index 8c109887b7..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/SmartPtr.h +++ /dev/null @@ -1,31 +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_SERIALIZATION_SMARTPTR_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_SMARTPTR_H -#pragma once - -template -class _smart_ptr; - -namespace Serialization -{ - class IArchive; -}; - -template -bool Serialize(Serialization::IArchive& ar, _smart_ptr& ptr, const char* name, const char* label); - -#include "SmartPtrImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_SMARTPTR_H diff --git a/Code/CryEngine/CryCommon/Serialization/SmartPtrImpl.h b/Code/CryEngine/CryCommon/Serialization/SmartPtrImpl.h deleted file mode 100644 index 64cd7f65c1..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/SmartPtrImpl.h +++ /dev/null @@ -1,73 +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_SERIALIZATION_SMARTPTRIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_SMARTPTRIMPL_H -#pragma once - -#include "SmartPtr.h" -#include -#include "ClassFactory.h" - -// Exposes _smart_ptr<> as serializeable type for Serialization::IArchive -template -class SmartPtrSerializer - : public Serialization::IPointer -{ -public: - SmartPtrSerializer(_smart_ptr& ptr) - : m_ptr(ptr) - {} - - const char* registeredTypeName() const override - { - if (m_ptr) - { - return Serialization::ClassFactory::the().getRegisteredTypeName(m_ptr.get()); - } - else - { - return ""; - } - } - - void create(const char* registeredTypeName) const override - { - CRY_ASSERT(!m_ptr || m_ptr->NumRefs() == 1); - if (registeredTypeName && registeredTypeName[0] != '\0') - { - m_ptr.reset(Serialization::ClassFactory::the().create(registeredTypeName)); - } - else - { - m_ptr.reset((T*)0); - } - } - Serialization::TypeID baseType() const{ return Serialization::TypeID::get(); } - virtual Serialization::SStruct serializer() const{ return Serialization::SStruct(*m_ptr); } - void* get() const{ return reinterpret_cast(m_ptr.get()); } - const void* handle() const { return &m_ptr; } - Serialization::TypeID pointerType() const { return Serialization::TypeID::get<_smart_ptr >(); } - Serialization::IClassFactory* factory() const{ return &Serialization::ClassFactory::the(); } -protected: - _smart_ptr& m_ptr; -}; - -template -bool Serialize(Serialization::IArchive& ar, _smart_ptr& ptr, const char* name, const char* label) -{ - SmartPtrSerializer serializer(ptr); - return ar(static_cast(serializer), name, label); -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_SMARTPTRIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/StringList.h b/Code/CryEngine/CryCommon/Serialization/StringList.h deleted file mode 100644 index 4b2ca96278..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/StringList.h +++ /dev/null @@ -1,301 +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_SERIALIZATION_STRINGLIST_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_STRINGLIST_H -#pragma once - - -#include -#include "Serialization/Strings.h" -#include "Serialization/DynArray.h" -#include -#include "Serialization/Assert.h" -#ifndef SERIALIZATION_STANDALONE -#include -#endif - -#include - -namespace Serialization { - class IArchive; - class StringListStatic -#ifdef SERIALIZATION_STANDALONE - : public std::vector - { -#else - : public AZStd::fixed_vector { -#endif - public: - enum - { - npos = -1 - }; - int find(const char* value) const - { - int numItems = int(size()); - for (int i = 0; i < numItems; ++i) - { - if (strcmp((*this)[i], value) == 0) - { - return i; - } - } - return npos; - } - }; - - class StringListStaticValue - { - public: - StringListStaticValue(const StringListStaticValue& original) - : stringList_(original.stringList_) - , index_(original.index_) - { - handle_ = this; - } - StringListStaticValue() - : stringList_(0) - , index_(StringListStatic::npos) - { - handle_ = this; - } - StringListStaticValue(const StringListStatic& stringList, int value) - : stringList_(&stringList) - , index_(value) - { - handle_ = this; - } - StringListStaticValue(const StringListStatic& stringList, int value, const void* handle, const Serialization::TypeID& type) - : stringList_(&stringList) - , index_(value) - , handle_(handle) - , type_(type) - { - } - StringListStaticValue(const StringListStatic& stringList, const char* value, const void* handle, const Serialization::TypeID& type) - : stringList_(&stringList) - , index_(stringList.find(value)) - , handle_(handle) - , type_(type) - { - YASLI_ASSERT(index_ != StringListStatic::npos); - } - StringListStaticValue& operator=(const char* value) - { - index_ = stringList_->find(value); - return *this; - } - StringListStaticValue& operator=(int value) - { - YASLI_ASSERT(value >= 0 && size_t(value) < size_t(stringList_->size())); - YASLI_ASSERT(this != 0); - index_ = value; - return *this; - } - StringListStaticValue& operator=(const StringListStaticValue& rhs) - { - stringList_ = rhs.stringList_; - index_ = rhs.index_; - return *this; - } - const char* c_str() const - { - if (index_ >= 0 && size_t(index_) < size_t(stringList_->size())) - { - return (*stringList_)[index_]; - } - else - { - return ""; - } - } - int index() const{ return index_; } - const void* handle() const{ return handle_; } - Serialization::TypeID type() const { return type_; } - const StringListStatic& stringList() const{ return *stringList_; } - template - void Serialize(IArchive& ar) - { - ar(index_, "index"); - } - protected: - const StringListStatic* stringList_; - int index_; - const void* handle_; - Serialization::TypeID type_; - }; - - class StringList -#ifdef SERIALIZATION_STANDALONE - : public std::vector - { -#else - : public DynArray{ -#endif - public: - StringList() {} - StringList(const StringList& rhs) - { - *this = rhs; - } - StringList& operator=(const StringList& rhs) - { - // As StringList crosses dll boundaries it is important to copy strings - // rather than reference count them to be sure that stored CryString uses - // proper allocator. - resize(rhs.size()); - for (size_t i = 0; i < size_t(size()); ++i) - { - (*this)[i] = rhs[i].c_str(); - } - return *this; - } - StringList(const StringListStatic& rhs) - { - const int size = int(rhs.size()); - resize(size); - for (int i = 0; i < int(size); ++i) - { - (*this)[i] = rhs[i]; - } - } - enum - { - npos = -1 - }; - int find(const char* value) const - { - const int numItems = int(size()); - for (int i = 0; i < numItems; ++i) - { - if ((*this)[i] == value) - { - return i; - } - } - return npos; - } - }; - - class StringListValue - { - public: - explicit StringListValue(const StringListStaticValue& value) - { - stringList_.resize(value.stringList().size()); - for (size_t i = 0; i < size_t(stringList_.size()); ++i) - { - stringList_[i] = value.stringList()[i]; - } - index_ = value.index(); - } - StringListValue(const StringListValue& value) - { - stringList_ = value.stringList_; - index_ = value.index_; - } - StringListValue() - : index_(StringList::npos) - { - handle_ = this; - } - StringListValue(const StringList& stringList, int value) - : stringList_(stringList) - , index_(value) - { - handle_ = this; - } - StringListValue(const StringList& stringList, int value, const void* handle, const Serialization::TypeID& typeId) - : stringList_(stringList) - , index_(value) - , handle_(handle) - , type_(typeId) - { - } - StringListValue(const StringList& stringList, const char* value) - : stringList_(stringList) - , index_(stringList.find(value)) - { - handle_ = this; - YASLI_ASSERT(index_ != StringList::npos); - } - StringListValue(const StringList& stringList, const char* value, const void* handle, const Serialization::TypeID& typeId) - : stringList_(stringList) - , index_(stringList.find(value)) - , handle_(handle) - , type_(typeId) - { - YASLI_ASSERT(index_ != StringList::npos); - } - StringListValue(const StringListStatic& stringList, const char* value) - : stringList_(stringList) - , index_(stringList.find(value)) - { - handle_ = this; - YASLI_ASSERT(index_ != StringList::npos); - } - StringListValue& operator=(const char* value) - { - index_ = stringList_.find(value); - return *this; - } - StringListValue& operator=(int value) - { - YASLI_ASSERT(value >= 0 && size_t(value) < size_t(stringList_.size())); - YASLI_ASSERT(this != 0); - index_ = value; - return *this; - } - const char* c_str() const - { - if (index_ >= 0 && size_t(index_) < size_t(stringList_.size())) - { - return stringList_[index_].c_str(); - } - else - { - return ""; - } - } - int index() const{ return index_; } - const void* handle() const { return handle_; } - Serialization::TypeID type() const { return type_; } - const StringList& stringList() const{ return stringList_; } - template - void Serialize(IArchive& ar) - { - ar(index_, "index"); - ar(stringList_, "stringList"); - } - protected: - StringList stringList_; - int index_; - const void* handle_; - Serialization::TypeID type_; - }; - - class IArchive; - - void splitStringList(StringList* result, const char* str, char sep); - void joinStringList(string* result, const StringList& stringList, char sep); - void joinStringList(string* result, const StringListStatic& stringList, char sep); - - bool Serialize(Serialization::IArchive& ar, Serialization::StringList& value, const char* name, const char* label); - bool Serialize(Serialization::IArchive& ar, Serialization::StringListValue& value, const char* name, const char* label); - bool Serialize(Serialization::IArchive& ar, Serialization::StringListStaticValue& value, const char* name, const char* label); -} - -#include "StringListImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_STRINGLIST_H diff --git a/Code/CryEngine/CryCommon/Serialization/StringListImpl.h b/Code/CryEngine/CryCommon/Serialization/StringListImpl.h deleted file mode 100644 index 4f7b573623..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/StringListImpl.h +++ /dev/null @@ -1,126 +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_SERIALIZATION_STRINGLISTIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_STRINGLISTIMPL_H -#pragma once - -#include "StringList.h" -#include "IArchive.h" -#include "DynArray.h" -#include "STL.h" - -namespace Serialization { - // --------------------------------------------------------------------------- - inline void splitStringList(StringList* result, const char* str, char delimeter) - { - result->clear(); - - const char* ptr = str; - for (; *ptr; ++ptr) - { - if (*ptr == delimeter) - { - result->push_back(string(str, ptr)); - str = ptr + 1; - } - } - result->push_back(string(str, ptr)); - } - - inline void joinStringList(string* result, const StringList& stringList, char sep) - { - YASLI_ESCAPE(result != 0, return ); - result->clear(); - for (StringList::const_iterator it = stringList.begin(); it != stringList.end(); ++it) - { - if (!result->empty()) - { - result += sep; - } - result->append(*it); - } - } - - inline void joinStringList(string* result, const StringListStatic& stringList, char sep) - { - YASLI_ESCAPE(result != 0, return ); - result->clear(); - for (StringListStatic::const_iterator it = stringList.begin(); it != stringList.end(); ++it) - { - if (!result->empty()) - { - (*result) += sep; - } - YASLI_ESCAPE(*it != 0, continue); - result->append(*it); - } - } - - inline bool Serialize(Serialization::IArchive& ar, Serialization::StringList& value, const char* name, const char* label) - { -#ifdef SERIALIZATION_STANDALONE - return ar(static_cast&>(value), name, label); -#else - return ar(static_cast&>(value), name, label); -#endif - } - - inline bool Serialize(Serialization::IArchive& ar, Serialization::StringListValue& value, const char* name, const char* label) - { - using Serialization::string; - if (ar.IsEdit()) - { - return ar(Serialization::SStruct(value), name, label); - } - else - { - string str; - if (ar.IsOutput()) - { - str = value.c_str(); - } - if (ar(str, name, label) && ar.IsInput()) - { - value = str.c_str(); - return true; - } - return false; - } - } - - inline bool Serialize(Serialization::IArchive& ar, Serialization::StringListStaticValue& value, const char* name, const char* label) - { - using Serialization::string; - if (ar.IsEdit()) - { - return ar(Serialization::SStruct(value), name, label); - } - else - { - string str; - if (ar.IsOutput()) - { - str = value.c_str(); - } - if (ar(str, name, label) && ar.IsInput()) - { - value = str.c_str(); - return true; - } - return true; - } - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_STRINGLISTIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Strings.h b/Code/CryEngine/CryCommon/Serialization/Strings.h deleted file mode 100644 index db8be9c3b8..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Strings.h +++ /dev/null @@ -1,32 +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_SERIALIZATION_STRINGS_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_STRINGS_H -#pragma once - -#ifdef SERIALIZATION_STANDALONE -#include -namespace Serialization { - using std::string; - using std::wstring; -} -#else -#include - -namespace Serialization { - typedef CryStringT string; - typedef CryStringT wstring; -} -#endif // SERIALIZATION_STANDALONE -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_STRINGS_H diff --git a/Code/CryEngine/CryCommon/Serialization/TypeID.h b/Code/CryEngine/CryCommon/Serialization/TypeID.h deleted file mode 100644 index 067813d9fc..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/TypeID.h +++ /dev/null @@ -1,290 +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_SERIALIZATION_TYPEID_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_TYPEID_H -#pragma once - - -#include "Serialization/Assert.h" -#include "Serialization/Strings.h" -#include - -namespace Serialization { - class IArchive; - struct TypeInfo; - class TypeID - { - public: - TypeID() - : typeInfo_(0) - , module_(0) {} - - TypeID(const TypeID& original) - : typeInfo_(original.typeInfo_) - , module_(original.module_) - { - } - - operator bool() const{ - return *this != TypeID(); - } - - template - static TypeID get(); - std::size_t sizeOf() const; - const char* name() const; - - bool operator==(const TypeID& rhs) const; - bool operator!=(const TypeID& rhs) const; - bool operator<(const TypeID& rhs) const; - private: - TypeInfo* typeInfo_; - void* module_; - friend struct TypeInfo; - friend class TypeDescription; - }; - - struct TypeInfo - { - TypeID id; - size_t size; - char name[128]; - - // We are trying to minimize type names here. Stripping namespaces, - // whitespaces and S/C/E/I prefixes. Why namespaces? Type names are usually - // used in two contexts: for unique name within factory context, where - // collision is unlikely, or for filtering in PropertyTree where concise - // name is much more useful. - static void cleanTypeName(char*& d, const char* dend, const char*& s, const char* send) - { - if (strncmp(s, "class ", 6) == 0) - { - s += 6; - } - else if (strncmp(s, "struct ", 7) == 0) - { - s += 7; - } - - while (*s == ' ' && s != send) - { - ++s; - } - - // strip C/S/I/E prefixes - if ((*s == 'C' || *s == 'S' || *s == 'I' || *s == 'E') && s[1] >= 'A' && s[1] <= 'Z') - { - ++s; - } - - if (s >= send) - { - return; - } - - char* startd = d; - while (d != dend && s != send) - { - while (*s == ' ' && s != send) - { - ++s; - } - if (s == send) - { - break; - } - if (*s == ':' && s[1] == ':') - { - // strip namespaces - s += 2; - d = startd; - - if ((*s == 'C' || *s == 'S' || *s == 'I' || *s == 'E') && s[1] >= 'A' && s[1] <= 'Z') - { - ++s; - } - } - if (s >= send) - { - break; - } - if (*s == '<') - { - * d = '<'; - ++d; - ++s; - cleanTypeName(d, dend, s, send); - } - else if (*s == '>') - { - * d = '\0'; - return; - } - * d = *s; - ++s; - ++d; - } - } - - template - static void extractTypeName(char (&name)[nameLen], const char* funcName) - { -#ifdef __clang__ - // "static yasli::TypeID yasli::TypeID::get() [T = ActualTypeName]" - const char* s = strstr(funcName, "[T = "); - if (s) - { - s += 5; - } - const char* send = strrchr(funcName, ']'); -#elif __GNUC__ >= 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4) - // "static yasli::TypeID yasli::TypeID::get() [with T = ActualTypeName]" - const char* s = strstr(funcName, "[with T = "); - if (s) - { - s += 9; - } - const char* send = strrchr(funcName, ']'); -#else - // "static yasli::TypeID yasli::TypeID::get()" - const char* s = strchr(funcName, '<'); - const char* send = strrchr(funcName, '>'); - YASLI_ASSERT(s != 0 && send != 0); - if (s != send) - { - ++s; - } -#endif - YASLI_ASSERT(s != 0 && send != 0); - - char* d = name; - const char* dend = name + sizeof(name) - 1; - cleanTypeName(d, dend, s, send); - * d = '\0'; - - // This assertion is not critical, but may result in collision as - // stripped name wil be used, e.g. for lookup in factory. - YASLI_ASSERT(s == send && "Type name does not fit into the buffer"); - } - - TypeInfo(size_t _size, const char* templatedFunctionName) - : size(_size) - { - extractTypeName(name, templatedFunctionName); - id.typeInfo_ = this; - static int moduleSpecificSymbol; - id.module_ = &moduleSpecificSymbol; - } - - bool operator==(const TypeInfo& rhs) const - { - return size == rhs.size && strcmp(name, rhs.name) == 0; - } - - bool operator<(const TypeInfo& rhs) const - { - if (size == rhs.size) - { - return strcmp(name, rhs.name) < 0; - } - else - { - return size < rhs.size; - } - } - }; - - template - TypeID TypeID::get() - { -#ifdef _MSC_VER - static TypeInfo typeInfo(sizeof(T), __FUNCSIG__); -#else - static TypeInfo typeInfo(sizeof(T), __PRETTY_FUNCTION__); -#endif - return typeInfo.id; - } - - inline const char* TypeID::name() const - { - if (typeInfo_) - { - return typeInfo_->name; - } - else - { - return ""; - } - } - - inline size_t TypeID::sizeOf() const - { - if (typeInfo_) - { - return typeInfo_->size; - } - else - { - return 0; - } - } - - inline bool TypeID::operator==(const TypeID& rhs) const - { - if (typeInfo_ == rhs.typeInfo_) - { - return true; - } - else if (!typeInfo_ || !rhs.typeInfo_) - { - return false; - } - else if (module_ == rhs.module_) - { - return false; - } - else - { - return *typeInfo_ == *rhs.typeInfo_; - } - } - - inline bool TypeID::operator!=(const TypeID& rhs) const - { - return !operator==(rhs); - } - - inline bool TypeID::operator<(const TypeID& rhs) const - { - if (!typeInfo_) - { - return rhs.typeInfo_ != 0; - } - else if (!rhs.typeInfo_) - { - return false; - } - else - { - return *typeInfo_ < *rhs.typeInfo_; - } - } - - template - T* createDerivedClass(TypeID typeID); -} - -//bool Serialize(Serialization::IArchive& ar, Serialization::TypeID& typeID, const char* name, const char* label); - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_TYPEID_H diff --git a/Code/CryEngine/CryCommon/Serialization/TypeInfo.h b/Code/CryEngine/CryCommon/Serialization/TypeInfo.h deleted file mode 100644 index eafd959d51..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/TypeInfo.h +++ /dev/null @@ -1,46 +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_SERIALIZATION_TYPEINFO_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_TYPEINFO_H -#pragma once - - -namespace Serialization { - class IArchive; -} - -struct STypeInfoInstance -{ - template - STypeInfoInstance(T& obj) - : m_pTypeInfo(&TypeInfo(&obj)) - , m_pObject(&obj) - { - } - - STypeInfoInstance(const CTypeInfo* typeInfo, void* object) - : m_pTypeInfo(typeInfo) - , m_pObject(object) - { - } - - inline void Serialize(Serialization::IArchive& ar); - - const CTypeInfo* m_pTypeInfo; - void* m_pObject; - std::set m_persistentStrings; -}; - -#include "TypeInfoImpl.h" -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_TYPEINFO_H diff --git a/Code/CryEngine/CryCommon/Serialization/TypeInfoImpl.h b/Code/CryEngine/CryCommon/Serialization/TypeInfoImpl.h deleted file mode 100644 index 7f94e8bec7..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/TypeInfoImpl.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. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_TYPEINFOIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_TYPEINFOIMPL_H -#pragma once - - - -#include "CryTypeInfo.h" -#include "Serialization/Decorators/Range.h" -#include "Serialization/Enum.h" -#include "ISplines.h" -#include -#include "Serialization/Color.h" -#include "Cry_Color.h" -#include "Decorators/Resources.h" - -struct SPrivateTypeInfoInstanceLevel -{ - SPrivateTypeInfoInstanceLevel(const CTypeInfo* typeInfo, void* object, STypeInfoInstance* instance) - : m_pTypeInfo(typeInfo) - , m_pObject(object) - , m_instance(instance) - { - } - - void Serialize(Serialization::IArchive& ar) - { - for AllSubVars(pVar, *m_pTypeInfo) - { - string group; - if (pVar->GetAttr("Group", group)) - { - if (!m_sCurrentGroup.empty()) - { - ar.CloseBlock(); - } - const char* name = m_instance->m_persistentStrings.insert(group).first->c_str(); - ar.OpenBlock(name, name); - m_sCurrentGroup = name; - } - else - { - const char* name = pVar->GetName(); - if (!*name) - { - name = pVar->Type.Name; - } - - const char* label = pVar->GetName(); - if (!*label) - { - string n = "^"; - n += pVar->GetName(); - label = m_instance->m_persistentStrings.insert(n).first->c_str(); - } - - SerializeVariable(pVar, m_pObject, ar, name, label); - } - } - - if (!m_sCurrentGroup.empty()) - { - ar.CloseBlock(); - m_sCurrentGroup.clear(); - } - } - - template - void SerializeT(const CTypeInfo::CVarInfo* pVar, void* pParentAddress, Serialization::IArchive& ar, const char* name, const char* label) - { - T value; - const CTypeInfo& type = pVar->Type; - type.ToValue(pVar->GetAddress(pParentAddress), value); - ar(value, name, label); - if (ar.IsInput()) - { - type.FromValue(pVar->GetAddress(pParentAddress), value); - } - } - - template - void SerializeNumericalT(const CTypeInfo::CVarInfo* pVar, void* pParentAddress, Serialization::IArchive& ar, const char* name, const char* label) - { - T value; - const CTypeInfo& type = pVar->Type; - type.ToValue(pVar->GetAddress(pParentAddress), value); - - float limMin, limMax; - if (pVar->GetLimit(eLimit_Min, limMin) && pVar->GetLimit(eLimit_Max, limMax)) - { - ar(Serialization::Range(value, limMin, limMax), name, label); - } - else - { - ar(value, name, label); - } - if (ar.IsInput()) - { - type.FromValue(pVar->GetAddress(pParentAddress), value); - } - } - - void SerializeVariable(const CTypeInfo::CVarInfo* pVar, void* pParentAddress, Serialization::IArchive& ar, const char* name, const char* label) - { - const CTypeInfo& type = pVar->Type; - - if (type.HasSubVars()) - { - if (strcmp(name, "Color") == 0) - { - Color3F value; - const CTypeInfo& type = pVar->Type; - type.ToValue(pVar->GetAddress(pParentAddress), value); - ColorF colour = value; - ar(colour, name, label); - if (ar.IsInput()) - { - value = Color3F(colour.r, colour.g, colour.b); - type.FromValue(pVar->GetAddress(pParentAddress), value); - } - } - else - { - // load params of sub-variables (variable is a struct or vector) - SPrivateTypeInfoInstanceLevel instance(&type, pVar->GetAddress(pParentAddress), m_instance); - ar(instance, name, label); - } - } - else - { - if (type.IsType()) - { - SerializeT(pVar, pParentAddress, ar, name, label); - } - else if (type.IsType()) - { - SerializeNumericalT(pVar, pParentAddress, ar, name, label); - } - else if (type.IsType()) - { - SerializeNumericalT(pVar, pParentAddress, ar, name, label); - } - else if (type.IsType()) - { - SerializeNumericalT(pVar, pParentAddress, ar, name, label); - } - else if (type.IsType()) - { - SerializeNumericalT(pVar, pParentAddress, ar, name, label); - } - else if (type.IsType()) - { - SerializeNumericalT(pVar, pParentAddress, ar, name, label); - } - else if (type.EnumElem(0)) - { - Serialization::StringList stringList; - const char* enumType = type.EnumElem(0); - for (int i = 1; enumType; ++i) - { - stringList.push_back(enumType); - enumType = type.EnumElem(i); - } - - string enumValue = pVar->ToString(pParentAddress); - int index = std::max(stringList.find(enumValue.c_str()), 0); - - Serialization::StringListValue stringListValue(stringList, index); - ar(stringListValue, name, label); - if (ar.IsInput()) - { - pVar->FromString(pParentAddress, stringListValue.c_str()); - } - } - else - { - ISplineInterpolator* pSpline = 0; - if (type.ToValue(pVar->GetAddress(pParentAddress), pSpline)) - { - // TODO: Curve field - } - else - { - string value; - value = pVar->ToString(pParentAddress); - - if (strcmp(name, "Texture") == 0) - { - // TODO: Texture field - } - else if (strcmp(name, "Material") == 0) - { - // TODO: Material field - } - else if (strcmp(name, "Geometry") == 0) - { - ar(Serialization::ModelFilename(value), name, label); - } - else if (strcmp(name, "Sound") == 0) - { - ar(Serialization::SoundName(value), name, label); - } - else if (strcmp(name, "GeomCache") == 0) - { - // TODO: Geom cache field - } - else - { - ar(value, name, label); - } - if (ar.IsInput()) - { - pVar->FromString(pParentAddress, value.c_str()); - } - } - } - } - } - -private: - const CTypeInfo* m_pTypeInfo; - void* m_pObject; - string m_sCurrentGroup; - STypeInfoInstance* m_instance; -}; - -//------------------------------ -inline void STypeInfoInstance::Serialize(Serialization::IArchive& ar) -{ - SPrivateTypeInfoInstanceLevel instance(m_pTypeInfo, m_pObject, this); - instance.Serialize(ar); -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_TYPEINFOIMPL_H diff --git a/Code/CryEngine/CryCommon/crycommon_files.cmake b/Code/CryEngine/CryCommon/crycommon_files.cmake index 3b63dab649..ca95802fd9 100644 --- a/Code/CryEngine/CryCommon/crycommon_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_files.cmake @@ -20,7 +20,6 @@ set(FILES ICmdLine.h IColorGradingController.h IConsole.h - IEngineModule.h IEntityRenderState.h IEntityRenderState_info.cpp IFlares.h @@ -52,7 +51,6 @@ set(FILES IPostEffectGroup.h IProcess.h IReadWriteXMLSink.h - IRemoteCommand.h IRenderAuxGeom.h IRenderer.h IRenderMesh.h @@ -60,7 +58,6 @@ set(FILES IResourceCompilerHelper.h IResourceManager.h ISerialize.h - IServiceNetwork.h IShader.h IShader_info.h ISoftCodeMgr.h @@ -120,7 +117,6 @@ set(FILES MemoryAccess.h Algorithm.h AnimKey.h - AnimTime.h BitFiddling.h CGFContent.h CGFContent_info.cpp @@ -155,7 +151,6 @@ set(FILES CryVersion.h CryZlib.h FrameProfiler.h - GeomCacheFileFormat.h HashGrid.h HeapAllocator.h HeapContainer.h @@ -207,7 +202,6 @@ set(FILES VectorSet.h VertexFormats.h XMLBinaryHeaders.h - Bezier.h RenderBus.h MainThreadRenderRequestBus.h OceanConstants.h @@ -265,101 +259,7 @@ set(FILES platform_impl.cpp Win32specific.h Win64specific.h - CryExtension/CryCreateClassInstance.h - CryExtension/CryGUID.h - CryExtension/CryTypeID.h - CryExtension/ICryFactory.h - CryExtension/ICryFactoryRegistry.h - CryExtension/ICryUnknown.h - CryExtension/Impl/Conversion.h - CryExtension/Impl/ClassWeaver.h - CryExtension/Impl/CryGUIDHelper.h - CryExtension/Impl/ICryFactoryRegistryImpl.h - CryExtension/Impl/RegFactoryNode.h - CryExtension/Impl/TypeList.h - CryPool/Allocator.h - CryPool/Container.h - CryPool/Defrag.h - CryPool/example.h - CryPool/Fallback.h - CryPool/Inspector.h - CryPool/List.h - CryPool/Memory.h - CryPool/PoolAlloc.h - CryPool/STLWrapper.h - CryPool/ThreadSafe.h stl/STLAlignedAlloc.h - Serialization/Assert.h - Serialization/BitVector.h - Serialization/BitVectorImpl.h - Serialization/BlackBox.h - Serialization/BoostSharedPtr.h - Serialization/Callback.h - Serialization/ClassFactory.h - Serialization/ClassFactoryImpl.h - Serialization/Color.h - Serialization/ColorImpl.h - Serialization/CRCRef.h - Serialization/CRCRefImpl.h - Serialization/CryExtension.h - Serialization/CryExtensionImpl.h - Serialization/CryName.h - Serialization/CryNameImpl.h - Serialization/CryStrings.h - Serialization/CryStringsImpl.h - Serialization/DynArray.h - Serialization/DynArrayImpl.h - Serialization/Enum.h - Serialization/EnumImpl.h - Serialization/IArchive.h - Serialization/IArchiveHost.h - Serialization/IClassFactory.h - Serialization/IntrusiveFactory.h - Serialization/ITextInputArchive.h - Serialization/ITextOutputArchive.h - Serialization/KeyValue.h - Serialization/Math.h - Serialization/MathImpl.h - Serialization/NetScriptSerialize.h - Serialization/Object.h - Serialization/Serializer.h - Serialization/SerializerImpl.h - Serialization/SmartPtr.h - Serialization/SmartPtrImpl.h - Serialization/STL.h - Serialization/STLImpl.h - Serialization/StringList.h - Serialization/StringListImpl.h - Serialization/Strings.h - Serialization/TypeID.h - Serialization/TypeInfo.h - Serialization/TypeInfoImpl.h - Serialization/Decorators/ActionButton.h - Serialization/Decorators/BitFlags.h - Serialization/Decorators/BitFlagsImpl.h - Serialization/Decorators/ColorPicker.h - Serialization/Decorators/ColorPickerImpl.h - Serialization/Decorators/JointName.h - Serialization/Decorators/JointNameImpl.h - Serialization/Decorators/LocalFrame.h - Serialization/Decorators/LocalFrameImpl.h - Serialization/Decorators/OutputFilePath.h - Serialization/Decorators/OutputFilePathImpl.h - Serialization/Decorators/Range.h - Serialization/Decorators/RangeImpl.h - Serialization/Decorators/ResourceFilePath.h - Serialization/Decorators/ResourceFilePathImpl.h - Serialization/Decorators/ResourceFolderPath.h - Serialization/Decorators/ResourceFolderPathImpl.h - Serialization/Decorators/Resources.h - Serialization/Decorators/ResourcesAudio.h - Serialization/Decorators/ResourceSelector.h - Serialization/Decorators/Slider.h - Serialization/Decorators/SliderImpl.h - Serialization/Decorators/Sprite.h - Serialization/Decorators/SpriteImpl.h - Serialization/Decorators/TagList.h - Serialization/Decorators/TagListImpl.h LyShine/IDraw2d.h LyShine/ILyShine.h LyShine/ISprite.h diff --git a/Code/CryEngine/CryCommon/platform_impl.cpp b/Code/CryEngine/CryCommon/platform_impl.cpp index 6c261bb1f1..142f07e5e7 100644 --- a/Code/CryEngine/CryCommon/platform_impl.cpp +++ b/Code/CryEngine/CryCommon/platform_impl.cpp @@ -14,8 +14,7 @@ #include #include #include -#include -#include +#include #include #include @@ -42,9 +41,6 @@ SC_API struct SSystemGlobalEnvironment* gEnv = nullptr; #include AZ_RESTRICTED_FILE(platform_impl_h) #endif -//The reg factory is used for registering the different modules along the whole project -struct SRegFactoryNode* g_pHeadToRegFactories = 0; - ////////////////////////////////////////////////////////////////////////// // If not in static library. #include @@ -106,16 +102,6 @@ extern "C" AZ_DLL_EXPORT void ModuleInitISystem(ISystem* pSystem, [[maybe_unused AZ::AllocatorManager::Instance(); // Force the AllocatorManager to instantiate and register any allocators defined in data sections } AZ::Debug::ProfileModuleInit(); - -#if !defined(AZ_MONOLITHIC_BUILD) - ICryFactoryRegistryImpl* pCryFactoryImpl = static_cast(pSystem->GetCryFactoryRegistry()); - if (pCryFactoryImpl) - { - pCryFactoryImpl->RegisterFactories(g_pHeadToRegFactories); - } - - AZ_Error("System", pCryFactoryImpl, "Failed to successfully load factory for %s. You may have a missing or stale DLL that needs to be recompiled.", moduleName); -#endif } // if pSystem } diff --git a/Code/CryEngine/CrySystem/DllMain.cpp b/Code/CryEngine/CrySystem/DllMain.cpp index aba39fb9fb..6173ebc0c6 100644 --- a/Code/CryEngine/CrySystem/DllMain.cpp +++ b/Code/CryEngine/CrySystem/DllMain.cpp @@ -15,10 +15,6 @@ #include "System.h" #include #include "DebugCallStack.h" -#if defined(AZ_MONOLITHIC_BUILD) -#include -#include -#endif #if defined(AZ_RESTRICTED_PLATFORM) #undef AZ_RESTRICTED_SECTION @@ -132,10 +128,7 @@ CRYSYSTEM_API ISystem* CreateSystemInterface(const SSystemInitParams& startupPar #define AZ_RESTRICTED_SECTION DLLMAIN_CPP_SECTION_2 #include AZ_RESTRICTED_FILE(DllMain_cpp) #endif -#if defined(AZ_MONOLITHIC_BUILD) - ICryFactoryRegistryImpl* pCryFactoryImpl = static_cast(pSystem->GetCryFactoryRegistry()); - pCryFactoryImpl->RegisterFactories(g_pHeadToRegFactories); -#endif // AZ_MONOLITHIC_BUILD + // the earliest point the system exists - w2e tell the callback if (startupParams.pUserCallback) { diff --git a/Code/CryEngine/CrySystem/ExtensionSystem/CryFactoryRegistryImpl.cpp b/Code/CryEngine/CrySystem/ExtensionSystem/CryFactoryRegistryImpl.cpp deleted file mode 100644 index 26c13a070d..0000000000 --- a/Code/CryEngine/CrySystem/ExtensionSystem/CryFactoryRegistryImpl.cpp +++ /dev/null @@ -1,359 +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 : Part of CryEngine's extension framework. - - -#include "CrySystem_precompiled.h" -#include "CryFactoryRegistryImpl.h" -#include "../System.h" - -#include -#include -#include - -#include - - -CCryFactoryRegistryImpl::CCryFactoryRegistryImpl() - : m_guard() - , m_byCName() - , m_byCID() - , m_byIID() - , m_callbacks() -{ -} - - -CCryFactoryRegistryImpl::~CCryFactoryRegistryImpl() -{ -} - - -CCryFactoryRegistryImpl& CCryFactoryRegistryImpl::Access() -{ - static StaticInstance> s_registry; - return s_registry; -} - - -ICryFactory* CCryFactoryRegistryImpl::GetFactory(const char* cname) const -{ - AUTO_READLOCK(m_guard); - - if (!cname) - { - return 0; - } - - const FactoryByCName search(cname); - FactoriesByCNameConstIt it = std::lower_bound(m_byCName.begin(), m_byCName.end(), search); - return it != m_byCName.end() && !(search < *it) ? (*it).m_ptr : 0; -} - - -ICryFactory* CCryFactoryRegistryImpl::GetFactory(const CryClassID& cid) const -{ - AUTO_READLOCK(m_guard); - - const FactoryByCID search(cid); - FactoriesByCIDConstIt it = std::lower_bound(m_byCID.begin(), m_byCID.end(), search); - return it != m_byCID.end() && !(search < *it) ? (*it).m_ptr : 0; -} - - -void CCryFactoryRegistryImpl::IterateFactories(const CryInterfaceID& iid, ICryFactory** pFactories, size_t& numFactories) const -{ - AUTO_READLOCK(m_guard); - - typedef std::pair SearchResult; - SearchResult res = std::equal_range(m_byIID.begin(), m_byIID.end(), FactoryByIID(iid, 0), LessPredFactoryByIIDOnly()); - - const size_t numFactoriesFound = std::distance(res.first, res.second); - if (pFactories) - { - numFactories = min(numFactories, numFactoriesFound); - FactoriesByIIDConstIt it = res.first; - for (size_t i = 0; i < numFactories; ++i, ++it) - { - pFactories[i] = (*it).m_ptr; - } - } - else - { - numFactories = numFactoriesFound; - } -} - - -void CCryFactoryRegistryImpl::RegisterCallback(ICryFactoryRegistryCallback* pCallback) -{ - if (!pCallback) - { - return; - } - - { - AUTO_MODIFYLOCK(m_guard); - - Callbacks::iterator it = std::lower_bound(m_callbacks.begin(), m_callbacks.end(), pCallback); - if (it == m_callbacks.end() || pCallback < *it) - { - m_callbacks.insert(it, pCallback); - } - else - { - assert(0 && "CCryFactoryRegistryImpl::RegisterCallback() -- pCallback already registered!"); - } - } - { - AUTO_READLOCK(m_guard); - - typedef std::pair SearchResult; - SearchResult res = std::equal_range(m_byIID.begin(), m_byIID.end(), FactoryByIID(cryiidof(), 0), LessPredFactoryByIIDOnly()); - - for (; res.first != res.second; ++res.first) - { - pCallback->OnNotifyFactoryRegistered((*res.first).m_ptr); - } - } -} - - -void CCryFactoryRegistryImpl::UnregisterCallback(ICryFactoryRegistryCallback* pCallback) -{ - if (!pCallback) - { - return; - } - - AUTO_MODIFYLOCK(m_guard); - - Callbacks::iterator it = std::lower_bound(m_callbacks.begin(), m_callbacks.end(), pCallback); - if (it != m_callbacks.end() && !(pCallback < *it)) - { - m_callbacks.erase(it); - } -} - - -bool CCryFactoryRegistryImpl::GetInsertionPos(ICryFactory* pFactory, FactoriesByCNameIt& itPosForCName, FactoriesByCIDIt& itPosForCID) -{ - assert(pFactory); - - struct FatalError - { - static void Report(ICryFactory* pKnownFactory, ICryFactory* pNewFactory) - { - char err[1024]; - sprintf_s(err, sizeof(err), "Conflicting factories...\n" - "Factory (0x%p): ClassID = %s, ClassName = \"%s\"\n" - "Factory (0x%p): ClassID = %s, ClassName = \"%s\"", - pKnownFactory, pKnownFactory ? CryGUIDHelper::Print(pKnownFactory->GetClassID()).c_str() : "$unknown$", pKnownFactory ? pKnownFactory->GetName() : "$unknown$", - pNewFactory, pNewFactory ? CryGUIDHelper::Print(pNewFactory->GetClassID()).c_str() : "$unknown$", pNewFactory ? pNewFactory->GetName() : "$unknown$"); - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_FACTORY_REGISTRY_USE_PRINTF_FOR_FATAL - printf("\n!!! Fatal error !!!\n"); - printf(err); - printf("\n"); -#elif defined(WIN32) || defined(WIN64) - OutputDebugStringA("\n!!! Fatal error !!!\n"); - OutputDebugStringA(err); - OutputDebugStringA("\n"); - MessageBoxA(0, err, "!!! Fatal error !!!", MB_OK | MB_ICONERROR); -#endif - - assert(0); - exit(0); - } - }; - - FactoryByCName searchByCName(pFactory); - FactoriesByCNameIt itForCName = std::lower_bound(m_byCName.begin(), m_byCName.end(), searchByCName); - if (itForCName != m_byCName.end()) - { - // If the addresses match, then this factory is already registered. It's not really worth error-ing about, - // as double registration will not cause any harm. - if (itForCName->m_ptr == pFactory) - { - return false; - } - - if (!(searchByCName < *itForCName)) - { - FatalError::Report((*itForCName).m_ptr, pFactory); - } - } - - FactoryByCID searchByCID(pFactory); - FactoriesByCIDIt itForCID = std::lower_bound(m_byCID.begin(), m_byCID.end(), searchByCID); - if (itForCID != m_byCID.end() && !(searchByCID < *itForCID)) - { - FatalError::Report((*itForCID).m_ptr, pFactory); - } - - itPosForCName = itForCName; - itPosForCID = itForCID; - - return true; -} - - -void CCryFactoryRegistryImpl::RegisterFactories(const SRegFactoryNode* pFactories) -{ - size_t numFactoriesToAdd = 0; - size_t numInterfacesSupported = 0; - { - const SRegFactoryNode* p = pFactories; - while (p) - { - ICryFactory* pFactory = p->m_pFactory; - assert(pFactory); - if (pFactory) - { - const CryInterfaceID* pIIDs = 0; - size_t numIIDs = 0; - pFactory->ClassSupports(pIIDs, numIIDs); - - numInterfacesSupported += numIIDs; - ++numFactoriesToAdd; - } - - p = p->m_pNext; - } - } - - { - AUTO_MODIFYLOCK(m_guard); - - m_byCName.reserve(m_byCName.size() + numFactoriesToAdd); - m_byCID.reserve(m_byCID.size() + numFactoriesToAdd); - m_byIID.reserve(m_byIID.size() + numInterfacesSupported); - - size_t numFactoriesAdded = 0; - const SRegFactoryNode* p = pFactories; - while (p) - { - ICryFactory* pFactory = p->m_pFactory; - if (pFactory) - { - FactoriesByCNameIt itPosForCName; - FactoriesByCIDIt itPosForCID; - if (GetInsertionPos(pFactory, itPosForCName, itPosForCID)) - { - m_byCName.insert(itPosForCName, FactoryByCName(pFactory)); - m_byCID.insert(itPosForCID, FactoryByCID(pFactory)); - - const CryInterfaceID* pIIDs = 0; - size_t numIIDs = 0; - pFactory->ClassSupports(pIIDs, numIIDs); - - for (size_t i = 0; i < numIIDs; ++i) - { - const FactoryByIID newFactory(pIIDs[i], pFactory); - m_byIID.push_back(newFactory); - } - - for (size_t i = 0, s = m_callbacks.size(); i < s; ++i) - { - m_callbacks[i]->OnNotifyFactoryRegistered(pFactory); - } - - ++numFactoriesAdded; - } - } - - p = p->m_pNext; - } - - if (numFactoriesAdded) - { - std::sort(m_byIID.begin(), m_byIID.end()); - } - } -} - - -void CCryFactoryRegistryImpl::UnregisterFactories(const SRegFactoryNode* pFactories) -{ - AUTO_MODIFYLOCK(m_guard); - - const SRegFactoryNode* p = pFactories; - while (p) - { - ICryFactory* pFactory = p->m_pFactory; - UnregisterFactoryInternal(pFactory); - p = p->m_pNext; - } -} - - -void CCryFactoryRegistryImpl::UnregisterFactory(ICryFactory* const pFactory) -{ - AUTO_MODIFYLOCK(m_guard); - - UnregisterFactoryInternal(pFactory); -} - - -void CCryFactoryRegistryImpl::UnregisterFactoryInternal(ICryFactory* const pFactory) -{ - if (pFactory) - { - FactoryByCName searchByCName(pFactory); - FactoriesByCNameIt itForCName = std::lower_bound(m_byCName.begin(), m_byCName.end(), searchByCName); - if (itForCName != m_byCName.end() && !(searchByCName < *itForCName)) - { - assert((*itForCName).m_ptr == pFactory); - if ((*itForCName).m_ptr == pFactory) - { - m_byCName.erase(itForCName); - } - } - - FactoryByCID searchByCID(pFactory); - FactoriesByCIDIt itForCID = std::lower_bound(m_byCID.begin(), m_byCID.end(), searchByCID); - if (itForCID != m_byCID.end() && !(searchByCID < *itForCID)) - { - assert((*itForCID).m_ptr == pFactory); - if ((*itForCID).m_ptr == pFactory) - { - m_byCID.erase(itForCID); - } - } - - const CryInterfaceID* pIIDs = 0; - size_t numIIDs = 0; - pFactory->ClassSupports(pIIDs, numIIDs); - - for (size_t i = 0; i < numIIDs; ++i) - { - FactoryByIID searchByIID(pIIDs[i], pFactory); - FactoriesByIIDIt itForIID = std::lower_bound(m_byIID.begin(), m_byIID.end(), searchByIID); - if (itForIID != m_byIID.end() && !(searchByIID < *itForIID)) - { - m_byIID.erase(itForIID); - } - } - - for (size_t i = 0, s = m_callbacks.size(); i < s; ++i) - { - m_callbacks[i]->OnNotifyFactoryUnregistered(pFactory); - } - } -} - -ICryFactoryRegistry* CSystem::GetCryFactoryRegistry() const -{ - return &CCryFactoryRegistryImpl::Access(); -} diff --git a/Code/CryEngine/CrySystem/ExtensionSystem/CryFactoryRegistryImpl.h b/Code/CryEngine/CrySystem/ExtensionSystem/CryFactoryRegistryImpl.h deleted file mode 100644 index a75ddf782f..0000000000 --- a/Code/CryEngine/CrySystem/ExtensionSystem/CryFactoryRegistryImpl.h +++ /dev/null @@ -1,128 +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 : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYSYSTEM_EXTENSIONSYSTEM_CRYFACTORYREGISTRYIMPL_H -#define CRYINCLUDE_CRYSYSTEM_EXTENSIONSYSTEM_CRYFACTORYREGISTRYIMPL_H -#pragma once - - - -#include -#include - -#include - - -class CCryFactoryRegistryImpl - : public ICryFactoryRegistryImpl -{ -public: - virtual ICryFactory* GetFactory(const char* cname) const; - virtual ICryFactory* GetFactory(const CryClassID& cid) const; - virtual void IterateFactories(const CryInterfaceID& iid, ICryFactory** pFactories, size_t& numFactories) const; - - virtual void RegisterCallback(ICryFactoryRegistryCallback* pCallback); - virtual void UnregisterCallback(ICryFactoryRegistryCallback* pCallback); - - virtual void RegisterFactories(const SRegFactoryNode* pFactories); - virtual void UnregisterFactories(const SRegFactoryNode* pFactories); - - virtual void UnregisterFactory(ICryFactory* const pFactory); - -public: - static CCryFactoryRegistryImpl& Access(); - CCryFactoryRegistryImpl(); - ~CCryFactoryRegistryImpl(); - -private: - struct FactoryByCName - { - const char* m_cname; - ICryFactory* m_ptr; - - FactoryByCName(const char* cname) - : m_cname(cname) - , m_ptr(0) {assert(m_cname); } - FactoryByCName(ICryFactory* ptr) - : m_cname(ptr ? ptr->GetName() : 0) - , m_ptr(ptr) {assert(m_cname && m_ptr); } - bool operator <(const FactoryByCName& rhs) const {return strcmp(m_cname, rhs.m_cname) < 0; } - }; - typedef std::vector FactoriesByCName; - typedef FactoriesByCName::iterator FactoriesByCNameIt; - typedef FactoriesByCName::const_iterator FactoriesByCNameConstIt; - - struct FactoryByCID - { - CryClassID m_cid; - ICryFactory* m_ptr; - - FactoryByCID(const CryClassID& cid) - : m_cid(cid) - , m_ptr(0) {} - FactoryByCID(ICryFactory* ptr) - : m_cid(ptr ? ptr->GetClassID() : MAKE_CRYGUID(0, 0)) - , m_ptr(ptr) {assert(m_ptr); } - bool operator <(const FactoryByCID& rhs) const {return m_cid < rhs.m_cid; } - }; - typedef std::vector FactoriesByCID; - typedef FactoriesByCID::iterator FactoriesByCIDIt; - typedef FactoriesByCID::const_iterator FactoriesByCIDConstIt; - - struct FactoryByIID - { - CryInterfaceID m_iid; - ICryFactory* m_ptr; - - FactoryByIID(CryInterfaceID iid, ICryFactory* pFactory) - : m_iid(iid) - , m_ptr(pFactory) {} - bool operator <(const FactoryByIID& rhs) const - { - if (m_iid != rhs.m_iid) - { - return m_iid < rhs.m_iid; - } - return m_ptr < rhs.m_ptr; - } - }; - typedef std::vector FactoriesByIID; - typedef FactoriesByIID::iterator FactoriesByIIDIt; - typedef FactoriesByIID::const_iterator FactoriesByIIDConstIt; - struct LessPredFactoryByIIDOnly - { - bool operator ()(const FactoryByIID& lhs, const FactoryByIID& rhs) const {return lhs.m_iid < rhs.m_iid; } - }; - - typedef std::vector Callbacks; - typedef Callbacks::iterator CallbacksIt; - typedef Callbacks::const_iterator CallbacksConstIt; - -private: - bool GetInsertionPos(ICryFactory* pFactory, FactoriesByCNameIt& itPosForCName, FactoriesByCIDIt& itPosForCID); - void UnregisterFactoryInternal(ICryFactory* const pFactory); - -private: - mutable CryReadModifyLock m_guard; - - FactoriesByCName m_byCName; - FactoriesByCID m_byCID; - FactoriesByIID m_byIID; - - Callbacks m_callbacks; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_EXTENSIONSYSTEM_CRYFACTORYREGISTRYIMPL_H diff --git a/Code/CryEngine/CrySystem/ExtensionSystem/TestCases/TestExtensions.cpp b/Code/CryEngine/CrySystem/ExtensionSystem/TestCases/TestExtensions.cpp deleted file mode 100644 index f87643d4f0..0000000000 --- a/Code/CryEngine/CrySystem/ExtensionSystem/TestCases/TestExtensions.cpp +++ /dev/null @@ -1,955 +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 : Part of CryEngine's extension framework. - - -#include "CrySystem_precompiled.h" -#include "TestExtensions.h" - -#ifdef EXTENSION_SYSTEM_INCLUDE_TESTCASES - -#include -#include -#include - - -////////////////////////////////////////////////////////////////////////// - - -namespace TestComposition -{ - struct ITestExt1 - : public ICryUnknown - { - CRYINTERFACE_DECLARE(ITestExt1, 0x9d9e0dcfa5764cb0, 0xa73701595f75bd32) - - virtual void Call1() const = 0; - }; - - DECLARE_SMART_POINTERS(ITestExt1); - - - class CTestExt1 - : public ITestExt1 - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(ITestExt1) - CRYINTERFACE_END() - - CRYGENERATE_CLASS(CTestExt1, "TestExt1", 0x43b04e7cc1be45ca, 0x9df6ccb1c0dc1ad8) - - public: - virtual void Call1() const; - - private: - int i; - }; - - CRYREGISTER_CLASS(CTestExt1) - - CTestExt1::CTestExt1() - { - i = 1; - } - - CTestExt1::~CTestExt1() - { - printf("Inside CTestExt1 dtor\n"); - } - - void CTestExt1::Call1() const - { - printf("Inside CTestExt1::Call1()\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - struct ITestExt2 - : public ICryUnknown - { - CRYINTERFACE_DECLARE(ITestExt2, 0x8eb7a4b399874b9c, 0xb96bd6da7a8c72f9) - - virtual void Call2() = 0; - }; - - DECLARE_SMART_POINTERS(ITestExt2); - - - class CTestExt2 - : public ITestExt2 - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(ITestExt2) - CRYINTERFACE_END() - - CRYGENERATE_CLASS(CTestExt2, "TestExt2", 0x25b3ebf8f1754b9a, 0xb5494e3da7cdd80f) - - public: - virtual void Call2(); - - private: - int i; - }; - - CRYREGISTER_CLASS(CTestExt2) - - CTestExt2::CTestExt2() - { - i = 2; - } - - CTestExt2::~CTestExt2() - { - printf("Inside CTestExt2 dtor\n"); - } - - void CTestExt2::Call2() - { - printf("Inside CTestExt2::Call2()\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - class CComposed - : public ICryUnknown - { - CRYGENERATE_CLASS(CComposed, "Composed", 0x0439d74b8dcd4b7f, 0x9287dcdf7e26a3a5) - - CRYCOMPOSITE_BEGIN() - CRYCOMPOSITE_ADD(m_pTestExt1, "Ext1") - CRYCOMPOSITE_ADD(m_pTestExt2, "Ext2") - CRYCOMPOSITE_END(CComposed) - - CRYINTERFACE_BEGIN() - CRYINTERFACE_END() - - private: - ITestExt1Ptr m_pTestExt1; - ITestExt2Ptr m_pTestExt2; - }; - - CRYREGISTER_CLASS(CComposed) - - CComposed::CComposed() - : m_pTestExt1() - , m_pTestExt2() - { - CryCreateClassInstance("TestExt1", m_pTestExt1); - CryCreateClassInstance("TestExt2", m_pTestExt2); - } - - CComposed::~CComposed() - { - } - - ////////////////////////////////////////////////////////////////////////// - - struct ITestExt3 - : public ICryUnknown - { - CRYINTERFACE_DECLARE(ITestExt3, 0xdd017935a2134898, 0xbd2fffa145551876) - - virtual void Call3() = 0; - }; - - DECLARE_SMART_POINTERS(ITestExt3); - - class CTestExt3 - : public ITestExt3 - { - CRYGENERATE_CLASS(CTestExt3, "TestExt3", 0xeceab40bc4bb4988, 0xa9f63c1db85a69b1) - - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(ITestExt3) - CRYINTERFACE_END() - - public: - virtual void Call3(); - - private: - int i; - }; - - CRYREGISTER_CLASS(CTestExt3) - - CTestExt3::CTestExt3() - { - i = 3; - } - - CTestExt3::~CTestExt3() - { - printf("Inside CTestExt3 dtor\n"); - } - - void CTestExt3::Call3() - { - printf("Inside CTestExt3::Call3()\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - class CComposed2 - : public ICryUnknown - { - CRYGENERATE_CLASS(CComposed2, "Composed2", 0x0439d74b8dcd4b7e, 0x9287dcdf7e26a3a6) - - CRYCOMPOSITE_BEGIN() - CRYCOMPOSITE_ADD(m_pTestExt3, "Ext3") - CRYCOMPOSITE_END(CComposed2) - - CRYINTERFACE_BEGIN() - CRYINTERFACE_END() - - private: - ITestExt3Ptr m_pTestExt3; - }; - - CRYREGISTER_CLASS(CComposed2) - - CComposed2::CComposed2() - : m_pTestExt3() - { - CryCreateClassInstance("TestExt3", m_pTestExt3); - } - - CComposed2::~CComposed2() - { - } - - ////////////////////////////////////////////////////////////////////////// - - class CTestExt4 - : public ITestExt1 - , public ITestExt2 - , public ITestExt3 - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(ITestExt1) - CRYINTERFACE_ADD(ITestExt2) - CRYINTERFACE_ADD(ITestExt3) - CRYINTERFACE_END() - - CRYGENERATE_CLASS(CTestExt4, "TestExt4", 0x43204e7cc1be45ca, 0x9df4ccb1c0dc1ad8) - - public: - virtual void Call1() const; - virtual void Call2(); - virtual void Call3(); - - private: - int i; - }; - - CRYREGISTER_CLASS(CTestExt4) - - CTestExt4::CTestExt4() - { - i = 4; - } - - CTestExt4::~CTestExt4() - { - printf("Inside CTestExt4 dtor\n"); - } - - void CTestExt4::Call1() const - { - printf("Inside CTestExt4::Call1()\n"); - } - - void CTestExt4::Call2() - { - printf("Inside CTestExt4::Call2()\n"); - } - - void CTestExt4::Call3() - { - printf("Inside CTestExt4::Call3()\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - class CMegaComposed - : public CComposed - , public CComposed2 - { - CRYGENERATE_CLASS(CMegaComposed, "MegaComposed", 0x512787559f84503, 0x421ac1af66f2fb6f) - - CRYCOMPOSITE_BEGIN() - CRYCOMPOSITE_ADD(m_pTestExt4, "Ext4") - CRYCOMPOSITE_ENDWITHBASE2(CMegaComposed, CComposed, CComposed2) - - CRYINTERFACE_BEGIN() - CRYINTERFACE_END() - - private: - AZStd::shared_ptr m_pTestExt4; - }; - - CRYREGISTER_CLASS(CMegaComposed) - - CMegaComposed::CMegaComposed() - : m_pTestExt4() - { - printf("Inside CMegaComposed ctor\n"); - m_pTestExt4 = CTestExt4::CreateClassInstance(); - } - - CMegaComposed::~CMegaComposed() - { - printf("Inside CMegaComposed dtor\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - static void TestComposition() - { - printf("\nTest composition:\n"); - - ICryUnknownPtr p; - if (CryCreateClassInstance("MegaComposed", p)) - { - ITestExt1Ptr p1 = cryinterface_cast(crycomposite_query(p, "Ext1")); - if (p1) - { - p1->Call1(); // calls CTestExt1::Call1() - } - ITestExt2Ptr p2 = cryinterface_cast(crycomposite_query(p, "Ext2")); - if (p2) - { - p2->Call2(); // calls CTestExt2::Call2() - } - ITestExt3Ptr p3 = cryinterface_cast(crycomposite_query(p, "Ext3")); - if (p3) - { - p3->Call3(); // calls CTestExt3::Call3() - } - p3 = cryinterface_cast(crycomposite_query(p, "Ext4")); - if (p3) - { - p3->Call3(); // calls CTestExt4::Call3() - } - p1 = cryinterface_cast(crycomposite_query(p.get(), "Ext4")); - p2 = cryinterface_cast(crycomposite_query(p.get(), "Ext4")); - - bool b = CryIsSameClassInstance(p1, p2); // true - } - - { - ICryUnknownConstPtr pCUnk = p; - ICryUnknownConstPtr pComp1 = crycomposite_query(pCUnk.get(), "Ext1"); - //ICryUnknownPtr pComp1 = crycomposite_query(pCUnk, "Ext1"); // must fail to compile due to const rules - - ITestExt1ConstPtr p1 = cryinterface_cast(pComp1); - if (p1) - { - p1->Call1(); - } - } - } -} // namespace TestComposition - - -////////////////////////////////////////////////////////////////////////// - - -namespace TestExtension -{ - class CFoobar - : public IFoobar - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(IFoobar) - CRYINTERFACE_END() - - CRYGENERATE_CLASS(CFoobar, "Foobar", 0x76c8dd6d16634531, 0x95d3b1cfabcf7ef4) - - public: - virtual void Foo(); - }; - - CRYREGISTER_CLASS(CFoobar) - - CFoobar::CFoobar() - { - } - - CFoobar::~CFoobar() - { - } - - void CFoobar::Foo() - { - printf("Inside CFoobar::Foo()\n"); - } - - static void TestFoobar() - { - AZStd::shared_ptr p = CFoobar::CreateClassInstance(); - { - CryInterfaceID iid = cryiidof(); - CryClassID clsid = p->GetFactory()->GetClassID(); - int t = 0; - } - - { - IAPtr sp_ = cryinterface_cast(p); // sp_ == NULL - - ICryUnknownPtr sp1 = cryinterface_cast(p); - IFoobarPtr sp = cryinterface_cast(sp1); - sp->Foo(); - } - - { - CFoobar* pF = p.get(); - pF->Foo(); - ICryUnknown* p1 = cryinterface_cast(pF); - } - - IFoobar* pFoo = cryinterface_cast(p.get()); - ICryFactory* pF1 = pFoo->GetFactory(); - pFoo->Foo(); - - int t = 0; - } - - ////////////////////////////////////////////////////////////////////////// - - class CRaboof - : public IRaboof - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(IRaboof) - CRYINTERFACE_END() - - CRYGENERATE_SINGLETONCLASS(CRaboof, "Raabof", 0xba482ce12b2e4309, 0x8238ed8b52cb1f1e) - - public: - virtual void Rab(); - }; - - CRYREGISTER_SINGLETON_CLASS(CRaboof) - - CRaboof::CRaboof() - { - } - - CRaboof::~CRaboof() - { - } - - void CRaboof::Rab() - { - printf("Inside CRaboof::Rab()\n"); - } - - static void TestRaboof() - { - AZStd::shared_ptr pFoo0_ = CRaboof::CreateClassInstance(); - IRaboofPtr pFoo0 = cryinterface_cast(pFoo0_); - ICryUnknownPtr p0 = cryinterface_cast(pFoo0); - - CryInterfaceID iid = cryiidof(); - CryClassID clsid = p0->GetFactory()->GetClassID(); - - AZStd::shared_ptr pFoo1 = CRaboof::CreateClassInstance(); - - pFoo0->Rab(); - pFoo1->Rab(); - } - - ////////////////////////////////////////////////////////////////////////// - - class CAB - : public IA - , public IB - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(IA) - CRYINTERFACE_ADD(IB) - CRYINTERFACE_END() - - CRYGENERATE_CLASS(CAB, "AB", 0xb9e54711a64448c0, 0xa4819b4ed3024d04) - - public: - virtual void A(); - virtual void B(); - - private: - int i; - }; - - CRYREGISTER_CLASS(CAB) - - CAB::CAB() - { - i = 0x12345678; - } - - CAB::~CAB() - { - } - - void CAB::A() - { - printf("Inside CAB::A()\n"); - } - - void CAB::B() - { - printf("Inside CAB::B()\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - class CABC - : public CAB - , public IC - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(IC) - CRYINTERFACE_ENDWITHBASE(CAB) - - CRYGENERATE_CLASS(CABC, "ABC", 0x4e61feae11854be7, 0xa16157c5f8baadd9) - - public: - virtual void C(); - - private: - int a; - }; - - CRYREGISTER_CLASS(CABC) - - CABC::CABC() - //: CAB() - { - a = 0x87654321; - } - - CABC::~CABC() - { - } - - void CABC::C() - { - printf("Inside CABC::C()\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - class CCustomC - : public ICustomC - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(IC) - CRYINTERFACE_ADD(ICustomC) - CRYINTERFACE_END() - - CRYGENERATE_CLASS(CCustomC, "CustomC", 0xee61760b98a44b71, 0xa05e7372b44bd0fd) - - public: - virtual void C(); - virtual void C1(); - - private: - int a; - }; - - CRYREGISTER_CLASS(CCustomC) - - CCustomC::CCustomC() - { - a = 0x87654321; - } - - CCustomC::~CCustomC() - { - } - - void CCustomC::C() - { - printf("Inside CCustomC::C()\n"); - } - - void CCustomC::C1() - { - printf("Inside CCustomC::C1()\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - class CMultiBase - : public CAB - , public CCustomC - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ENDWITHBASE2(CAB, CCustomC) - - CRYGENERATE_CLASS(CMultiBase, "MultiBase", 0x75966b8f98644d42, 0x8fbdd489e94cc29e) - - public: - virtual void A(); - virtual void C1(); - - int i; - }; - - CRYREGISTER_CLASS(CMultiBase) - - CMultiBase::CMultiBase() - { - i = 0x87654321; - } - - CMultiBase::~CMultiBase() - { - } - - void CMultiBase::C1() - { - printf("Inside CMultiBase::C1()\n"); - } - - void CMultiBase::A() - { - printf("Inside CMultiBase::A()\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - static void TestComplex() - { - { - ICPtr p; - if (CryCreateClassInstance(MAKE_CRYGUID(0x75966b8f98644d42, 0x8fbdd489e94cc29e), p)) - { - p->C(); - } - } - - { - ICustomCPtr p; - if (CryCreateClassInstance("MultiBase", p)) - { - p->C(); - } - } - - { - IFoobarPtr p; - if (CryCreateClassInstance(MAKE_CRYGUID(0x75966b8f98644d42, 0x8fbdd489e94cc29e), p)) - { - p->Foo(); - } - } - - { - AZStd::shared_ptr p = CMultiBase::CreateClassInstance(); - AZStd::shared_ptr pc = p; - - { - ICryUnknownPtr pUnk = cryinterface_cast(p); - ICryUnknownConstPtr pCUnk0 = cryinterface_cast(p); - ICryUnknownConstPtr pCUnk1 = cryinterface_cast(pc); - //ICryUnknownPtr pUnkF = cryinterface_cast(pc); // must fail to compile due to const rules - - ICryFactory* pF = pUnk->GetFactory(); - - int t = 0; - } - - ICPtr pC = cryinterface_cast(p); - ICustomCPtr pCC = cryinterface_cast(pC); - - p->C(); - p->C1(); - - pC->C(); - pCC->C1(); - - IAPtr pA = cryinterface_cast(p); - pA->A(); - p->A(); - } - - { - AZStd::shared_ptr p = CCustomC::CreateClassInstance(); - - ICPtr pC = cryinterface_cast(p); - ICustomCPtr pCC = cryinterface_cast(pC); - - p->C(); - p->C1(); - - pC->C(); - pCC->C1(); - } - { - CryInterfaceID ia = cryiidof(); - CryInterfaceID ib = cryiidof(); - CryInterfaceID ic = cryiidof(); - CryInterfaceID ico = cryiidof(); - } - - { - AZStd::shared_ptr p = CAB::CreateClassInstance(); - CryClassID clsid = p->GetFactory()->GetClassID(); - - IAPtr pA = cryinterface_cast(p); - IBPtr pB = cryinterface_cast(p); - - IBPtr pB1 = cryinterface_cast(pA); - IAPtr pA1 = cryinterface_cast(pB); - - pA->A(); - pB->B(); - - ICryUnknownPtr p1 = cryinterface_cast(pA); - ICryUnknownPtr p2 = cryinterface_cast(pB); - const ICryUnknown* p3 = cryinterface_cast(pB.get()); - - int t = 0; - } - - { - AZStd::shared_ptr pABC = CABC::CreateClassInstance(); - CryClassID clsid = pABC->GetFactory()->GetClassID(); - - ICryFactory* pFac = pABC->GetFactory(); - pFac->ClassSupports(cryiidof()); - pFac->ClassSupports(cryiidof()); - - IAPtr pABC0 = cryinterface_cast(pABC); - IBPtr pABC1 = cryinterface_cast(pABC0); - ICPtr pABC2 = cryinterface_cast(pABC1); - - pABC2->C(); - pABC1->B(); - - pABC2->GetFactory(); - - const IC* pCconst = pABC2.get(); - const ICryUnknown* pOconst = cryinterface_cast(pCconst); - const IA* pAconst = cryinterface_cast(pOconst); - const IB* pBconst = cryinterface_cast(pAconst); - - //const IA* pA11 = cryinterface_cast(pOconst); - - pCconst = cryinterface_cast(pBconst); - - IC* pC = static_cast(static_cast(pABC1.get())); - pC->C(); // calls IB::B() - - int t = 0; - } - } - - ////////////////////////////////////////////////////////////////////////// - // use of extension system without any of the helper macros/templates - - class CDontLikeMacrosFactory - : public ICryFactory - { - // ICryFactory - public: - virtual const char* GetClassName() const - { - return "DontLikeMacros"; - } - virtual const CryClassID& GetClassID() const - { - static const CryClassID cid = {0x73c3ab0042e6488aull, 0x89ca1a3763365565ull}; - return cid; - } - virtual bool ClassSupports(const CryInterfaceID& iid) const - { - return iid == cryiidof() || iid == cryiidof(); - } - virtual void ClassSupports(const CryInterfaceID*& pIIDs, size_t& numIIDs) const - { - static const CryInterfaceID iids[2] = {cryiidof(), cryiidof()}; - pIIDs = iids; - numIIDs = 2; - } - virtual ICryUnknownPtr CreateClassInstance() const; - - public: - static CDontLikeMacrosFactory& Access() - { - return s_factory; - } - - private: - CDontLikeMacrosFactory() {} - ~CDontLikeMacrosFactory() {} - - private: - static CDontLikeMacrosFactory s_factory; - }; - - CDontLikeMacrosFactory CDontLikeMacrosFactory::s_factory; - - class CDontLikeMacros - : public IDontLikeMacros - { - // ICryUnknown - public: - virtual ICryFactory* GetFactory() const - { - return &CDontLikeMacrosFactory::Access(); - }; - - // only needed to be able to create initial shared_ptr so we don't lose type info for debugging (i.e. inspecting shared_ptr<>) - template - friend void AZStd::Internal::sp_ms_deleter::destroy(); - template - friend AZStd::shared_ptr AZStd::make_shared(); - - protected: - virtual void* QueryInterface(const CryInterfaceID& iid) const - { - if (iid == cryiidof()) - { - return (void*) (ICryUnknown*) this; - } - else if (iid == cryiidof()) - { - return (void*) (IDontLikeMacros*) this; - } - else - { - return 0; - } - } - - virtual void* QueryComposite(const char*) const - { - return 0; - } - - // IDontLikeMacros - public: - virtual void CallMe() - { - printf("Yey, no macros...\n"); - } - - CDontLikeMacros() {} - - protected: - virtual ~CDontLikeMacros() {} - }; - - ICryUnknownPtr CDontLikeMacrosFactory::CreateClassInstance() const - { - AZStd::shared_ptr p = AZStd::make_shared(); - return ICryUnknownPtr(*static_cast*>(static_cast(&p))); - } - - static SRegFactoryNode g_dontLikeMacrosFactory(&CDontLikeMacrosFactory::Access()); - - ////////////////////////////////////////////////////////////////////////// - - static void TestDontLikeMacros() - { - ICryFactory* f = &CDontLikeMacrosFactory::Access(); - - f->ClassSupports(cryiidof()); - f->ClassSupports(cryiidof()); - - const CryInterfaceID* pIIDs = 0; - size_t numIIDs = 0; - f->ClassSupports(pIIDs, numIIDs); - - ICryUnknownPtr p = f->CreateClassInstance(); - IDontLikeMacrosPtr pp = cryinterface_cast(p); - - ICryUnknownPtr pq = crycomposite_query(p, "blah"); - - pp->CallMe(); - } -} // namespace TestExtension - - -////////////////////////////////////////////////////////////////////////// - - -void TestExtensions(ICryFactoryRegistryImpl* pReg) -{ - printf("Test extensions:\n"); - - struct MyCallback - : public ICryFactoryRegistryCallback - { - virtual void OnNotifyFactoryRegistered(ICryFactory* pFactory) - { - int test = 0; - } - virtual void OnNotifyFactoryUnregistered(ICryFactory* pFactory) - { - int test = 0; - } - }; - - //pReg->RegisterCallback((ICryFactoryRegistryCallback*) 0x4); - //pReg->RegisterCallback((ICryFactoryRegistryCallback*) 0x1); - //pReg->RegisterCallback((ICryFactoryRegistryCallback*) 0x3); - //pReg->RegisterCallback((ICryFactoryRegistryCallback*) 0x3); - //pReg->RegisterCallback((ICryFactoryRegistryCallback*) 0x2); - - //pReg->UnregisterCallback((ICryFactoryRegistryCallback*) 0x2); - //pReg->UnregisterCallback((ICryFactoryRegistryCallback*) 0x2); - //pReg->UnregisterCallback((ICryFactoryRegistryCallback*) 0x4); - //pReg->UnregisterCallback((ICryFactoryRegistryCallback*) 0x3); - //pReg->UnregisterCallback((ICryFactoryRegistryCallback*) 0x1); - - //MyCallback callback0; - //pReg->RegisterCallback(&callback0); - //pReg->RegisterFactories(g_pHeadToRegFactories); - - //pReg->RegisterFactories(g_pHeadToRegFactories); - //pReg->UnregisterFactories(g_pHeadToRegFactories); - - ICryFactory* pF[4]; - size_t numFactories = 4; - pReg->IterateFactories(cryiidof(), pF, numFactories); - pReg->IterateFactories(MAKE_CRYGUID(-1, -1), pF, numFactories); - - numFactories = (size_t) -1; - pReg->IterateFactories(cryiidof(), 0, numFactories); - - MyCallback callback1; - pReg->RegisterCallback(&callback1); - pReg->UnregisterCallback(&callback1); - - ICryFactory* p; - p = pReg->GetFactory(MAKE_CRYGUID(0xee61760b98a44b71, 0xa05e7372b44bd0fd)); - p = pReg->GetFactory("CustomC"); - p = pReg->GetFactory("ABC"); - p = pReg->GetFactory((const char*)0); - - p = pReg->GetFactory("DontLikeMacros"); - p = pReg->GetFactory(MAKE_CRYGUID(0x73c3ab0042e6488a, 0x89ca1a3763365565)); - - TestExtension::TestFoobar(); - TestExtension::TestRaboof(); - TestExtension::TestComplex(); - TestExtension::TestDontLikeMacros(); - - TestComposition::TestComposition(); -} - -#endif // #ifdef EXTENSION_SYSTEM_INCLUDE_TESTCASES diff --git a/Code/CryEngine/CrySystem/ExtensionSystem/TestCases/TestExtensions.h b/Code/CryEngine/CrySystem/ExtensionSystem/TestCases/TestExtensions.h deleted file mode 100644 index ac9ad04dc7..0000000000 --- a/Code/CryEngine/CrySystem/ExtensionSystem/TestCases/TestExtensions.h +++ /dev/null @@ -1,126 +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 : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYSYSTEM_EXTENSIONSYSTEM_TESTCASES_TESTEXTENSIONS_H -#define CRYINCLUDE_CRYSYSTEM_EXTENSIONSYSTEM_TESTCASES_TESTEXTENSIONS_H -#pragma once - - -//#define EXTENSION_SYSTEM_INCLUDE_TESTCASES - -#ifdef EXTENSION_SYSTEM_INCLUDE_TESTCASES - -#include - -struct ICryFactoryRegistryImpl; - -void TestExtensions(ICryFactoryRegistryImpl* pReg); - -struct IFoobar - : public ICryUnknown -{ - CRYINTERFACE_DECLARE(IFoobar, 0x539e9c672cad4a03, 0x9ecd8069c99a846b) - - virtual void Foo() = 0; -}; - -DECLARE_SMART_POINTERS(IFoobar); - -struct IRaboof - : public ICryUnknown -{ - CRYINTERFACE_DECLARE(IRaboof, 0x135ca25e634b4d13, 0x9e4467968a708822) - - virtual void Rab() = 0; -}; - -DECLARE_SMART_POINTERS(IRaboof); - -struct IA - : public ICryUnknown -{ - CRYINTERFACE_DECLARE(IA, 0xd93aaceb35ec427e, 0xb64bf8dec4997e67) - - virtual void A() = 0; -}; - -DECLARE_SMART_POINTERS(IA); - -struct IB - : public ICryUnknown -{ - CRYINTERFACE_DECLARE(IB, 0xe0d830c826424e11, 0x9eacfa19eaf31ffb) - - virtual void B() = 0; -}; - -DECLARE_SMART_POINTERS(IB); - -struct IC - : public ICryUnknown -{ - CRYINTERFACE_DECLARE(IC, 0x577509a20fc5477c, 0x893757c9ca88b27b) - - virtual void C() = 0; -}; - -DECLARE_SMART_POINTERS(IC); - -struct ICustomC - : public IC -{ - CRYINTERFACE_DECLARE(ICustomC, 0x2ac769da4c7443bf, 0x80911033e21dfbcf) - - virtual void C1() = 0; -}; - -DECLARE_SMART_POINTERS(ICustomC); - -////////////////////////////////////////////////////////////////////////// -// use of extension system without any of the helper macros/templates - -struct IDontLikeMacros - : public ICryUnknown -{ - template - friend const CryInterfaceID& InterfaceCastSemantics::cryiidof(); - template - friend void AZStd::Internal::sp_ms_deleter::destroy(); - template - friend AZStd::shared_ptr AZStd::make_shared(); -protected: - virtual ~IDontLikeMacros() {} - -private: - // It's very important that this static function is implemented for each interface! - // Otherwise the consistency of cryinterface_cast() is compromised because - // cryiidof() = cryiidof>() {baseof = ICryUnknown in most cases} - static const CryInterfaceID& IID() - { - static const CryInterfaceID iid = {0x0f43b7e3f1364af0ull, 0xb4a16a975bea3ec4ull}; - return iid; - } - -public: - virtual void CallMe() = 0; -}; - -DECLARE_SMART_POINTERS(IDontLikeMacros); - - -#endif // #ifdef EXTENSION_SYSTEM_INCLUDE_TESTCASES - -#endif // CRYINCLUDE_CRYSYSTEM_EXTENSIONSYSTEM_TESTCASES_TESTEXTENSIONS_H diff --git a/Code/CryEngine/CrySystem/RemoteCommand.cpp b/Code/CryEngine/CrySystem/RemoteCommand.cpp deleted file mode 100644 index 5f1129be22..0000000000 --- a/Code/CryEngine/CrySystem/RemoteCommand.cpp +++ /dev/null @@ -1,191 +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 : Remote command system implementation - -#include "CrySystem_precompiled.h" -#include "IServiceNetwork.h" -#include "RemoteCommand.h" -#include "RemoteCommandHelpers.h" - -//----------------------------------------------------------------------------- - -// remote system internal logging -#ifdef RELEASE - #define LOG_VERBOSE(level, txt, ...) -#else - #define LOG_VERBOSE(level, txt, ...) if (GetManager()->CheckVerbose(level)) { GetManager()->Log(txt, __VA_ARGS__); } -#endif - -//----------------------------------------------------------------------------- - -CRemoteCommandManager::CRemoteCommandManager() -{ - // Create the CVAR - m_pVerboseLevel = gEnv->pConsole->RegisterInt("rc_debugVerboseLevel", 0, VF_DEV_ONLY); -} - -CRemoteCommandManager::~CRemoteCommandManager() -{ - // Release the CVar - if (NULL != m_pVerboseLevel) - { - m_pVerboseLevel->Release(); - m_pVerboseLevel = NULL; - } -} - -IRemoteCommandServer* CRemoteCommandManager::CreateServer(uint16 localPort) -{ - // Create the listener - IServiceNetworkListener* listener = gEnv->pServiceNetwork->CreateListener(localPort); - if (NULL == listener) - { - return NULL; - } - - // Create the wrapper - return new CRemoteCommandServer(this, listener); -} - -IRemoteCommandClient* CRemoteCommandManager::CreateClient() -{ - // Create the wrapper - return new CRemoteCommandClient(this); -} - -void CRemoteCommandManager::RegisterCommandClass(IRemoteCommandClass& commandClass) -{ - // Make sure command class is not already registered - const string& className(commandClass.GetName()); - TClassMap::const_iterator it = m_pClasses.find(className); - if (it != m_pClasses.end()) - { - LOG_VERBOSE(1, "Class '%s' is already registered", - className.c_str()); - - return; - } - - const uint32 classID = m_pClassesByID.size(); - m_pClassesByID.push_back(&commandClass); - m_pClassesMap[ className ] = classID; - m_pClasses[ className ] = &commandClass; - - // Verbose - LOG_VERBOSE(1, "Registered command class '%s' with id %d", - className.c_str(), - classID); -} - -#ifndef RELEASE -bool CRemoteCommandManager::CheckVerbose(const uint32 level) const -{ - const int verboseLevel = m_pVerboseLevel->GetIVal(); - return (int)level < verboseLevel; -} - -void CRemoteCommandManager::Log(const char* txt, ...) const -{ - // format the print buffer - char buffer[512]; - va_list ap; - va_start(ap, txt); - vsprintf_s(buffer, sizeof(buffer), txt, ap); - va_end(ap); - - // pass to log - gEnv->pLog->LogAlways(buffer); -} -#endif - -void CRemoteCommandManager::BuildClassMapping(const std::vector& classNames, std::vector< IRemoteCommandClass* >& outClasses) -{ - LOG_VERBOSE(3, "Building class mapping for %d classes", - classNames.size()); - - // Output list size has the same size as class names array - const uint32 numClasses = classNames.size(); - outClasses.resize(numClasses); - - // Match the classes - for (size_t i = 0; i < numClasses; ++i) - { - // Find the matching class - const string& className = classNames[i]; - TClassMap::const_iterator it = m_pClasses.find(className); - if (it != m_pClasses.end()) - { - CRY_ASSERT(className == it->second->GetName()); - CRY_ASSERT(it->second != NULL); - outClasses[i] = it->second; - - // Report class mapping in heavy verbose mode - LOG_VERBOSE(3, "Class[%d] = %s", - i, - className.c_str()); - } - else - { - outClasses[i] = NULL; - - // Class not mapped (this can cause errors) - LOG_VERBOSE(0, "Remote command class '%s' not found on this machine", - className.c_str()); - } - } -} - -void CRemoteCommandManager::SetVerbosityLevel(const uint32 level) -{ - // propagate the value to CVar (so it is consistent across the engine) - if (NULL != m_pVerboseLevel) - { - m_pVerboseLevel->Set((int)level); - } -} - -void CRemoteCommandManager::GetClassList(std::vector& outClassNames) const -{ - const uint32 numClasses = m_pClassesByID.size(); - outClassNames.resize(numClasses); - for (size_t id = 0; id < numClasses; ++id) - { - IRemoteCommandClass* theClass = m_pClassesByID[id]; - if (NULL != theClass) - { - outClassNames[id] = theClass->GetName(); - } - } -} - -bool CRemoteCommandManager::FindClassId(IRemoteCommandClass* commandClass, uint32& outClassId) const -{ - // Local search (linear, slower) - TClassIDMap::const_iterator it = m_pClassesMap.find(commandClass->GetName()); - if (it != m_pClassesMap.end()) - { - outClassId = it->second; - return true; - } - - // Not found - return false; -} - -//----------------------------------------------------------------------------- - -// Do not remove (can mess up the uber file builds) -#undef LOG_VERBOSE - -//----------------------------------------------------------------------------- diff --git a/Code/CryEngine/CrySystem/RemoteCommand.h b/Code/CryEngine/CrySystem/RemoteCommand.h deleted file mode 100644 index 6ce5e3fd11..0000000000 --- a/Code/CryEngine/CrySystem/RemoteCommand.h +++ /dev/null @@ -1,459 +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 : Remote command system implementation - - -#pragma once - - -//----------------------------------------------------------------------------- - -#include "IServiceNetwork.h" -#include "IRemoteCommand.h" -#include "CryThread.h" - -class CRemoteCommandManager; - -// Remote command client implementation -class CRemoteCommandClient - : public IRemoteCommandClient - , public CryRunnable -{ -protected: - //------------------------------------------------------------- - - class Command - { - public: - ILINE IServiceNetworkMessage* GetMessage() const - { - return m_pMessage; - } - - ILINE uint32 GetCommandId() const - { - return m_id; - } - - public: - // Create command data from serializing a remote command object - static Command* Compile(const IRemoteCommand& cmd, const uint32 commandId, const uint32 classId); - - void AddRef(); - void Release(); - - private: - Command(); - ~Command(); - - volatile int m_refCount; - uint32 m_id; - const char* m_szClassName; // debug only - IServiceNetworkMessage* m_pMessage; - }; - - //------------------------------------------------------------- - - // Local connection reference to command - // NOTE: pCommand is reference counted from the calling code - struct CommandRef - { - Command* m_pCommand; - uint64 m_lastSentTime; - - ILINE CommandRef() - : m_pCommand(NULL) - , m_lastSentTime(0) - {} - - ILINE CommandRef(Command* pCommand) - : m_pCommand(pCommand) - , m_lastSentTime(0) - {} - - // Order function for set container (we want to keep the commands sorted by ID) - static ILINE bool CompareCommandRefs(CommandRef* const& a, CommandRef* const& b) - { - return a->m_pCommand->GetCommandId() < b->m_pCommand->GetCommandId(); - } - }; - - //------------------------------------------------------------- - - // Remote server connection wrapper - class Connection - : public IRemoteCommandConnection - { - // How many commands we can send upfront before waiting for an ACK - static const uint32 kCommandSendLead = 50; - - // How much command data can be merged into a single packet (KB) - static const uint32 kCommandMaxMergePacketSize = 1024; - - // Time after which we start resending commands (ms) - static const uint32 kCommandResendTime = 2000; - - protected: - CRemoteCommandManager* m_pManager; - volatile int m_refCount; - - // Connection (from service network layer) - IServiceNetworkConnection* m_pConnection; - - // Cached address of the remote endpoint - ServiceNetworkAddress m_remoteAddress; - - // Pending commands, they are kept ed here until they are ACKed as executed by server - typedef std::vector TCommands; - TCommands m_pCommands; - CryMutex m_commandAccessMutex; - - // A queue of raw messages - typedef CryMT::CLocklessPointerQueue TRawMessageQueue; - TRawMessageQueue m_pRawMessages; - CryMutex m_rawMessagesMutex; - - // Last command that was ACKed as received by server - // This is used to synchronize the both ends of the pipeline - uint32 m_lastReceivedCommand; - - // Last command that was ACKed as executed by server - // This is used to synchronize the both ends of the pipeline - uint32 m_lastExecutedCommand; - - public: - ILINE CRemoteCommandManager* GetManager() const - { - return m_pManager; - } - - public: - Connection(CRemoteCommandManager* pManager, IServiceNetworkConnection* pConnection, uint32 currentCommandId); - - // Add command to sending queue in this connection - void AddToSendQueue(Command* pCommand); - - // Process the communication, returns false if connection should be deleted - bool Update(); - - // Send the "disconnect" message to the remote side therefore gracefully closing the connection. - void SendDisconnectMessage(); - - public: - // IRemoteCommandConnection interface implementation - virtual bool IsAlive() const; - virtual const ServiceNetworkAddress& GetRemoteAddress() const; - virtual bool SendRawMessage(IServiceNetworkMessage* pMessage); - virtual IServiceNetworkMessage* ReceiveRawMessage(); - virtual void Close(bool bFlushQueueBeforeClosing = false); - virtual void AddRef(); - virtual void Release(); - - private: - ~Connection(); - }; - -protected: - CRemoteCommandManager* m_pManager; - - typedef std::vector TConnections; - TConnections m_pConnections; - TConnections m_pConnectionsToDelete; - CryMutex m_accessMutex; - - // Local command ID counter, incremented atomically using CryInterlockedIncrement - volatile uint32 m_commandId; - - typedef CryThread TRemoteClientThread; - TRemoteClientThread* m_pThread; - CryEvent m_threadEvent; - bool m_bCloseThread; - -public: - ILINE CRemoteCommandManager* GetManager() const - { - return m_pManager; - } - -public: - CRemoteCommandClient(CRemoteCommandManager* pManager); - virtual ~CRemoteCommandClient(); - - // IRemoteCommandClient interface - virtual void Delete(); - virtual bool Schedule(const IRemoteCommand& command); - virtual IRemoteCommandConnection* ConnectToServer(const class ServiceNetworkAddress& serverAddress); - - // CryRunnable interface implementation - virtual void Run(); - virtual void Cancel(); -}; - -//----------------------------------------------------------------------------- - -// Remote command server implementation -class CRemoteCommandServer - : public IRemoteCommandServer - , public CryRunnable -{ -#if defined(AZ_RESTRICTED_PLATFORM) -#include AZ_RESTRICTED_FILE(RemoteCommand_h) -#endif - -protected: - // Wrapped commands - class WrappedCommand - { - private: - IRemoteCommand* m_pCommand; - volatile int m_refCount; - uint32 m_commandID; - - public: - ILINE const uint32 GetId() const - { - return m_commandID; - } - - ILINE IRemoteCommand* GetCommand() const - { - return m_pCommand; - } - - public: - WrappedCommand(IRemoteCommand* pCommand, const uint32 commandId); - void AddRef(); - void Release(); - - private: - ~WrappedCommand(); - }; - - // Local endpoint - class Endpoint - { - private: - IServiceNetworkConnection* m_pConnection; - class CRemoteCommandServer* m_pServer; - CRemoteCommandManager* m_pManager; - - // ACK counters for synchronization - uint32 m_lastReceivedCommand; - uint32 m_lastExecutedCommand; - uint32 m_lastReceivedCommandACKed; - uint32 m_lastExecutedCommandACKed; - CryMutex m_accessLock; - - // We have received class list (it's a valid RC connection) - bool m_bHasReceivedClassList; - - // Locally mapped class id (because IDs on remote side can be different than here) - typedef std::vector< IRemoteCommandClass* > TLocalClassFactoryList; - TLocalClassFactoryList m_pLocalClassFactories; - - // Commands that were received and should be executed - typedef CryMT::CLocklessPointerQueue< WrappedCommand > TCommandQueue; - TCommandQueue m_pCommandsToExecute; - CryMutex m_commandListLock; - - public: - ILINE CRemoteCommandManager* GetManager() const - { - return m_pManager; - } - - // Get the endpoint connection - ILINE IServiceNetworkConnection* GetConnection() const - { - return m_pConnection; - } - - // Have we received a class list from the client - ILINE bool HasReceivedClassList() const - { - return m_bHasReceivedClassList; - } - - public: - Endpoint(CRemoteCommandManager* pManager, class CRemoteCommandServer* pServer, IServiceNetworkConnection* pConnection); - ~Endpoint(); - - // Execute pending commands (called from main thread) - void Execute(); - - // Update (send/receive, etc) Returns false if endpoint died. - bool Update(); - - // Get the class name as translated by this endpoint (by ID) - const char* GetClassName(const uint32 classId) const; - - // Create command object by class ID - IRemoteCommand* CreateObject(const uint32 classId) const; - }; - - // Received raw message - // Beware to use always via pointer to this type since propper reference counting is not implemented for copy and assigment - struct RawMessage - { - // We keep a reference to connection so we know where to send the response - IServiceNetworkConnection* m_pConnection; - IServiceNetworkMessage* m_pMessage; - - ILINE RawMessage(IServiceNetworkConnection* pConnection, IServiceNetworkMessage* pMessage) - : m_pConnection(pConnection) - , m_pMessage(pMessage) - { - m_pMessage->AddRef(); - m_pConnection->AddRef(); - } - - ILINE ~RawMessage() - { - m_pMessage->Release(); - m_pConnection->Release(); - } - - private: - ILINE RawMessage([[maybe_unused]] const RawMessage& other) {}; - ILINE RawMessage& operator==([[maybe_unused]] const RawMessage& other) { return *this; } - }; - -protected: - CRemoteCommandManager* m_pManager; - - // Network listening socket - IServiceNetworkListener* m_pListener; - - // Live endpoints - typedef std::vector TEndpoints; - TEndpoints m_pEndpoints; - TEndpoints m_pUpdateEndpoints; - CryMutex m_accessLock; - - // Endpoints that were discarded and should be deleted - // We can delete endpoints only from the update thread - TEndpoints m_pEndpointToDelete; - - // Received raw messages - typedef CryMT::CLocklessPointerQueue TRawMessagesQueue; - TRawMessagesQueue m_pRawMessages; - CryMutex m_rawMessagesLock; - - // Listeners for raw messages that require synchronous processing - typedef std::vector TRawMessageListenersSync; - TRawMessageListenersSync m_pRawListenersSync; - - // Listeners for raw messages that can be processed asynchronously (faster path) - typedef std::vector TRawMessageListenersAsync; - TRawMessageListenersAsync m_pRawListenersAsync; - - // Command communication and deserialization is done on thread - typedef CryThread TRemoteServerThread; - TRemoteServerThread* m_pThread; - - // Suppression counter (execution of commands is suppressed when>0) - // This is updated using CryInterlocked* functions - volatile int m_suppressionCounter; - bool m_bIsSuppressed; - - // Request to close the network thread - bool m_bCloseThread; - -public: - ILINE CRemoteCommandManager* GetManager() const - { - return m_pManager; - } - -public: - CRemoteCommandServer(CRemoteCommandManager* pManager, IServiceNetworkListener* pListener); - virtual ~CRemoteCommandServer(); - - // IRemoteCommandServer interface implementation - virtual void Delete(); - virtual void FlushCommandQueue(); - virtual void SuppressCommands(); - virtual void ResumeCommands(); - virtual void RegisterSyncMessageListener(IRemoteCommandListenerSync* pListener); - virtual void UnregisterSyncMessageListener(IRemoteCommandListenerSync* pListener); - virtual void RegisterAsyncMessageListener(IRemoteCommandListenerAsync* pListener); - virtual void UnregisterAsyncMessageListener(IRemoteCommandListenerAsync* pListener); - virtual void Broadcast(IServiceNetworkMessage* pMessage); - virtual bool HasConnectedClients() const; - - // CryRunnable - virtual void Run(); - virtual void Cancel(); - -protected: - void ProcessRawMessageAsync(IServiceNetworkMessage* pMessage, IServiceNetworkConnection* pConnection); - void ProcessRawMessagesSync(); -}; - -//----------------------------------------------------------------------------- - -// Remote command manager implementation -class CRemoteCommandManager - : public IRemoteCommandManager -{ -public: - CRemoteCommandManager(); - virtual ~CRemoteCommandManager(); - - // IRemoteCommandManager interface implementation - virtual void SetVerbosityLevel(const uint32 level); - virtual IRemoteCommandServer* CreateServer(uint16 localPort); - virtual IRemoteCommandClient* CreateClient(); - virtual void RegisterCommandClass(IRemoteCommandClass& commandClass); - - // Debug print -#ifdef RELEASE - void Log([[maybe_unused]] const char* txt, ...) const {}; - bool CheckVerbose([[maybe_unused]] const uint32 level) const { return false; } -#else - void Log(const char* txt, ...) const; - bool CheckVerbose(const uint32 level) const; -#endif - - // Build ID->Class Factory mapping given the class name list, will report errors to the log. - void BuildClassMapping(const std::vector& classNames, std::vector< IRemoteCommandClass* >& outClasses); - - // Get list of class names (in order of their IDs) - void GetClassList(std::vector& outClassNames) const; - - // Find class ID for given class, returns false if not found - bool FindClassId(IRemoteCommandClass* commandClass, uint32& outClassId) const; - -public: - ILINE CRemoteCommandManager* GetManager() - { - return this; - } - -private: - // Class name mapping - typedef std::map< string, IRemoteCommandClass* > TClassMap; - TClassMap m_pClasses; - - // Class ID lookup - typedef std::vector< IRemoteCommandClass* > TClassIDList; - TClassIDList m_pClassesByID; - - // Class ID mapping - typedef std::map< string, int > TClassIDMap; - TClassIDMap m_pClassesMap; - - // Verbose level - ICVar* m_pVerboseLevel; -}; diff --git a/Code/CryEngine/CrySystem/RemoteCommandClient.cpp b/Code/CryEngine/CrySystem/RemoteCommandClient.cpp deleted file mode 100644 index 1855aae4a9..0000000000 --- a/Code/CryEngine/CrySystem/RemoteCommandClient.cpp +++ /dev/null @@ -1,756 +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 : Remote command system implementation - -#include "CrySystem_precompiled.h" -#include "IServiceNetwork.h" -#include "RemoteCommand.h" -#include "RemoteCommandHelpers.h" - -//----------------------------------------------------------------------------- - -// remote system internal logging -#ifdef RELEASE - #define LOG_VERBOSE(level, txt, ...) -#else - #define LOG_VERBOSE(level, txt, ...) if (GetManager()->CheckVerbose(level)) { GetManager()->Log(txt, __VA_ARGS__); } -#endif - -//----------------------------------------------------------------------------- - -CRemoteCommandClient::Command::Command() - : m_refCount(1) - , m_szClassName(NULL) - , m_id(0) -{ -} - -CRemoteCommandClient::Command::~Command() -{ - // Release message buffer with compiled command data - if (m_pMessage != NULL) - { - m_pMessage->Release(); - m_pMessage = NULL; - } -} - -CRemoteCommandClient::Command* CRemoteCommandClient::Command::Compile(const IRemoteCommand& cmd, const uint32 commandId, const uint32 classId) -{ - // Build command header - CommandHeader header; - header.classId = classId; - header.commandId = commandId; - header.size = 0; // not known yet - - // Output stream builder - CDataWriteStreamBuffer writer; - - // Start the packet with a command header (it will be later overwritten) - writer << header; - - // Serialize command header and data - const uint32 commandDataStart = writer.GetSize(); - cmd.SaveToStream(writer); - const uint32 commandDataEnd = writer.GetSize(); - - // Extract a message from the stream - IServiceNetworkMessage* pMessage = writer.BuildMessage(); - if (NULL == pMessage) - { - // No message was generated (for some reason) - // Do not allow this command to compile - return NULL; - } - - // Rewrite header with the proper command size - // This is a little bit over-the-top because it uses another serializer created - // on top of the message buffer. The advantage is that we have the endianess problem abstracted away. - // TODO: consider writing the size directly - { - // update header with popper data size - const uint32 dataSize = commandDataEnd - commandDataStart; - header.size = dataSize; - - // rewrite the header in existing message - CDataWriteStreamToMessage inPlaceWriter(pMessage); - inPlaceWriter << header; - } - - // Create command wrapper - Command* pCommand = new Command(); - pCommand->m_id = commandId; - pCommand->m_szClassName = cmd.GetClass()->GetName(); - pCommand->m_pMessage = pMessage; - return pCommand; -} - -void CRemoteCommandClient::Command::AddRef() -{ - CryInterlockedIncrement(&m_refCount); -} - -void CRemoteCommandClient::Command::Release() -{ - if (0 == CryInterlockedDecrement(&m_refCount)) - { - delete this; - } -} - -//----------------------------------------------------------------------------- - -CRemoteCommandClient::Connection::Connection(CRemoteCommandManager* pManager, IServiceNetworkConnection* pConnection, uint32 currentCommandId) - : m_pConnection(pConnection) - , m_pManager(pManager) - , m_lastReceivedCommand(currentCommandId) - , m_lastExecutedCommand(currentCommandId) - , m_remoteAddress(pConnection->GetRemoteAddress()) - , m_refCount(1) -{ - // The first thing to do after the connection is initialized is to - // send the message with list of classes supported by this side. - { - // Write the header - PackedHeader header; - header.magic = PackedHeader::kMagic; - header.msgType = PackedHeader::eCommand_ClassList; - header.count = currentCommandId; // send the intial command ID so we can be in sync - - // Get the class list for our local remote command manager - std::vector< string > classList; - GetManager()->GetClassList(classList); - - // Write the message - CDataWriteStreamBuffer writer; - writer << header; - writer << classList; - - // Send the message to the remote side - IServiceNetworkMessage* pMsg = writer.BuildMessage(); - if (NULL != pMsg) - { - LOG_VERBOSE(1, "Sent class list message (%d classes, size=%d) to '%s'", - classList.size(), - pMsg->GetSize(), - m_pConnection->GetRemoteAddress().ToString().c_str()); - - // TODO: well, there is no reason this can fail since the connection is brand new, but... - // We still relay on the service network to deliver this message unharmed. - m_pConnection->SendMsg(pMsg); - - // cleanup - pMsg->Release(); - } - } -} - -CRemoteCommandClient::Connection::~Connection() -{ - // Close the connection - const bool bFlushBeforeClosing = false; - Close(bFlushBeforeClosing); - - // Release any commands left over on the list - for (TCommands::const_iterator it = m_pCommands.begin(); - it != m_pCommands.end(); ++it) - { - (*it)->m_pCommand->Release(); - delete (*it); - } - m_pCommands.clear(); - - // Release all of the raw messages that were not picked up - while (!m_pRawMessages.empty()) - { - IServiceNetworkMessage* pMessage = m_pRawMessages.pop(); - pMessage->Release(); - } - - // Release the connection object - SAFE_RELEASE(m_pConnection); -} - -void CRemoteCommandClient::Connection::SendDisconnectMessage() -{ - if (NULL != m_pConnection && m_pConnection->IsAlive()) - { - IDataWriteStream* pWriter = gEnv->pServiceNetwork->CreateMessageWriter(); - if (NULL != pWriter) - { - // write header to message - PackedHeader header; - header.magic = PackedHeader::kMagic; - header.count = 0; - header.msgType = PackedHeader::eCommand_Disconnect; - *pWriter << header; - - // Send the disconnect signal - IServiceNetworkMessage* pMessage = pWriter->BuildMessage(); - if (NULL != pMessage) - { - m_pConnection->SendMsg(pMessage); - pMessage->Release(); - } - - pWriter->Delete(); - } - } -} - -void CRemoteCommandClient::Connection::AddToSendQueue(Command* pCommand) -{ - // Do not add commands if the connection is closed - if (m_pConnection == NULL) - { - return; - } - - // Add command to local list - // NOTE: this list always needs to be sorted in increasing command ID for various optimization reason. - // This is achieved by resorting after pushing each element. Usually the cost of this is close to nothing - // because incoming commands tend to be added with increasing command IDs. - // The only case when something else can happen is when commands are added from different threads - // and the one that was lower CommandID took longer to serialize and therefore is added later. - // Anyway, this case is handled here. - { - CryAutoLock lock(m_commandAccessMutex); - - // Always add to the end (don't try to guess position) - // TODO: consider binary search - m_pCommands.push_back(new CommandRef(pCommand)); - - // Resort, NODE: This usually does not sort anything because the vector is already sorted - std::sort(m_pCommands.begin(), m_pCommands.end(), CommandRef::CompareCommandRefs); - } - - // Keep local reference to command (since we added it to our array) - pCommand->AddRef(); -} - -bool CRemoteCommandClient::Connection::Update() -{ - // If the network connection got dead we should close this one to - if ((NULL == m_pConnection) || !m_pConnection->IsAlive()) - { - return false; - } - - // Receive ACKs first so we have better view of what to send - uint32 newLastExecutedCommand = m_lastExecutedCommand; - uint32 newLastReceivedCommand = m_lastReceivedCommand; - IServiceNetworkMessage* pMsg = m_pConnection->ReceiveMsg(); - while (pMsg != NULL) - { - // Deserialize the message - { - CDataReadStreamFormMessage reader(pMsg); - ResponseHeader response; - reader << response; - - // is this proper command system message ? - if (response.magic == PackedHeader::kMagic) - { - if (response.msgType == PackedHeader::eCommand_ACK) - { - // Update internal ACK values - // This code supports getting the ACK messages out of order. - newLastExecutedCommand = max(newLastExecutedCommand, response.lastCommandExecuted); - newLastReceivedCommand = max(newLastReceivedCommand, response.lastCommandReceived); - - LOG_VERBOSE(3, "ACK (rcv=%d, exe=%d) received from '%s'", - response.lastCommandReceived, - response.lastCommandExecuted, - m_pConnection->GetRemoteAddress().ToString().c_str()); - } - else if (response.msgType == PackedHeader::eCommand_Disconnect) - { - // Disconnect request was received - LOG_VERBOSE(3, "DISCONNECT (rcv=%d, exe=%d) received from '%s'", - response.lastCommandReceived, - response.lastCommandExecuted, - m_pConnection->GetRemoteAddress().ToString().c_str()); - - // Close connection - m_pConnection->Close(); - m_pConnection->Release(); - m_pConnection = NULL; - - // release the message - pMsg->Release(); - - // Signal manager to delete this object - return false; - } - } - else - { - // Keep an extra reference for the message in the raw message list - pMsg->AddRef(); - - // Assume it's a raw message, add it to the raw list - m_pRawMessages.push(pMsg); - } - } - - // Release message data - pMsg->Release(); - - // Get next message from the network - pMsg = m_pConnection->ReceiveMsg(); - } - - // ACK was updated - if ((newLastExecutedCommand != m_lastExecutedCommand) || - (newLastReceivedCommand != m_lastReceivedCommand)) - { - m_lastExecutedCommand = newLastExecutedCommand; - m_lastReceivedCommand = newLastReceivedCommand; - - // Drop commands that were ACKed as received (server has them and they will be executed soon) - { - CryAutoLock lock(m_commandAccessMutex); - - // we use this to count how many elements we need to remove later from the command vector - uint32 numCommandsToDelete = 0; - - for (TCommands::const_iterator it = m_pCommands.begin(); - it != m_pCommands.end(); ++it) - { - CommandRef* cmdRef = *it; - - // Command is still needed because it was not yet received by the remote part - if (cmdRef->m_pCommand->GetCommandId() > newLastReceivedCommand) - { - break; - } - - // Drop the command data - cmdRef->m_pCommand->Release(); - delete cmdRef; - - ++numCommandsToDelete; - } - - // Erase the command slots in the vector (in one batch) - if (numCommandsToDelete > 0) - { - m_pCommands.erase(m_pCommands.begin(), m_pCommands.begin() + numCommandsToDelete); - } - } - } - - // (Re)Send the commands - { - // Calculate the maximum command ID we can send, this depends on - // the last command that was ACKed as executed on the remote side. - // This effectively throttles the communication and prevents the - // situation when remote side is flooded with unprocessed commands. - // NOTE: the time when command is executed is different to the - // time that command is received. Sometimes if the server is suppressed (level loading) - // it can take a long time before commands begin to execute. - const uint32 maxCommandIdToSend = m_lastExecutedCommand + kCommandSendLead; - - // Calculate the cutoff time for sending (all commands that were not send before this time will be sent again) - // This assumes that the last sent time for new commands is 0 (so they will always got sent the first time) - // This situation can only happen due to the network failure since RemoteCommand layer does not require the commands to be resent. - const uint64 currentTime = gEnv->pTimer->GetAsyncTime().GetMilliSecondsAsInt64(); - const uint64 cutoffTime = currentTime - kCommandResendTime; - - std::vector< CommandRef* > commandsInPacket; // temp array - - // Process until we send all that there is to send - for (;; ) - { - // When sending connections try to merge them in larger packets. - // NOTE: this should not impact delivery time since we are not waiting - // for pending commands to accumulate before sending them, it's just an optimization - // to prevent may small messages from being sent. - uint32 packetDataSizeSoFar = 0; - { - CryAutoLock lock(m_commandAccessMutex); - - // fast local clear - // TODO: do we have a good template alternative to temporary array on stack? - packetDataSizeSoFar = 0; - commandsInPacket.resize(0); - - for (TCommands::iterator it = m_pCommands.begin(); - it != m_pCommands.end(); ++it) - { - CommandRef* commandRef = *it; - - // this command is to new, don't send it - if (commandRef->m_pCommand->GetCommandId() >= maxCommandIdToSend) - { - break; - } - - // should we send this command ? - if (commandRef->m_lastSentTime < cutoffTime) - { - // will it fit into current packet ? - const uint32 commandDataSize = commandRef->m_pCommand->GetMessage()->GetSize(); - if (packetDataSizeSoFar == 0 || // always add at least one command to the packet (no splitting) - (packetDataSizeSoFar + commandDataSize < kCommandMaxMergePacketSize)) - { - if (commandRef->m_lastSentTime == 0) - { - LOG_VERBOSE(3, "Command ID=%d is sent FIRST TIME to '%s'", - commandRef->m_pCommand->GetCommandId(), - m_pConnection->GetRemoteAddress().ToString().c_str()); - } - else - { - LOG_VERBOSE(3, "Command ID=%d is resent to '%s'", - commandRef->m_pCommand->GetCommandId(), - m_pConnection->GetRemoteAddress().ToString().c_str()); - } - - // will be sent - commandsInPacket.push_back(commandRef); - packetDataSizeSoFar += commandDataSize; - } - else - { - LOG_VERBOSE(3, "Command ID=%d is to big (%d) to fit packet size limit (%d)", - commandRef->m_pCommand->GetCommandId(), - commandDataSize, - kCommandMaxMergePacketSize); - - // no more commands will fit current packet - break; - } - } - } - } - - // No new commands to be send - if (commandsInPacket.empty()) - { - break; - } - - // Stats - LOG_VERBOSE(3, "Sending %d commands in packet, total size=%d, maxID=%d, dest: %s", - commandsInPacket.size(), - packetDataSizeSoFar, - maxCommandIdToSend, - m_pConnection->GetRemoteAddress().ToString().c_str()); - - // Estimate the size of the network packet - const uint32 messageDataSize = packetDataSizeSoFar + PackedHeader::kSerializationSize; - - // Allocate and fill the message buffer - IServiceNetworkMessage* pSendMsg = gEnv->pServiceNetwork->AllocMessageBuffer(messageDataSize); - if (NULL != pSendMsg) - { - CDataWriteStreamToMessage writer(pSendMsg); - - // Packet header - PackedHeader header; - header.magic = PackedHeader::kMagic; - header.msgType = PackedHeader::eCommand_Command; - header.count = commandsInPacket.size(); // number commands to send in this packet - writer << header; - - // Merge data of single commands - for (size_t i = 0; i < commandsInPacket.size(); ++i) - { - const IServiceNetworkMessage* pCommandMsg = commandsInPacket[i]->m_pCommand->GetMessage(); - writer.Write(pCommandMsg->GetPointer(), pCommandMsg->GetSize()); - } - - // Schedule the packet for sending via our network connection - if (m_pConnection->SendMsg(pSendMsg)) - { - // Only after the network layer has accepted our message we can assume that the commands were sent - for (size_t i = 0; i < commandsInPacket.size(); ++i) - { - CommandRef* cmdRef = commandsInPacket[i]; - cmdRef->m_lastSentTime = currentTime; - } - - // Release temporary message memory - pSendMsg->Release(); - } - else - { - // We failed to send the message (possibly the send queue is full) - pSendMsg->Release(); - break; - } - } - else - { - // No message was created, stop sending - break; - } - } - } - - // Keep the connection alive - return true; -} - -bool CRemoteCommandClient::Connection::IsAlive() const -{ - return (NULL != m_pConnection) && (m_pConnection->IsAlive()); -} - -const ServiceNetworkAddress& CRemoteCommandClient::Connection::GetRemoteAddress() const -{ - return m_remoteAddress; -} - -void CRemoteCommandClient::Connection::Close(bool bFlushQueueBeforeClosing /*= false*/) -{ - // Close the connection - if (NULL != m_pConnection) - { - if (m_pConnection->IsAlive() && bFlushQueueBeforeClosing) - { - // We have a chance to send a graceful disconnect message, so send it - SendDisconnectMessage(); - - // Send all the messages from the send queue before closing this connection. - // This does not block current thread. - m_pConnection->FlushAndClose(IServiceNetworkConnection::kDefaultFlushTime); - } - else - { - // Just close the connection (hasher way) - m_pConnection->Close(); - } - } -} - -bool CRemoteCommandClient::Connection::SendRawMessage(IServiceNetworkMessage* pMessage) -{ - // We can send the raw messages right away - if (NULL != m_pConnection && m_pConnection->IsAlive()) - { - return m_pConnection->SendMsg(pMessage); - } - else - { - return false; - } -} - -IServiceNetworkMessage* CRemoteCommandClient::Connection::ReceiveRawMessage() -{ - return m_pRawMessages.pop(); -} - -void CRemoteCommandClient::Connection::AddRef() -{ - CryInterlockedIncrement(&m_refCount); -} - -void CRemoteCommandClient::Connection::Release() -{ - if (0 == CryInterlockedDecrement(&m_refCount)) - { - delete this; - } -} - -//----------------------------------------------------------------------------- - -CRemoteCommandClient::CRemoteCommandClient(CRemoteCommandManager* pManager) - : m_pManager(pManager) - , m_commandId(0) - , m_bCloseThread(false) -{ - // Start processing thread (sending, etc) - m_pThread = new TRemoteClientThread(); - m_pThread->Start(*this); -} - -CRemoteCommandClient::~CRemoteCommandClient() -{ - // Stop the thread - if (NULL != m_pThread) - { - m_pThread->Cancel(); - m_pThread->Stop(); - m_pThread->WaitForThread(); - delete m_pThread; - } - - // Delete connections - for (size_t i = 0; i < m_pConnections.size(); ++i) - { - m_pConnections[i]->Release(); - } - m_pConnections.clear(); -} - -void CRemoteCommandClient::Delete() -{ - delete this; -} - -IRemoteCommandConnection* CRemoteCommandClient::ConnectToServer(const class ServiceNetworkAddress& serverAddress) -{ - CryAutoLock< CryMutex > lock(m_accessMutex); - - // Do not connect twice to the same server - for (TConnections::const_iterator it = m_pConnections.begin(); - it != m_pConnections.end(); ++it) - { - if (ServiceNetworkAddress::CompareBaseAddress((*it)->GetRemoteAddress(), serverAddress)) - { - LOG_VERBOSE(0, "Failed to connect to server '%s': already connected", - serverAddress.ToString().c_str()); - - return NULL; - } - } - - // Open a network connection - IServiceNetworkConnection* pNetConnection = gEnv->pServiceNetwork->Connect(serverAddress); - if (NULL == pNetConnection) - { - LOG_VERBOSE(0, "Failed to connect to server '%s': server is not responding", - serverAddress.ToString().c_str()); - - return NULL; - } - - // Get current command ID (only commands after this one will be sent) - const uint32 firstCommandId = m_commandId; - - // Create a wrapping class and add it to the connection list - Connection* pConnection = new Connection(GetManager(), pNetConnection, firstCommandId); - m_pConnections.push_back(pConnection); - - // Keep internal reference - pConnection->AddRef(); - - LOG_VERBOSE(0, "Connected to remote command server '%s', first command ID=%d", - serverAddress.ToString().c_str(), - firstCommandId); - - return pConnection; -} - -bool CRemoteCommandClient::Schedule(const IRemoteCommand& command) -{ - // No connections - if (m_pConnections.empty()) - { - return false; - } - - // Find ClassID for command - uint32 classId = 0; - if (!GetManager()->FindClassId(command.GetClass(), classId)) - { - LOG_VERBOSE(0, "Class '%s' not recognized. Did you call RegisterClass() ?", - command.GetClass()->GetName()); - - return false; - } - - // Alloc new command ID and compile command data - // TODO: consider moving the compilation to thread (this may be unsafe). - const uint32 commandId = CryInterlockedIncrement((volatile int*) &m_commandId); - Command* pCommand = Command::Compile(command, commandId, classId); - - // Register new command in all of the existing server connections - if (NULL != pCommand) - { - CryAutoLock lock(m_accessMutex); - - for (TConnections::const_iterator it = m_pConnections.begin(); - it != m_pConnections.end(); ++it) - { - (*it)->AddToSendQueue(pCommand); - } - - // We are done with our reference - pCommand->Release(); - } - - // Signal the thread to process data - m_threadEvent.Set(); - return true; -} - -void CRemoteCommandClient::Run() -{ - TConnections pUpdateList; - - CryThreadSetName(-1, "RemoteCommandThread"); - - while (!m_bCloseThread) - { - // copy to local list for updating - { - CryAutoLock lock(m_accessMutex); - pUpdateList = m_pConnections; - } - - // update current connection list - for (TConnections::const_iterator it = pUpdateList.begin(); - it != pUpdateList.end(); ++it) - { - if (!(*it)->Update()) - { - CryAutoLock lock(m_accessMutex); - m_pConnectionsToDelete.push_back(*it); - } - } - - // delete pending connections - { - CryAutoLock lock(m_accessMutex); - for (TConnections::iterator it = m_pConnectionsToDelete.begin(); - it != m_pConnectionsToDelete.end(); ++it) - { - // delete the object - (*it)->Release(); - (*it)->Close(true); - - // remove from connection list - TConnections::iterator jt = std::find(m_pConnections.begin(), m_pConnections.end(), *it); - if (jt != m_pConnections.end()) - { - m_pConnections.erase(jt); - } - } - - // reset the array - m_pConnectionsToDelete.clear(); - } - - // Limit the CPU usage - const uint32 maxWaitTime = 100; - m_threadEvent.Wait(maxWaitTime); - } -} - -void CRemoteCommandClient::Cancel() -{ - m_bCloseThread = true; -} - -//----------------------------------------------------------------------------- - -// Do not remove (can mess up the uber file builds) -#undef LOG_VERBOSE - -//----------------------------------------------------------------------------- diff --git a/Code/CryEngine/CrySystem/RemoteCommandHelpers.cpp b/Code/CryEngine/CrySystem/RemoteCommandHelpers.cpp deleted file mode 100644 index 6857a9a31c..0000000000 --- a/Code/CryEngine/CrySystem/RemoteCommandHelpers.cpp +++ /dev/null @@ -1,361 +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 : Helper classes for remote command system - - -#include "CrySystem_precompiled.h" -#include "IServiceNetwork.h" -#include "RemoteCommandHelpers.h" - -//----------------------------------------------------------------------------- - -CDataReadStreamFormMessage::CDataReadStreamFormMessage(const IServiceNetworkMessage* message) - : m_pMessage(message) - , m_size(message->GetSize()) - , m_pData(static_cast(message->GetPointer())) - , m_offset(0) -{ - // AddRef() is not const unfortunatelly - const_cast(m_pMessage)->AddRef(); -} - -CDataReadStreamFormMessage::~CDataReadStreamFormMessage() -{ - // Release() is not const unfortunatelly - const_cast(m_pMessage)->Release(); -} - -void CDataReadStreamFormMessage::Delete() -{ - delete this; -} - -void CDataReadStreamFormMessage::Skip(const uint32 size) -{ - CRY_ASSERT(m_offset + size < m_size); - m_offset += size; -} - -void CDataReadStreamFormMessage::Read(void* pData, const uint32 size) -{ - CRY_ASSERT(m_offset + size < m_size); - const char* pReadPtr = m_pData + m_offset; - memcpy(pData, pReadPtr, size); - m_offset += size; -} - -void CDataReadStreamFormMessage::Read8(void* pData) -{ - // it does not actually matter if its uint64, int64 or double so use any - ReadType(pData); -} - -void CDataReadStreamFormMessage::Read4(void* pData) -{ - // it does not actually matter if its uint32, int32 or float so use any - ReadType(pData); -} - -void CDataReadStreamFormMessage::Read2(void* pData) -{ - // it does not actually matter if its uint16, int16 so use any - ReadType(pData); -} - -void CDataReadStreamFormMessage::Read1(void* pData) -{ - // it does not actually matter if its uint8, int8 so use any - ReadType(pData); -} - -const void* CDataReadStreamFormMessage::GetPointer() -{ - const char* pReadPtr = m_pData + m_offset; - return pReadPtr; -} - -//----------------------------------------------------------------------------- - -CDataWriteStreamToMessage::CDataWriteStreamToMessage(IServiceNetworkMessage* pMessage) - : m_pMessage(pMessage) - , m_size(pMessage->GetSize()) - , m_pData(static_cast(pMessage->GetPointer())) - , m_offset(0) -{ - m_pMessage->AddRef(); -} - -CDataWriteStreamToMessage::~CDataWriteStreamToMessage() -{ - m_pMessage->Release(); -} - -void CDataWriteStreamToMessage::Delete() -{ - delete this; -} - -const uint32 CDataWriteStreamToMessage::GetSize() const -{ - return m_size; -} - -void CDataWriteStreamToMessage::CopyToBuffer(void* pData) const -{ - memcpy(pData, m_pData, m_size); -} - -IServiceNetworkMessage* CDataWriteStreamToMessage::BuildMessage() const -{ - m_pMessage->AddRef(); - return m_pMessage; -} - -void CDataWriteStreamToMessage::Write(const void* pData, const uint32 size) -{ - CRY_ASSERT(m_offset + size < m_size); - memcpy((char*)m_pData + m_offset, pData, size); - m_offset += size; -} - -void CDataWriteStreamToMessage::Write8(const void* pData) -{ - // it does not actually matter if its uint64, int64 or double so use any - WriteType(pData); -} - -void CDataWriteStreamToMessage::Write4(const void* pData) -{ - // it does not actually matter if its uint32, int32 or float so use any - WriteType(pData); -} - -void CDataWriteStreamToMessage::Write2(const void* pData) -{ - // it does not actually matter if its uint16, int16 so use any - WriteType(pData); -} - -void CDataWriteStreamToMessage::Write1(const void* pData) -{ - // it does not actually matter if its uint8, int8 so use any - WriteType(pData); -} - -//----------------------------------------------------------------------------- - -CDataReadStreamMemoryBuffer::CDataReadStreamMemoryBuffer(const void* pData, const uint32 size) - : m_size(size) - , m_offset(0) -{ - m_pData = new uint8 [size]; - memcpy(m_pData, pData, size); -} - -CDataReadStreamMemoryBuffer::~CDataReadStreamMemoryBuffer() -{ - delete [] m_pData; - m_pData = NULL; -} - -void CDataReadStreamMemoryBuffer::Delete() -{ - delete this; -} - -void CDataReadStreamMemoryBuffer::Skip(const uint32 size) -{ - CRY_ASSERT(m_offset + size <= m_size); - m_offset += size; -} - -void CDataReadStreamMemoryBuffer::Read8(void* pData) -{ - Read(pData, 8); - SwapEndian(*reinterpret_cast(pData)); -} - -void CDataReadStreamMemoryBuffer::Read4(void* pData) -{ - Read(pData, 4); - SwapEndian(*reinterpret_cast(pData)); -} - -void CDataReadStreamMemoryBuffer::Read2(void* pData) -{ - Read(pData, 2); - SwapEndian(*reinterpret_cast(pData)); -} - -void CDataReadStreamMemoryBuffer::Read1(void* pData) -{ - return Read(pData, 1); -} - -const void* CDataReadStreamMemoryBuffer::GetPointer() -{ - return m_pData + m_offset; -}; - -void CDataReadStreamMemoryBuffer::Read(void* pData, const uint32 size) -{ - CRY_ASSERT(m_offset + size <= m_size); - memcpy(pData, m_pData + m_offset, size); - m_offset += size; -} - -//----------------------------------------------------------------------------- - -CDataWriteStreamBuffer::CDataWriteStreamBuffer() - : m_size(0) -{ - // Start with the initial (preallocated) partition - // This optimization assumes that initial size of most of the messages will be small. - // NOTE: default partition is not added to the partition table (that would require push_backs to vector) - char* partitionMemory = &m_defaultPartition[0]; - m_pCurrentPointer = partitionMemory; - m_leftInPartition = sizeof(m_defaultPartition); -} - -CDataWriteStreamBuffer::~CDataWriteStreamBuffer() -{ - // Free all memory partitions that were allocated dynamically - for (size_t i = 0; i < m_pPartitions.size(); ++i) - { - CryModuleFree(m_pPartitions[i]); - } -} - -void CDataWriteStreamBuffer::Delete() -{ - delete this; -} - -const uint32 CDataWriteStreamBuffer::GetSize() const -{ - return m_size; -} - -void CDataWriteStreamBuffer::CopyToBuffer(void* pData) const -{ - uint32 dataLeft = m_size; - char* pWritePtr = (char*)pData; - - // Copy data from default (preallocated) partition - { - const uint32 partitionSize = sizeof(m_defaultPartition); - const uint32 dataToCopy = min(partitionSize, dataLeft); - memcpy(pWritePtr, &m_defaultPartition[0], dataToCopy); - - // advance - pWritePtr += dataToCopy; - dataLeft -= dataToCopy; - } - - // Copy data from dynamic partitions - for (uint32 i = 0; i < m_pPartitions.size(); ++i) - { - // get size of data to copy - const uint32 partitionSize = m_partitionSizes[i]; - const uint32 dataToCopy = min(partitionSize, dataLeft); - memcpy(pWritePtr, m_pPartitions[i], dataToCopy); - - // advance - pWritePtr += dataToCopy; - dataLeft -= dataToCopy; - } - - // Make sure all data was written - CRY_ASSERT(dataLeft == 0); -} - -IServiceNetworkMessage* CDataWriteStreamBuffer::BuildMessage() const -{ - // No data written, no message created - if (0 == m_size) - { - return NULL; - } - - // Create message to hold all the data - IServiceNetworkMessage* pMessage = gEnv->pServiceNetwork->AllocMessageBuffer(m_size); - if (NULL == pMessage) - { - return NULL; - } - - // Copy data to messages - CopyToBuffer(pMessage->GetPointer()); - return pMessage; -} - -void CDataWriteStreamBuffer::Write(const void* pData, const uint32 size) -{ - static const uint32 kAdditionalPartitionSize = 65536; - - uint32 dataLeft = size; - while (dataLeft > 0) - { - // new partition needed - if (m_leftInPartition == 0) - { - // Allocate new partition data - char* partitionMemory = (char*)CryModuleMalloc(kAdditionalPartitionSize); - CRY_ASSERT(partitionMemory != NULL); - - // add new partition to list - m_partitionSizes.push_back(kAdditionalPartitionSize); - m_pPartitions.push_back(partitionMemory); - m_pCurrentPointer = partitionMemory; - m_leftInPartition = kAdditionalPartitionSize; - } - - // how many bytes can we write to current partition ? - const uint32 maxToWrite = min(m_leftInPartition, dataLeft); - memcpy(m_pCurrentPointer, pData, maxToWrite); - - // advance - m_size += maxToWrite; - dataLeft -= maxToWrite; - pData = (const char*)pData + maxToWrite; - m_pCurrentPointer += maxToWrite; - m_leftInPartition -= maxToWrite; - } -} - -void CDataWriteStreamBuffer::Write8(const void* pData) -{ - // it does not actually matter if its uint64, int64 or double so use any - WriteType(pData); -} - -void CDataWriteStreamBuffer::Write4(const void* pData) -{ - // it does not actually matter if its uint32, int32 or float so use any - WriteType(pData); -} - -void CDataWriteStreamBuffer::Write2(const void* pData) -{ - // it does not actually matter if its uint16, int16 so use any - WriteType(pData); -} - -void CDataWriteStreamBuffer::Write1(const void* pData) -{ - // it does not actually matter if its uint8, int8 so use any - WriteType(pData); -} - -//----------------------------------------------------------------------------- diff --git a/Code/CryEngine/CrySystem/RemoteCommandHelpers.h b/Code/CryEngine/CrySystem/RemoteCommandHelpers.h deleted file mode 100644 index 948097db22..0000000000 --- a/Code/CryEngine/CrySystem/RemoteCommandHelpers.h +++ /dev/null @@ -1,307 +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 : Remote command system helper classes - - -#ifndef CRYINCLUDE_CRYSYSTEM_REMOTECOMMANDHELPERS_H -#define CRYINCLUDE_CRYSYSTEM_REMOTECOMMANDHELPERS_H -#pragma once - - -//------------------------------------------------------------------------ - -#include "IRemoteCommand.h" - -struct IServiceNetworkMessage; - -//------------------------------------------------------------------------ - -// Stream reader for service network message -// Implements automatic byte swapping -class CDataReadStreamFormMessage - : public IDataReadStream -{ -private: - const IServiceNetworkMessage* m_pMessage; - const char* m_pData; - uint32 m_offset; - uint32 m_size; - -private: - template - ILINE void ReadType(void* pData) - { - CRY_ASSERT(m_offset + sizeof(T) < m_size); - const T& readPos = *reinterpret_cast(m_pData + m_offset); - *reinterpret_cast(pData) = readPos; - SwapEndian(*reinterpret_cast(pData)); - m_offset += sizeof(T); - } - -public: - CDataReadStreamFormMessage(const IServiceNetworkMessage* message); - virtual ~CDataReadStreamFormMessage(); - - const uint32 GetOffset() const - { - return m_offset; - } - - void SetPosition(uint32 offset) - { - m_offset = offset; - } - -public: - // IDataReadStream interface - virtual void Delete(); - virtual void Skip(const uint32 size); - virtual void Read(void* pData, const uint32 size); - virtual void Read8(void* pData); - virtual void Read4(void* pData); - virtual void Read2(void* pData); - virtual void Read1(void* pData); - virtual const void* GetPointer(); -}; - -//------------------------------------------------------------------------ - -// Stream writer that writes into the service network message -class CDataWriteStreamToMessage - : public IDataWriteStream -{ -private: - IServiceNetworkMessage* m_pMessage; - char* m_pData; - uint32 m_offset; - uint32 m_size; - -private: - template - ILINE void WriteType(const void* pData) - { - CRY_ASSERT(m_offset + sizeof(T) < m_size); - T& writePos = *reinterpret_cast(m_pData + m_offset); - writePos = *reinterpret_cast(pData); - SwapEndian(writePos); - m_offset += sizeof(T); - } - -public: - CDataWriteStreamToMessage(IServiceNetworkMessage* pMessage); - virtual ~CDataWriteStreamToMessage(); - - // IDataWriteStream interface implementation - virtual void Delete(); - virtual const uint32 GetSize() const; - virtual struct IServiceNetworkMessage* BuildMessage() const; - virtual void CopyToBuffer(void* pData) const; - virtual void Write(const void* pData, const uint32 size); - virtual void Write8(const void* pData); - virtual void Write4(const void* pData); - virtual void Write2(const void* pData); - virtual void Write1(const void* pData); -}; - -//------------------------------------------------------------------------ - -/// Stream reader reading from owner memory buffer -class CDataReadStreamMemoryBuffer - : public IDataReadStream -{ -private: - const uint32 m_size; - uint8* m_pData; - uint32 m_offset; - -public: - // memory is copied! - CDataReadStreamMemoryBuffer(const void* pData, const uint32 size); - virtual ~CDataReadStreamMemoryBuffer(); - - virtual void Delete(); - virtual void Skip(const uint32 size); - virtual void Read8(void* pData); - virtual void Read4(void* pData); - virtual void Read2(void* pData); - virtual void Read1(void* pData); - virtual const void* GetPointer(); - virtual void Read(void* pData, const uint32 size); -}; - -//------------------------------------------------------------------------ - -// Stream writer that writes into the internal memory buffer -class CDataWriteStreamBuffer - : public IDataWriteStream -{ - static const uint32 kStaticPartitionSize = 4096; - -private: - // Default (preallocated) partition - char m_defaultPartition[ kStaticPartitionSize ]; - - // Allocated dynamic partitions - std::vector m_pPartitions; - - // Size of the dynamic message partitions - std::vector m_partitionSizes; - - // Pointer to current writing position in the current partition - char* m_pCurrentPointer; - - // Space left in current partition - uint32 m_leftInPartition; - - // Total message size so far - uint32 m_size; - -private: - // Directly write typed data into the stream - template - ILINE void WriteType(const void* pData) - { - // try to use the faster path if we are not crossing the partition boundary - if (m_leftInPartition >= sizeof(T)) - { - // faster case - T& writePos = *reinterpret_cast(m_pCurrentPointer); - writePos = *reinterpret_cast(pData); - SwapEndian(writePos); - m_pCurrentPointer += sizeof(T); - m_leftInPartition -= sizeof(T); - m_size += sizeof(T); - } - else - { - // slower case (more generic) - T tempVal(*reinterpret_cast(pData)); - SwapEndian(tempVal); - Write(&tempVal, sizeof(tempVal)); - } - } - -public: - CDataWriteStreamBuffer(); - virtual ~CDataWriteStreamBuffer(); - - // IDataWriteStream interface implementation - virtual void Delete(); - virtual const uint32 GetSize() const; - virtual IServiceNetworkMessage* BuildMessage() const; - virtual void CopyToBuffer(void* pData) const; - virtual void Write(const void* pData, const uint32 size); - virtual void Write8(const void* pData); - virtual void Write4(const void* pData); - virtual void Write2(const void* pData); - virtual void Write1(const void* pData); -}; - -//----------------------------------------------------------------------------- - -// Packet header -struct PackedHeader -{ - // Estimation (or better yet, exact value) of how much data this header will take when written. - // Please make sure that actual size after serialization is not bigger than this value. - static const uint32 kSerializationSize = sizeof(uint8) + sizeof(uint32) + sizeof(uint32); - - // Magic value that identifies command messages vs raw messages - static const uint32 kMagic = 0xABBAF00D; - - // Command type - // Keep the values unchanged as this may break the protocol - enum ECommand - { - // Server class list mapping - eCommand_ClassList = 0, - - // Command data - eCommand_Command = 1, - - // Disconnect signal - eCommand_Disconnect = 2, - - // ACK packet - eCommand_ACK = 3, - }; - - uint32 magic; - uint8 msgType; - uint32 count; - - // serialization operator - template< class T > - friend T& operator<<(T& stream, PackedHeader& header) - { - stream << header.magic; - stream << header.msgType; - stream << header.count; - return stream; - } -}; - -// Header sent with every command -struct CommandHeader -{ - uint32 commandId; - uint32 classId; - uint32 size; - - CommandHeader() - : commandId(0) - , classId(0) - , size(0) - {} - - // serialization operator - template< class T > - friend T& operator<<(T& stream, CommandHeader& header) - { - stream << header.commandId; - stream << header.classId; - stream << header.size; - return stream; - } -}; - -// General Response/ACK header -struct ResponseHeader -{ - uint32 magic; - uint8 msgType; - uint32 lastCommandReceived; - uint32 lastCommandExecuted; - - ResponseHeader() - : lastCommandReceived(0) - , lastCommandExecuted(0) - , msgType(PackedHeader::eCommand_ACK) - {} - - // serialization operator - template< class T > - friend T& operator<<(T& stream, ResponseHeader& header) - { - stream << header.magic; - stream << header.msgType; - stream << header.lastCommandReceived; - stream << header.lastCommandExecuted; - return stream; - } -}; - -//----------------------------------------------------------------------------- - -#endif // CRYINCLUDE_CRYSYSTEM_REMOTECOMMANDHELPERS_H diff --git a/Code/CryEngine/CrySystem/RemoteCommandServer.cpp b/Code/CryEngine/CrySystem/RemoteCommandServer.cpp deleted file mode 100644 index 362a9faf1a..0000000000 --- a/Code/CryEngine/CrySystem/RemoteCommandServer.cpp +++ /dev/null @@ -1,832 +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 : Remote command system implementation (server) - -#include "CrySystem_precompiled.h" -#include "IServiceNetwork.h" -#include "RemoteCommand.h" -#include "RemoteCommandHelpers.h" - -//----------------------------------------------------------------------------- - -// remote system internal logging -#ifdef RELEASE -#define LOG_VERBOSE(level, txt, ...) -#else -#define LOG_VERBOSE(level, txt, ...) if (GetManager()->CheckVerbose(level)) { GetManager()->Log(txt, __VA_ARGS__); } -#endif - -//----------------------------------------------------------------------------- - -CRemoteCommandServer::WrappedCommand::WrappedCommand(IRemoteCommand* pCommand, const uint32 commandId) - : m_pCommand(pCommand) - , m_refCount(1) - , m_commandID(commandId) -{ -} - -CRemoteCommandServer::WrappedCommand::~WrappedCommand() -{ - CRY_ASSERT(m_refCount == 0); - m_pCommand->Delete(); -} - -void CRemoteCommandServer::WrappedCommand::AddRef() -{ - CryInterlockedIncrement(&m_refCount); -} - -void CRemoteCommandServer::WrappedCommand::Release() -{ - if (0 == CryInterlockedDecrement(&m_refCount)) - { - delete this; - } -} - -//----------------------------------------------------------------------------- - -CRemoteCommandServer::Endpoint::Endpoint(CRemoteCommandManager* pManager, class CRemoteCommandServer* pServer, IServiceNetworkConnection* pConnection) - : m_pConnection(pConnection) - , m_pManager(pManager) - , m_pServer(pServer) - , m_lastReceivedCommand(0) - , m_lastExecutedCommand(0) - , m_lastReceivedCommandACKed(0) - , m_lastExecutedCommandACKed(0) - , m_bHasReceivedClassList(false) -{ -} - -CRemoteCommandServer::Endpoint::~Endpoint() -{ - // release commands that were not yet executed - // this will release the command memory buffers (if they are not referenced elsewhere) - while (!m_pCommandsToExecute.empty()) - { - WrappedCommand* pCommand = m_pCommandsToExecute.pop(); - pCommand->Release(); - } - - // make sure the network connection is closed - if (NULL != m_pConnection) - { - // send the disconnect message - { - CDataWriteStreamBuffer writer; - - // format messages - PackedHeader header; - header.magic = PackedHeader::kMagic; - header.msgType = PackedHeader::eCommand_Disconnect; - header.count = 0; - writer << header; - - // Send the message - IServiceNetworkMessage* pMessage = writer.BuildMessage(); - if (NULL != pMessage) - { - m_pConnection->SendMsg(pMessage); - pMessage->Release(); - } - } - - // close the connection (but try to send messages out) - m_pConnection->FlushAndClose(IServiceNetworkConnection::kDefaultFlushTime); - m_pConnection->Release(); - m_pConnection = NULL; - } -} - -const char* CRemoteCommandServer::Endpoint::GetClassName(const uint32 classId) const -{ - // class index is out of bounds - if (classId >= m_pLocalClassFactories.size()) - { - return "InvalidClassID"; - } - - // get class factory for the class ID - IRemoteCommandClass* theClass = m_pLocalClassFactories[ classId ]; - if (NULL == theClass) - { - // ID is valid but we do not support this class - // Can happen, usually due to version mismatch between client and server binaries - return "UnsupportedClassID"; - } - - return theClass->GetName(); -} - -IRemoteCommand* CRemoteCommandServer::Endpoint::CreateObject(const uint32 classId) const -{ - // class index is out of bounds - if (classId >= m_pLocalClassFactories.size()) - { - return NULL; - } - - // get class factory for given class index - IRemoteCommandClass* theClass = m_pLocalClassFactories[ classId ]; - if (NULL == theClass) - { - // ID is valid but we do not support this class - // Can happen, usually due to version mismatch between client and server binaries - return NULL; - } - - // use the class definition to create the instance of the remote command object - return theClass->CreateObject(); -} - -void CRemoteCommandServer::Endpoint::Execute() -{ - uint32 idOfLastExecutedCommand = 0; - - // Process the commands on the execution list - while (!m_pCommandsToExecute.empty()) - { - // Pop the command from the stack - WrappedCommand* pCommand = m_pCommandsToExecute.pop(); - - LOG_VERBOSE(3, "Executing command '%s', ID %d", - pCommand->GetCommand()->GetClass()->GetName(), - pCommand->GetId()); - - // Here is where the magic happens - { - pCommand->GetCommand()->Execute(); - } - - // Keep track of the command ID executed so far (so we can update the ACK later) - CRY_ASSERT(pCommand->GetId() > idOfLastExecutedCommand); - idOfLastExecutedCommand = pCommand->GetId(); - - // Command was executed, we can release it - pCommand->Release(); - } - - // Update the ACK data (if it's needed) - if (idOfLastExecutedCommand != 0) - { - CryAutoLock lock(m_accessLock); - - LOG_VERBOSE(3, "Updating LastExecutedCommandID %d->%d", - m_lastExecutedCommand, - idOfLastExecutedCommand); - - // Well, it only makes sens if the current command ID is greater that the last one executed - CRY_ASSERT(idOfLastExecutedCommand > m_lastExecutedCommand); - if (idOfLastExecutedCommand > m_lastExecutedCommand) - { - m_lastExecutedCommand = idOfLastExecutedCommand; - } - } -} - -bool CRemoteCommandServer::Endpoint::Update() -{ - // Check connection status - if (!m_pConnection->IsAlive()) - { - // Signal the owner that this endpoint should be deleted - return false; - } - - // Receive and deserialize the commands - // Note that this is done asynchronously so commands can be decoded even if the main thread is busy - // Note that execution is DEFERRED to the main thread (I wouldn't risk doing it from this thread ;-)) - bool bDisconnectReceived = false; - IServiceNetworkMessage* pMsg = m_pConnection->ReceiveMsg(); - while (NULL != pMsg && !bDisconnectReceived) - { - CDataReadStreamFormMessage reader(pMsg); - - // read back the packet header - PackedHeader packetHeader; - reader << packetHeader; - - // Is this a command system messages ? - if (packetHeader.magic == PackedHeader::kMagic) - { - switch (packetHeader.msgType) - { - // Class list, usually sent as first thing after connection - case PackedHeader::eCommand_ClassList: - { - // deserialize class names - std::vector< string > classNames; - reader << classNames; - - // sync the command ID to the current value on the client - const uint32 firstCommandID = packetHeader.count; - m_lastExecutedCommand = firstCommandID; - m_lastExecutedCommandACKed = firstCommandID; - m_lastReceivedCommand = firstCommandID; - m_lastReceivedCommandACKed = firstCommandID; - m_bHasReceivedClassList = true; - - LOG_VERBOSE(3, "Received class list packet, count=%d, first message=%d from '%s'", - classNames.size(), - packetHeader.count, - m_pConnection->GetRemoteAddress().ToString().c_str()); - - // create class mapping between remote client and this server - GetManager()->BuildClassMapping(classNames, m_pLocalClassFactories); - break; - } - - // Actual command packets - case PackedHeader::eCommand_Command: - { - LOG_VERBOSE(3, "Received packet, count=%d from '%s'", - packetHeader.count, - m_pConnection->GetRemoteAddress().ToString().c_str()); - - // load the serialized commands - const uint32 numCommands = packetHeader.count; - for (uint32 i = 0; i < numCommands; ++i) - { - // Each command is prefixed with header - CommandHeader header; - reader << header; - - // We must be able to skip to the end of the command data because sometimes - // some data can be omitted - either by dropping the command altogether or - // by faulty deserialization. Don't trust the user. - const uint32 offset = reader.GetOffset(); - const uint32 endOffset = offset + header.size; // here is where we can skip - - LOG_VERBOSE(3, "Received command ID=%d (class id=%d, size=%d) from '%s'", - header.commandId, - header.classId, - header.size, - m_pConnection->GetRemoteAddress().ToString().c_str()); - - // Do not process commands out of order. - // This should not happen if network is in good health, but we cannot assume that, never-ever. - // This code will cause our side to stop executing new commands until the remote side to resend the missing ones. - // Typically it is better than executing commands out of order. - const uint32 expectedNextCommand = m_lastReceivedCommand + 1; - if (header.commandId > expectedNextCommand) - { - LOG_VERBOSE(0, "Out of order command ID (%d > %d) received from '%s'", - header.commandId, - expectedNextCommand, - m_pConnection->GetRemoteAddress().ToString().c_str()); - - // next commands will be even older, no need to check them - break; - } - - // Do not process the old commands - // This may happen pretty often when command is resent while the ACK is "in-flight" - // Just drop the data and go on. - if (header.commandId <= m_lastReceivedCommand) - { - // getting old command is not an error, it just means that we have large enough lag - // that the client started resending old commands. - LOG_VERBOSE(1, "Old command (%d <= %d) received from '%s'", - header.commandId, - m_lastReceivedCommand, - m_pConnection->GetRemoteAddress().ToString().c_str()); - } - else - { - // next command received, we are very strict about matchig the command IDs here - CRY_ASSERT(header.commandId == expectedNextCommand); - m_lastReceivedCommand = expectedNextCommand; - - // create the command - IRemoteCommand* pCommand = CreateObject(header.classId); - if (NULL != pCommand) - { - // Fine-grain logging - LOG_VERBOSE(3, "Received command '%s', classId=%d, commandId=%d from '%s'", - pCommand->GetClass()->GetName(), - header.classId, - header.commandId, - m_pConnection->GetRemoteAddress().ToString().c_str()); - - // Deserialize the command data from network message - pCommand->LoadFromStream(reader); - - // Add to list of commands to execute - { - m_pCommandsToExecute.push(new WrappedCommand(pCommand, header.commandId)); - } - } - else - { - LOG_VERBOSE(0, "ClassId %d not recognized. Skipping command ID%d from '%s'", - header.classId, - header.commandId, - m_pConnection->GetRemoteAddress().ToString().c_str()); - } - - // Update the last command ID - m_lastReceivedCommand = header.commandId; - } - - // Sync the message stream to popper position - CRY_ASSERT(reader.GetOffset() <= endOffset); - reader.SetPosition(endOffset); - } - - break; - } - - // request to disconnect (graceful) - case PackedHeader::eCommand_Disconnect: - { - LOG_VERBOSE(3, "Received disconnect request from '%s'", - m_pConnection->GetRemoteAddress().ToString().c_str()); - - m_pConnection->Close(); - bDisconnectReceived = true; - - break; - } - - // should not happen - default: - { - LOG_VERBOSE(0, "Invalid message type '%s' received from '%s'", - packetHeader.msgType, - m_pConnection->GetRemoteAddress().ToString().c_str()); - - break; - } - } - } - else - { - // This is a raw message, try to process immediately using async listeners. - // If it fails, add to the queue for processing on the main thread by sync listeners. - m_pServer->ProcessRawMessageAsync(pMsg, m_pConnection); - } - - // Release the message data - pMsg->Release(); - - // Get the next message from network - if (!bDisconnectReceived) - { - pMsg = m_pConnection->ReceiveMsg(); - } - } - - // The value of lastExecutedCommand can change outside this thread, - // so capture it one and keep it constant for the duration of the logic in this function. - const uint32 snapshotLastExecutedCommand = m_lastExecutedCommand; - - // Determine if we should send generate the ACK signal - if ((snapshotLastExecutedCommand != m_lastExecutedCommandACKed) || - (m_lastReceivedCommand != m_lastReceivedCommandACKed)) // this can - { - ResponseHeader header; - header.magic = PackedHeader::kMagic; - header.msgType = PackedHeader::eCommand_ACK; - header.lastCommandReceived = m_lastReceivedCommand; - header.lastCommandExecuted = snapshotLastExecutedCommand; // note that we use the captured values - - LOG_VERBOSE(3, "Sending ACK to '%s' with LastReceived=%d, LastExecuted=%d", - m_pConnection->GetRemoteAddress().ToString().c_str(), - header.lastCommandReceived, - header.lastCommandExecuted); - - // Write header into the message - CDataWriteStreamBuffer writer; - writer << header; - - // Extract the message - IServiceNetworkMessage* pMessage = writer.BuildMessage(); - if (NULL != pMessage) - { - // Send it back over the connection (works as ACK) - if (m_pConnection->SendMsg(pMessage)) - { - // Only after the message is accepted by the network we can assume that we have ACKed it properly - // This can still leave a possibility that this message gets eaten in the network but we will resend newer ACK - // soon enough that we don't need to bother with this. - m_lastExecutedCommandACKed = header.lastCommandExecuted; - m_lastReceivedCommandACKed = header.lastCommandReceived; - } - - pMessage->Release(); - } - } - - // Continue - return true; -} - -//----------------------------------------------------------------------------- - -CRemoteCommandServer::CRemoteCommandServer(CRemoteCommandManager* pManager, IServiceNetworkListener* pListener) - : m_pManager(pManager) - , m_pListener(pListener) - , m_bCloseThread(false) - , m_suppressionCounter(0) - , m_bIsSuppressed(false) -{ - // Start processing thread (receiving from network, deserialization, etc) - m_pThread = new TRemoteServerThread(); - m_pThread->Start(*this); -} - -CRemoteCommandServer::~CRemoteCommandServer() -{ - // Stop the thread, assumes that thread is responsive - if (NULL != m_pThread) - { - m_pThread->Cancel(); - m_pThread->Stop(); - m_pThread->WaitForThread(); - delete m_pThread; - } - - // Cleanup the clients endpoints - for (TEndpoints::const_iterator it = m_pEndpoints.begin(); - it != m_pEndpoints.end(); ++it) - { - delete (*it); - } - m_pEndpoints.clear(); - - // Cleanup the clients that were not yet deleted but are dead - for (TEndpoints::const_iterator it = m_pEndpointToDelete.begin(); - it != m_pEndpointToDelete.end(); ++it) - { - delete (*it); - } - m_pEndpointToDelete.clear(); - - // Cleanup the raw messages - while (!m_pRawMessages.empty()) - { - delete m_pRawMessages.pop(); - } - - // Properly close the listening socket - if (m_pListener != NULL) - { - m_pListener->Close(); - m_pListener->Release(); - m_pListener = NULL; - } -} - -void CRemoteCommandServer::ProcessRawMessageAsync(IServiceNetworkMessage* pMessage, IServiceNetworkConnection* pConnection) -{ - // we lock for the whole duration of the function - I think that's the safest. - // this function is being called from remote command server thread and even if it locks for a moment that's not a tragic situation. - CryAutoLock lock(m_rawMessagesLock); - - // Process the message using async listeners - bool bWasProcessed = false; - for (TRawMessageListenersAsync::const_iterator it = m_pRawListenersAsync.begin(); - it != m_pRawListenersAsync.end(); ++it) - { - CDataReadStreamFormMessage reader(pMessage); - CDataWriteStreamBuffer writer; - - // Request the listener to process this message - if ((*it)->OnRawMessageAsync(pConnection->GetRemoteAddress(), reader, writer)) - { - // Send response back using the source connection - if (writer.GetSize() > 0) - { - IServiceNetworkMessage* pNewMessage = writer.BuildMessage(); - if (NULL != pNewMessage) - { - pConnection->SendMsg(pNewMessage); - pNewMessage->Release(); - } - } - - // mark as processed - bWasProcessed = true; - break; - } - } - - // Stats - if (bWasProcessed) - { - LOG_VERBOSE(3, "Raw message from '%s', size %d ASYNC, PROCESSED", - pConnection->GetRemoteAddress().ToString().c_str(), - pMessage->GetSize()); - } - else - { - LOG_VERBOSE(3, "Raw message from '%s', size %d ASYNC, NOT PROCESSED", - pConnection->GetRemoteAddress().ToString().c_str(), - pMessage->GetSize()); - } - - // If we have sync listeners add the raw message for processing on the main thread - if (!bWasProcessed && !m_pRawListenersSync.empty()) - { - m_pRawMessages.push(new RawMessage(pConnection, pMessage)); - } -} - -void CRemoteCommandServer::ProcessRawMessagesSync() -{ - // get messages - TRawMessageListenersSync listeners; - { - CryAutoLock lock(m_rawMessagesLock); - listeners = m_pRawListenersSync; - } - - // process each message - while (!m_pRawMessages.empty()) - { - RawMessage* pMsg = m_pRawMessages.pop(); - - // Process messages only from alive connection (they could die before we got a chance to process the message) - if (pMsg && pMsg->m_pConnection->IsAlive()) - { - // Try to process by on of the listeners - bool bWasProcessed = false; - for (TRawMessageListenersSync::const_iterator jt = listeners.begin(); - jt != listeners.end(); ++jt) - { - CDataReadStreamFormMessage reader(pMsg->m_pMessage); - CDataWriteStreamBuffer writer; - - // Request the listener to process this message - if ((*jt)->OnRawMessageSync(pMsg->m_pConnection->GetRemoteAddress(), reader, writer)) - { - // Send response back using the source connection - if (writer.GetSize() > 0) - { - IServiceNetworkMessage* pMessage = writer.BuildMessage(); - if (NULL != pMessage) - { - pMsg->m_pConnection->SendMsg(pMessage); - pMessage->Release(); - } - } - - // mark as processed - bWasProcessed = true; - break; - } - } - - // Stats - if (bWasProcessed) - { - LOG_VERBOSE(3, "Raw message from '%s', size %d SYNC PROCESSED", - pMsg->m_pConnection->GetRemoteAddress().ToString().c_str(), - pMsg->m_pMessage->GetSize()); - } - else - { - LOG_VERBOSE(3, "Raw message from '%s', size %d SYNC NOT PROCESSED", - pMsg->m_pConnection->GetRemoteAddress().ToString().c_str(), - pMsg->m_pMessage->GetSize()); - } - } - - /// Cleanup - delete pMsg; - } -} - -void CRemoteCommandServer::Delete() -{ - delete this; -} - -void CRemoteCommandServer::FlushCommandQueue() -{ - // Always process raw messages, even if commands are suspended - ProcessRawMessagesSync(); - - // When the command server is suppressed externally, well, then don't execute any commands - // This is usually used when the main thread is doing some heavy stuff. - // TODO: Consider signaling the clients about this condition. - if (m_bIsSuppressed) - { - LOG_VERBOSE(4, "FlushCommandQueue: suppressed (counter=%d)", - m_suppressionCounter); - - return; - } - - // Update the endpoints from a copy of the list - { - CryAutoLock lock(m_accessLock); - m_pUpdateEndpoints = m_pEndpoints; - } - - // Execute the commands for each endpoint - for (TEndpoints::const_iterator it = m_pUpdateEndpoints.begin(); - it != m_pUpdateEndpoints.end(); ++it) - { - (*it)->Execute(); - } - - // Delete endpoints that were discarded within the thread (due to network errors) - // We couldn't do that there because we would need to lock to much inside the mutex (bad idea) - if (!m_pEndpointToDelete.empty()) - { - // TODO: consider using different CS for pDeletedEnpoints array - CryAutoLock lock(m_accessLock); - - // delete the endpoint structured (deferred) - for (size_t i = 0; i < m_pEndpointToDelete.size(); ++i) - { - delete m_pEndpointToDelete[i]; - } - - m_pEndpointToDelete.clear(); - } -} - -void CRemoteCommandServer::SuppressCommands() -{ - if (CryInterlockedIncrement(&m_suppressionCounter) > 0) - { - m_bIsSuppressed = true; - } -} - -void CRemoteCommandServer::ResumeCommands() -{ - if (CryInterlockedDecrement(&m_suppressionCounter) == 0) - { - m_bIsSuppressed = false; - } -} - -void CRemoteCommandServer::Run() -{ - TEndpoints updateList; - - CryThreadSetName(-1, "RemoteCommandThread"); - -#if defined(AZ_RESTRICTED_PLATFORM) -#include AZ_RESTRICTED_FILE(RemoteCommandServer_cpp) -#endif - - while (!m_bCloseThread) - { - // Accept new connections - { - IServiceNetworkConnection* pNewConnection = m_pListener->Accept(); - if (NULL != pNewConnection) - { - LOG_VERBOSE(2, "New endpoint created with connection '%s'", - pNewConnection->GetRemoteAddress().ToString().c_str()); - - // Create endpoint wrapper - Endpoint* pEndPoint = new Endpoint(GetManager(), this, pNewConnection); - - // Add to endpoint list - { - CryAutoLock lock(m_accessLock); - m_pEndpoints.push_back(pEndPoint); - } - } - } - - // Get the current endpoint table (for update) - { - CryAutoLock lock(m_accessLock); - updateList = m_pEndpoints; - } - - // Update endpoints - for (TEndpoints::iterator it = updateList.begin(); - it != updateList.end(); ++it) - { - Endpoint* ep = (*it); - if (!ep->Update()) - { - LOG_VERBOSE(2, "RemoteCommand endpoint '%s' closed", - ep->GetConnection()->GetRemoteAddress().ToString().c_str()); - - // remove the endpoint from the original list - { - CryAutoLock lock(m_accessLock); - - // it's safe to remove from the endpoints list - we are iterating over a copy - m_pEndpoints.erase(std::find(m_pEndpoints.begin(), m_pEndpoints.end(), ep)); - - // don't delete the endpoint structure now (it may still be executed on main thread) - // instead add it to a list that will be processed at the end of execution so this endpoint can get deleted - m_pEndpointToDelete.push_back(ep); - } - } - } - - // Limit the CPU usage - // TODO: consider using some event based mechanism since the only source of - // work for this thread is the network we can esily be triggered by that. - Sleep(5); - } -} - -void CRemoteCommandServer::Cancel() -{ - m_bCloseThread = true; -} - -void CRemoteCommandServer::RegisterSyncMessageListener(IRemoteCommandListenerSync* pListener) -{ - CryAutoLock lock(m_rawMessagesLock); - m_pRawListenersSync.push_back(pListener); -} - -void CRemoteCommandServer::UnregisterSyncMessageListener(IRemoteCommandListenerSync* pListener) -{ - CryAutoLock lock(m_rawMessagesLock); - - TRawMessageListenersSync::iterator it = std::find(m_pRawListenersSync.begin(), m_pRawListenersSync.end(), pListener); - if (it != m_pRawListenersSync.end()) - { - m_pRawListenersSync.erase(it); - } -} - -void CRemoteCommandServer::RegisterAsyncMessageListener(IRemoteCommandListenerAsync* pListener) -{ - CryAutoLock lock(m_rawMessagesLock); - m_pRawListenersAsync.push_back(pListener); -} - -void CRemoteCommandServer::UnregisterAsyncMessageListener(IRemoteCommandListenerAsync* pListener) -{ - CryAutoLock lock(m_rawMessagesLock); - - TRawMessageListenersAsync::iterator it = std::find(m_pRawListenersAsync.begin(), m_pRawListenersAsync.end(), pListener); - if (it != m_pRawListenersAsync.end()) - { - m_pRawListenersAsync.erase(it); - } -} - -void CRemoteCommandServer::Broadcast(IServiceNetworkMessage* pMessage) -{ - if (NULL != pMessage && pMessage->GetSize() > 0) - { - CryAutoLock lock(m_rawMessagesLock); - for (TEndpoints::const_iterator jt = m_pEndpoints.begin(); - jt != m_pEndpoints.end(); ++jt) - { - Endpoint* pEndpoint = (*jt); - if (pEndpoint->HasReceivedClassList()) - { - IServiceNetworkConnection* pConnection = pEndpoint->GetConnection(); - if (NULL != pConnection) - { - pConnection->SendMsg(pMessage); - } - } - } - } -} - -bool CRemoteCommandServer::HasConnectedClients() const -{ - CryAutoLock lock(m_rawMessagesLock); - - for (TEndpoints::const_iterator jt = m_pEndpoints.begin(); - jt != m_pEndpoints.end(); ++jt) - { - Endpoint* pEndpoint = (*jt); - if (pEndpoint->HasReceivedClassList()) - { - IServiceNetworkConnection* pConnection = pEndpoint->GetConnection(); - if (pConnection->IsAlive()) - { - return true; - } - } - } - - return false; -} - -//----------------------------------------------------------------------------- - -// Do not remove (can mess up the uber file builds) -#undef LOG_VERBOSE - -//----------------------------------------------------------------------------- diff --git a/Code/CryEngine/CrySystem/Serialization/ArchiveHost.cpp b/Code/CryEngine/CrySystem/Serialization/ArchiveHost.cpp deleted file mode 100644 index f7ed4ae46c..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/ArchiveHost.cpp +++ /dev/null @@ -1,239 +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 "CrySystem_precompiled.h" -#include -#include "JSONIArchive.h" -#include "JSONOArchive.h" -#include "BinArchive.h" -#include "XmlIArchive.h" -#include "XmlOArchive.h" -#include - -namespace Serialization -{ - bool LoadFile(std::vector& content, const char* filename) - { - AZ::IO::HandleType fileHandle = gEnv->pCryPak->FOpen(filename, "rb"); - if (!fileHandle) - { - return false; - } - - gEnv->pCryPak->FSeek(fileHandle, 0, SEEK_END); - size_t size = gEnv->pCryPak->FTell(fileHandle); - gEnv->pCryPak->FSeek(fileHandle, 0, SEEK_SET); - - content.resize(size); - bool result = true; - if (size != 0) - { - result = gEnv->pCryPak->FRead(&content[0], size, fileHandle) == size; - } - gEnv->pCryPak->FClose(fileHandle); - return result; - } - - class CArchiveHost - : public IArchiveHost - { - public: - bool LoadJsonFile(const SStruct& obj, const char* filename) override - { - std::vector content; - if (!LoadFile(content, filename)) - { - return false; - } - JSONIArchive ia; - if (!ia.open(content.data(), content.size())) - { - return false; - } - return ia(obj); - } - - bool SaveJsonFile(const char* gameFilename, const SStruct& obj) override - { - char buffer[AZ::IO::IArchive::MaxPath]; - const char* filename = gEnv->pCryPak->AdjustFileName(gameFilename, buffer, AZ_ARRAY_SIZE(buffer), AZ::IO::IArchive::FLAGS_FOR_WRITING); - JSONOArchive oa; - if (!oa(obj)) - { - return false; - } - return oa.save(filename); - } - - bool LoadJsonBuffer(const SStruct& obj, const char* buffer, size_t bufferLength) override - { - if (bufferLength == 0) - { - return false; - } - JSONIArchive ia; - if (!ia.open(buffer, bufferLength)) - { - return false; - } - return ia(obj); - } - - bool SaveJsonBuffer(DynArray& buffer, const SStruct& obj) override - { - JSONOArchive oa; - if (!oa(obj)) - { - return false; - } - buffer.assign(oa.buffer(), oa.buffer() + oa.length()); - return true; - } - - - bool LoadBinaryFile(const SStruct& obj, const char* filename) override - { - std::vector content; - if (!LoadFile(content, filename)) - { - return false; - } - BinIArchive ia; - if (!ia.open(content.data(), content.size())) - { - return false; - } - return ia(obj); - } - - bool SaveBinaryFile(const char* gameFilename, const SStruct& obj) override - { - char buffer[AZ::IO::IArchive::MaxPath]; - const char* filename = gEnv->pCryPak->AdjustFileName(gameFilename, buffer, AZ_ARRAY_SIZE(buffer), AZ::IO::IArchive::FLAGS_FOR_WRITING); - BinOArchive oa; - obj(oa); - return oa.save(filename); - } - - bool LoadBinaryBuffer(const SStruct& obj, const char* buffer, size_t bufferLength) override - { - if (bufferLength == 0) - { - return false; - } - BinIArchive ia; - if (!ia.open(buffer, bufferLength)) - { - return false; - } - return ia(obj); - } - - bool SaveBinaryBuffer(DynArray& buffer, const SStruct& obj) override - { - BinOArchive oa; - obj(oa); - buffer.assign(oa.buffer(), oa.buffer() + oa.length()); - return true; - } - - bool CloneBinary(const SStruct& dest, const SStruct& src) override - { - BinOArchive oa; - src(oa); - BinIArchive ia; - if (!ia.open(oa.buffer(), oa.length())) - { - return false; - } - dest(ia); - return true; - } - - bool CompareBinary(const SStruct& lhs, const SStruct& rhs) override - { - BinOArchive oa1; - lhs(oa1); - BinOArchive oa2; - rhs(oa2); - if (oa1.length() != oa2.length()) - { - return false; - } - return memcmp(oa1.buffer(), oa2.buffer(), oa1.length()) == 0; - } - - bool SaveXmlFile(const char* filename, const SStruct& obj, const char* rootNodeName) override - { - XmlNodeRef node = SaveXmlNode(obj, rootNodeName); - if (!node) - { - return false; - } - return node->saveToFile(filename); - } - - bool LoadXmlFile(const SStruct& obj, const char* filename) override - { - XmlNodeRef node = gEnv->pSystem->LoadXmlFromFile(filename); - if (!node) - { - return false; - } - return LoadXmlNode(obj, node); - } - - XmlNodeRef SaveXmlNode(const SStruct& obj, const char* nodeName) override - { - CXmlOArchive oa; - XmlNodeRef node = gEnv->pSystem->CreateXmlNode(nodeName); - if (!node) - { - return XmlNodeRef(); - } - oa.SetXmlNode(node); - if (!obj(oa)) - { - return XmlNodeRef(); - } - return oa.GetXmlNode(); - } - - bool SaveXmlNode(XmlNodeRef& node, const SStruct& obj) override - { - if (!node) - { - return false; - } - CXmlOArchive oa; - oa.SetXmlNode(node); - return obj(oa); - } - - bool LoadXmlNode(const SStruct& obj, const XmlNodeRef& node) override - { - CXmlIArchive ia; - ia.SetXmlNode(node); - if (!obj(ia)) - { - return false; - } - return true; - } - }; - - IArchiveHost* CreateArchiveHost() - { - return new CArchiveHost; - } -} diff --git a/Code/CryEngine/CrySystem/Serialization/ArchiveHost.h b/Code/CryEngine/CrySystem/Serialization/ArchiveHost.h deleted file mode 100644 index 360dded0c7..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/ArchiveHost.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include - -namespace Serialization -{ - IArchiveHost* CreateArchiveHost(); -} diff --git a/Code/CryEngine/CrySystem/Serialization/BinArchive.cpp b/Code/CryEngine/CrySystem/Serialization/BinArchive.cpp deleted file mode 100644 index f16c15cc96..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/BinArchive.cpp +++ /dev/null @@ -1,839 +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 "CrySystem_precompiled.h" -#include "BinArchive.h" -#include -#include "Serialization/ClassFactory.h" - -namespace Serialization { - static const unsigned char SIZE16 = 254; - static const unsigned char SIZE32 = 255; - - static const unsigned int BIN_MAGIC = 0xb1a4c17f; - - //#ifdef _DEBUG - //typedef std::map HashMap; - //static HashMap hashMap; - //#endif - - BinOArchive::BinOArchive() - : IArchive(OUTPUT | BINARY) - { - clear(); - } - - void BinOArchive::clear() - { - stream_.clear(); - stream_.write((const char*)&BIN_MAGIC, sizeof(BIN_MAGIC)); - } - - size_t BinOArchive::length() const - { - return stream_.position(); - } - - bool BinOArchive::save(const char* filename) - { - FILE* f = nullptr; - azfopen(&f, filename, "wb"); - if (!f) - { - return false; - } - - if (fwrite(buffer(), 1, length(), f) != length()) - { - fclose(f); - return false; - } - - fclose(f); - return true; - } - - inline void BinOArchive::openNode(const char* name, bool size8) - { - if (!strlen(name)) - { - return; - } - - unsigned short hash = calcHash(name); - stream_.write(hash); - - blockSizeOffsets_.push_back(int(stream_.position())); - stream_.write((unsigned char)0); - if (!size8) - { - stream_.write((unsigned short)0); - } - -#ifdef _DEBUG - // HashMap::iterator i = hashMap.find(hash); - // if(i != hashMap.end() && i->second != name) - // ASSERT_STR(0, name); - // hashMap[hash] = name; -#endif - } - - inline void BinOArchive::closeNode(const char* name, bool size8) - { - if (!strlen(name)) - { - return; - } - - unsigned int offset = blockSizeOffsets_.back(); - unsigned int size = (unsigned int)(stream_.position() - offset - sizeof(unsigned char) - (size8 ? 0 : sizeof(unsigned short))); - blockSizeOffsets_.pop_back(); - unsigned char* sizePtr = (unsigned char*)(stream_.buffer() + offset); - - if (size < SIZE16) - { - *sizePtr = size; - if (!size8) - { - unsigned char* buffer = sizePtr + 3; - memmove(buffer - 2, buffer, size); - stream_.setPosition(stream_.position() - 2); - } - } - else - { - YASLI_ASSERT(!size8); - if (size < 0x10000) - { - *sizePtr = SIZE16; - *((unsigned short*)(sizePtr + 1)) = size; - } - else - { - unsigned char* buffer = sizePtr + 3; - stream_.write((unsigned short)0); - *sizePtr = SIZE32; - memmove(buffer + 2, buffer, size); - *((unsigned int*)(sizePtr + 1)) = size; - } - } - } - - bool BinOArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) - { - bool size8 = strlen(value.get()) + 1 < SIZE16; - openNode(name, size8); - stream_ << value.get(); - stream_.write(char(0)); - closeNode(name, size8); - return true; - } - - bool BinOArchive::operator()(IWString& value, const char* name, [[maybe_unused]] const char* label) - { - bool size8 = (wcslen(value.get()) + 1) * 2 < SIZE16; - openNode(name, size8); - stream_ << value.get(); - stream_.write(short(0)); - closeNode(name, size8); - return true; - } - - bool BinOArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) - { - openNode(name, false); - ser(*this); - closeNode(name, false); - return true; - } - - bool BinOArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) - { - openNode(name, false); - - unsigned int size = (unsigned int)ser.size(); - if (size < SIZE16) - { - stream_.write((unsigned char)size); - } - else if (size < 0x10000) - { - stream_.write(SIZE16); - stream_.write((unsigned short)size); - } - else - { - stream_.write(SIZE32); - stream_.write(size); - } - - if (strlen(name)) - { - if (size > 0) - { - int i = 0; - do - { - char elementName[16]; - azitoa(i++, elementName, AZ_ARRAY_SIZE(elementName), 10); - ser(*this, elementName, ""); - } while (ser.next()); - } - - closeNode(name, false); - } - else - { - if (size > 0) - { - do - { - ser(*this, "", ""); - } - while (ser.next()); - } - } - - return true; - } - - bool BinOArchive::operator()(IPointer& ptr, const char* name, [[maybe_unused]] const char* label) - { - openNode(name, false); - - const char* typeName = ptr.registeredTypeName(); - if (!typeName) - { - typeName = ""; - } - if (typeName[0] == '\0' && ptr.get()) - { - CRY_ASSERT_MESSAGE(0, "Writing unregistered class. Use SERIALIZATION_CLASS_NAME macro for registration."); - } - - TypeID baseType = ptr.baseType(); - - if (ptr.get()) - { - stream_ << typeName; - stream_.write(char(0)); - ptr.serializer()(*this); - } - else - { - stream_.write(char(0)); - } - - closeNode(name, false); - return true; - } - - ////////////////////////////////////////////////////////////////////////// - - BinIArchive::BinIArchive() - : IArchive(INPUT | BINARY) - , loadedData_(0) - { - } - - BinIArchive::~BinIArchive() - { - close(); - } - - bool BinIArchive::load(const char* filename) - { - close(); - - FILE* f = nullptr; - azfopen(&f, filename, "rb"); - - if (!f) - { - return false; - } - fseek(f, 0, SEEK_END); - size_t length = ftell(f); - fseek(f, 0, SEEK_SET); - if (length == 0) - { - fclose(f); - return false; - } - loadedData_ = new char[length]; - if (fread((void*)loadedData_, 1, length, f) != length || !open(loadedData_, length)) - { - close(); - fclose(f); - return false; - } - fclose(f); - return true; - } - - bool BinIArchive::open(const char* buffer, size_t size) - { - if (size < sizeof(int)) - { - return false; - } - if (*(unsigned*)(buffer) != BIN_MAGIC) - { - return false; - } - buffer += sizeof(unsigned int); - size -= sizeof(unsigned int); - - blocks_.push_back(Block(buffer, (unsigned int)size)); - return true; - } - - void BinIArchive::close() - { - if (loadedData_) - { - delete[] loadedData_; - } - loadedData_ = 0; - } - - bool BinIArchive::openNode(const char* name) - { - Block block(0, 0); - if (currentBlock().get(name, block)) - { - blocks_.push_back(block); - return true; - } - return false; - } - - void BinIArchive::closeNode([[maybe_unused]] const char* name, [[maybe_unused]] bool check) - { - YASLI_ASSERT(!check || currentBlock().validToClose()); - blocks_.pop_back(); - } - - bool BinIArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - string str; - read(str); - value.set(str.c_str()); - return true; - } - - if (!openNode(name)) - { - return false; - } - - string str; - read(str); - value.set(str.c_str()); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(IWString& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - wstring str; - read(str); - value.set(str.c_str()); - return true; - } - - if (!openNode(name)) - { - return false; - } - - wstring str; - read(str); - value.set(str.c_str()); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - - bool BinIArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - ser(*this); - return true; - } - - if (!openNode(name)) - { - return false; - } - - ser(*this); - closeNode(name, false); - return true; - } - - bool BinIArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) - { - if (strlen(name)) - { - if (!openNode(name)) - { - return false; - } - - size_t size = currentBlock().readPackedSize(); - ser.resize(size); - - if (size > 0) - { - int i = 0; - do - { - char elementName[16]; - azitoa(i++, elementName, AZ_ARRAY_SIZE(elementName), 10); - ser(*this, elementName, ""); - } - while (ser.next()); - } - closeNode(name); - return true; - } - else - { - size_t size = currentBlock().readPackedSize(); - ser.resize(size); - if (size > 0) - { - do - { - ser(*this, "", ""); - } - while (ser.next()); - } - return true; - } - } - - bool BinIArchive::operator()(IPointer& ptr, const char* name, [[maybe_unused]] const char* label) - { - if (strlen(name) && !openNode(name)) - { - return false; - } - - string typeName; - read(typeName); - if (ptr.get() && (typeName.empty() || strcmp(typeName.c_str(), ptr.registeredTypeName()) != 0)) - { - ptr.create(""); // 0 - } - if (!typeName.empty() && !ptr.get()) - { - ptr.create(typeName.c_str()); - } - - if (SStruct ser = ptr.serializer()) - { - ser(*this); - } - - if (strlen(name)) - { - closeNode(name); - } - return true; - } - - unsigned int BinIArchive::Block::readPackedSize() - { - unsigned char size8; - read(size8); - if (size8 < SIZE16) - { - return size8; - } - if (size8 == SIZE16) - { - unsigned short size16; - read(size16); - return size16; - } - unsigned int size32; - read(size32); - return size32; - } - - bool BinIArchive::Block::get(const char* name, Block& block) - { - if (begin_ == end_) - { - return false; - } - complex_ = true; - unsigned short hashName = calcHash(name); - const char* currInitial = curr_; - bool restarted = false; - for (;; ) - { - if (curr_ >= end_) - { - return false; - } - - unsigned short hash; - read(hash); - unsigned int size = readPackedSize(); - - const char* currPrev = curr_; - if ((curr_ += size) == end_) - { - if (restarted) - { - return false; - } - curr_ = begin_; - restarted = true; - } - - //ASSERT(curr_ < end_); - - if (hash == hashName) - { - block = Block(currPrev, size); - return true; - } - - if (curr_ == currInitial) - { - return false; - } - } - } -} diff --git a/Code/CryEngine/CrySystem/Serialization/BinArchive.h b/Code/CryEngine/CrySystem/Serialization/BinArchive.h deleted file mode 100644 index 2d7daba899..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/BinArchive.h +++ /dev/null @@ -1,180 +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 - -// For tags 16-bit xor-hash is used, with check for uniquness in debug -// Block size is automatic: 8, 16 or 32 bits - -#include "Serialization/IArchive.h" -#include "MemoryWriter.h" - -namespace Serialization { - inline unsigned short calcHash(const char* str) - { - unsigned short hash = 0; - const unsigned short* p = (const unsigned short*)(str); - for (;; ) - { - unsigned short w = *p++; - if (!(w & 0xff)) - { - break; - } - hash ^= w; - if (!(w & 0xff00)) - { - break; - } - } - return hash; - } - - class BinOArchive - : public IArchive - { - public: - - BinOArchive(); - ~BinOArchive() {} - - void clear(); - size_t length() const; - const char* buffer() const { return stream_.buffer(); } - bool save(const char* fileName); - - bool operator()(bool& value, const char* name, const char* label); - bool operator()(IString& value, const char* name, const char* label); - bool operator()(IWString& value, const char* name, const char* label); - bool operator()(float& value, const char* name, const char* label); - bool operator()(double& value, const char* name, const char* label); - bool operator()(int32& value, const char* name, const char* label); - bool operator()(uint32& value, const char* name, const char* label); - bool operator()(int16& value, const char* name, const char* label); - bool operator()(uint16& value, const char* name, const char* label); - bool operator()(int64& value, const char* name, const char* label); - bool operator()(uint64& value, const char* name, const char* label); - - bool operator()(int8& value, const char* name, const char* label); - bool operator()(uint8& value, const char* name, const char* label); - bool operator()(char& value, const char* name, const char* label); - - bool operator()(const SStruct& ser, const char* name, const char* label); - bool operator()(IContainer& ser, const char* name, const char* label); - bool operator()(IPointer& ptr, const char* name, const char* label); - - using IArchive::operator(); - - private: - void openContainer(const char* name, int size, const char* typeName); - void openNode(const char* name, bool size8 = true); - void closeNode(const char* name, bool size8 = true); - - std::vector blockSizeOffsets_; - MemoryWriter stream_; - }; - - ////////////////////////////////////////////////////////////////////////// - - class BinIArchive - : public IArchive - { - public: - - BinIArchive(); - ~BinIArchive(); - - bool load(const char* fileName); - bool open(const char* buffer, size_t length); // doesn't copy the buffer - bool open(const BinOArchive& ar) { return open(ar.buffer(), ar.length()); } - void close(); - - bool operator()(bool& value, const char* name, const char* label); - bool operator()(IString& value, const char* name, const char* label); - bool operator()(IWString& value, const char* name, const char* label); - bool operator()(float& value, const char* name, const char* label); - bool operator()(double& value, const char* name, const char* label); - bool operator()(int16& value, const char* name, const char* label); - bool operator()(uint16& value, const char* name, const char* label); - bool operator()(int32& value, const char* name, const char* label); - bool operator()(uint32& value, const char* name, const char* label); - bool operator()(int64& value, const char* name, const char* label); - bool operator()(uint64& value, const char* name, const char* label); - - bool operator()(int8& value, const char* name, const char* label); - bool operator()(uint8& value, const char* name, const char* label); - bool operator()(char& value, const char* name, const char* label); - - bool operator()(const SStruct& ser, const char* name, const char* label); - bool operator()(IContainer& ser, const char* name, const char* label); - bool operator()(IPointer& ptr, const char* name, const char* label); - - using IArchive::operator(); - - private: - class Block - { - public: - Block(const char* data, int size) - : begin_(data) - , end_(data + size) - , curr_(data) - , complex_(false) {} - - bool get(const char* name, Block& block); - - void read(void* data, int size) - { - YASLI_ASSERT(curr_ + size <= end_); - memcpy(data, curr_, size); - curr_ += size; - } - - template - void read(T& x){ read(&x, sizeof(x)); } - - void read(string& s) - { - YASLI_ASSERT(curr_ + strlen(curr_) < end_); - s = curr_; - curr_ += strlen(curr_) + 1; - } - void read(wstring& s) - { - YASLI_ASSERT(curr_ + sizeof(wchar_t) * wcslen((wchar_t*)curr_) < end_); - s = (wchar_t*)curr_; - curr_ += (wcslen((wchar_t*)curr_) + 1) * sizeof(wchar_t); - } - - unsigned int readPackedSize(); - - bool validToClose() const { return complex_ || curr_ == end_; } - - private: - const char* begin_; - const char* end_; - const char* curr_; - bool complex_; - }; - - typedef std::vector Blocks; - Blocks blocks_; - const char* loadedData_; - - bool openNode(const char* name); - void closeNode(const char* name, bool check = true); - Block& currentBlock() { return blocks_.back(); } - template - void read(T& t) { currentBlock().read(t); } - }; -} diff --git a/Code/CryEngine/CrySystem/Serialization/JSONIArchive.cpp b/Code/CryEngine/CrySystem/Serialization/JSONIArchive.cpp deleted file mode 100644 index 8e323cc44c..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/JSONIArchive.cpp +++ /dev/null @@ -1,1525 +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 "CrySystem_precompiled.h" -#include -#include -#include -#include "Serialization/ClassFactory.h" -#include "Serialization/STL.h" -#include "JSONIArchive.h" -#include "Serialization/BlackBox.h" -#include "MemoryReader.h" -#include "MemoryWriter.h" - -#if 0 -# define DEBUG_TRACE(fmt, ...) printf(fmt "\n", __VA_ARGS__) -# define DEBUG_TRACE_TOKENIZER(fmt, ...) printf(fmt "\n", __VA_ARGS__) -#else -# define DEBUG_TRACE(...) -# define DEBUG_TRACE_TOKENIZER(...) -#endif - -namespace Serialization { - static char hexValueTable[256] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, - - 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - - static void unescapeString(std::vector& buf, string& out, const char* begin, const char* end) - { - if (begin >= end) - { - out.clear(); - return; - } - // TODO: use stack string - buf.resize(end - begin); - char* ptr = &buf[0]; - while (begin != end) - { - if (*begin != '\\') - { - *ptr = *begin; - ++ptr; - } - else - { - ++begin; - if (begin == end) - { - break; - } - - switch (*begin) - { - case '0': - *ptr = '\0'; - ++ptr; - break; - case 't': - *ptr = '\t'; - ++ptr; - break; - case 'n': - *ptr = '\n'; - ++ptr; - break; - case 'r': - *ptr = '\r'; - ++ptr; - break; - case '\\': - *ptr = '\\'; - ++ptr; - break; - case '\"': - *ptr = '\"'; - ++ptr; - break; - case '\'': - *ptr = '\''; - ++ptr; - break; - case 'x': - if (begin + 2 < end) - { - *ptr = (hexValueTable[int(begin[1])] << 4) + hexValueTable[int(begin[2])]; - ++ptr; - begin += 2; - break; - } - default: - *ptr = *begin; - ++ptr; - break; - } - } - ++begin; - } - buf.resize(ptr - &buf[0]); - if (!buf.empty()) - { - out.assign(&buf[0], &buf[0] + buf.size()); - } - else - { - out.clear(); - } - } - - // --------------------------------------------------------------------------- - - class JSONTokenizer - { - public: - JSONTokenizer(); - - Token operator()(const char* text) const; - private: - inline bool isSpace(char c) const; - inline bool isWordPart(unsigned char c) const; - inline bool isComment(char c) const; - inline bool isQuoteOpen(int& quoteIndex, char c) const; - inline bool isQuoteClose(int quoteIndex, char c) const; - inline bool isQuote(char c) const; - }; - - JSONTokenizer::JSONTokenizer() - { - } - - inline bool JSONTokenizer::isSpace(char c) const - { - return c == ' ' || c == '\t' || c == '\n' || c == '\r'; - } - - inline bool JSONTokenizer::isComment(char c) const - { - return c == '#'; - } - - - inline bool JSONTokenizer::isQuote(char c) const - { - return c == '\"'; - } - - static const char charTypes[256] = { - 0 /* 0x00: */, - 0 /* 0x01: */, - 0 /* 0x02: */, - 0 /* 0x03: */, - 0 /* 0x04: */, - 0 /* 0x05: */, - 0 /* 0x06: */, - 0 /* 0x07: */, - 0 /* 0x08: */, - 0 /* 0x09: \t */, - 0 /* 0x0A: \n */, - 0 /* 0x0B: */, - 0 /* 0x0C: */, - 0 /* 0x0D: */, - 0 /* 0x0E: */, - 0 /* 0x0F: */, - - - 0 /* 0x10: */, - 0 /* 0x11: */, - 0 /* 0x12: */, - 0 /* 0x13: */, - 0 /* 0x14: */, - 0 /* 0x15: */, - 0 /* 0x16: */, - 0 /* 0x17: */, - 0 /* 0x18: */, - 0 /* 0x19: */, - 0 /* 0x1A: */, - 0 /* 0x1B: */, - 0 /* 0x1C: */, - 0 /* 0x1D: */, - 0 /* 0x1E: */, - 0 /* 0x1F: */, - - - 0 /* 0x20: */, - 0 /* 0x21: ! */, - 0 /* 0x22: " */, - 0 /* 0x23: # */, - 0 /* 0x24: $ */, - 0 /* 0x25: % */, - 0 /* 0x26: & */, - 0 /* 0x27: ' */, - 0 /* 0x28: ( */, - 0 /* 0x29: ) */, - 0 /* 0x2A: * */, - 0 /* 0x2B: + */, - 0 /* 0x2C: , */, - 1 /* 0x2D: - */, - 1 /* 0x2E: . */, - 0 /* 0x2F: / */, - - - 1 /* 0x30: 0 */, - 1 /* 0x31: 1 */, - 1 /* 0x32: 2 */, - 1 /* 0x33: 3 */, - 1 /* 0x34: 4 */, - 1 /* 0x35: 5 */, - 1 /* 0x36: 6 */, - 1 /* 0x37: 7 */, - 1 /* 0x38: 8 */, - 1 /* 0x39: 9 */, - 0 /* 0x3A: : */, - 0 /* 0x3B: ; */, - 0 /* 0x3C: < */, - 0 /* 0x3D: = */, - 0 /* 0x3E: > */, - 0 /* 0x3F: ? */, - - - 0 /* 0x40: @ */, - 1 /* 0x41: A */, - 1 /* 0x42: B */, - 1 /* 0x43: C */, - 1 /* 0x44: D */, - 1 /* 0x45: E */, - 1 /* 0x46: F */, - 1 /* 0x47: G */, - 1 /* 0x48: H */, - 1 /* 0x49: I */, - 1 /* 0x4A: J */, - 1 /* 0x4B: K */, - 1 /* 0x4C: L */, - 1 /* 0x4D: M */, - 1 /* 0x4E: N */, - 1 /* 0x4F: O */, - - - 1 /* 0x50: P */, - 1 /* 0x51: Q */, - 1 /* 0x52: R */, - 1 /* 0x53: S */, - 1 /* 0x54: T */, - 1 /* 0x55: U */, - 1 /* 0x56: V */, - 1 /* 0x57: W */, - 1 /* 0x58: X */, - 1 /* 0x59: Y */, - 1 /* 0x5A: Z */, - 0 /* 0x5B: [ */, - 0 /* 0x5C: \ */, - 0 /* 0x5D: ] */, - 0 /* 0x5E: ^ */, - 1 /* 0x5F: _ */, - - - 0 /* 0x60: ` */, - 1 /* 0x61: a */, - 1 /* 0x62: b */, - 1 /* 0x63: c */, - 1 /* 0x64: d */, - 1 /* 0x65: e */, - 1 /* 0x66: f */, - 1 /* 0x67: g */, - 1 /* 0x68: h */, - 1 /* 0x69: i */, - 1 /* 0x6A: j */, - 1 /* 0x6B: k */, - 1 /* 0x6C: l */, - 1 /* 0x6D: m */, - 1 /* 0x6E: n */, - 1 /* 0x6F: o */, - - - 1 /* 0x70: p */, - 1 /* 0x71: q */, - 1 /* 0x72: r */, - 1 /* 0x73: s */, - 1 /* 0x74: t */, - 1 /* 0x75: u */, - 1 /* 0x76: v */, - 1 /* 0x77: w */, - 1 /* 0x78: x */, - 1 /* 0x79: y */, - 1 /* 0x7A: z */, - 0 /* 0x7B: { */, - 0 /* 0x7C: | */, - 0 /* 0x7D: } */, - 0 /* 0x7E: ~ */, - 0 /* 0x7F: */, - - - 0 /* 0x80: */, - 0 /* 0x81: */, - 0 /* 0x82: */, - 0 /* 0x83: */, - 0 /* 0x84: */, - 0 /* 0x85: */, - 0 /* 0x86: */, - 0 /* 0x87: */, - 0 /* 0x88: */, - 0 /* 0x89: */, - 0 /* 0x8A: */, - 0 /* 0x8B: */, - 0 /* 0x8C: */, - 0 /* 0x8D: */, - 0 /* 0x8E: */, - 0 /* 0x8F: */, - - - 0 /* 0x90: */, - 0 /* 0x91: */, - 0 /* 0x92: */, - 0 /* 0x93: */, - 0 /* 0x94: */, - 0 /* 0x95: */, - 0 /* 0x96: */, - 0 /* 0x97: */, - 0 /* 0x98: */, - 0 /* 0x99: */, - 0 /* 0x9A: */, - 0 /* 0x9B: */, - 0 /* 0x9C: */, - 0 /* 0x9D: */, - 0 /* 0x9E: */, - 0 /* 0x9F: */, - - - 0 /* 0xA0: */, - 0 /* 0xA1: */, - 0 /* 0xA2: */, - 0 /* 0xA3: */, - 0 /* 0xA4: */, - 0 /* 0xA5: */, - 0 /* 0xA6: */, - 0 /* 0xA7: */, - 0 /* 0xA8: */, - 0 /* 0xA9: */, - 0 /* 0xAA: */, - 0 /* 0xAB: */, - 0 /* 0xAC: */, - 0 /* 0xAD: */, - 0 /* 0xAE: */, - 0 /* 0xAF: */, - - - 0 /* 0xB0: */, - 0 /* 0xB1: */, - 0 /* 0xB2: */, - 0 /* 0xB3: */, - 0 /* 0xB4: */, - 0 /* 0xB5: */, - 0 /* 0xB6: */, - 0 /* 0xB7: */, - 0 /* 0xB8: */, - 0 /* 0xB9: */, - 0 /* 0xBA: */, - 0 /* 0xBB: */, - 0 /* 0xBC: */, - 0 /* 0xBD: */, - 0 /* 0xBE: */, - 0 /* 0xBF: */, - - - 0 /* 0xC0: */, - 0 /* 0xC1: */, - 0 /* 0xC2: */, - 0 /* 0xC3: */, - 0 /* 0xC4: */, - 0 /* 0xC5: */, - 0 /* 0xC6: */, - 0 /* 0xC7: */, - 0 /* 0xC8: */, - 0 /* 0xC9: */, - 0 /* 0xCA: */, - 0 /* 0xCB: */, - 0 /* 0xCC: */, - 0 /* 0xCD: */, - 0 /* 0xCE: */, - 0 /* 0xCF: */, - - - 0 /* 0xD0: */, - 0 /* 0xD1: */, - 0 /* 0xD2: */, - 0 /* 0xD3: */, - 0 /* 0xD4: */, - 0 /* 0xD5: */, - 0 /* 0xD6: */, - 0 /* 0xD7: */, - 0 /* 0xD8: */, - 0 /* 0xD9: */, - 0 /* 0xDA: */, - 0 /* 0xDB: */, - 0 /* 0xDC: */, - 0 /* 0xDD: */, - 0 /* 0xDE: */, - 0 /* 0xDF: */, - - - 0 /* 0xE0: */, - 0 /* 0xE1: */, - 0 /* 0xE2: */, - 0 /* 0xE3: */, - 0 /* 0xE4: */, - 0 /* 0xE5: */, - 0 /* 0xE6: */, - 0 /* 0xE7: */, - 0 /* 0xE8: */, - 0 /* 0xE9: */, - 0 /* 0xEA: */, - 0 /* 0xEB: */, - 0 /* 0xEC: */, - 0 /* 0xED: */, - 0 /* 0xEE: */, - 0 /* 0xEF: */, - - - 0 /* 0xF0: */, - 0 /* 0xF1: */, - 0 /* 0xF2: */, - 0 /* 0xF3: */, - 0 /* 0xF4: */, - 0 /* 0xF5: */, - 0 /* 0xF6: */, - 0 /* 0xF7: */, - 0 /* 0xF8: */, - 0 /* 0xF9: */, - 0 /* 0xFA: */, - 0 /* 0xFB: */, - 0 /* 0xFC: */, - 0 /* 0xFD: */, - 0 /* 0xFE: */, - 0 /* 0xFF: */ - }; - - inline bool JSONTokenizer::isWordPart(unsigned char c) const - { - return charTypes[c] != 0; - } - - Token JSONTokenizer::operator()(const char* ptr) const - { - while (isSpace(*ptr)) - { - ++ptr; - } - Token cur(ptr, ptr); - while (!cur && *ptr != '\0') - { - while (isComment(*cur.end)) - { -#if 0 - const char* commentStart = ptr; -#endif - while (*cur.end && *cur.end != '\n') - { - ++cur.end; - } - while (isSpace(*cur.end)) - { - ++cur.end; - } - DEBUG_TRACE_TOKENIZER("Got comment: '%s'", string(commentStart, cur.end).c_str()); - cur.start = cur.end; - } - CRY_ASSERT(!isSpace(*cur.end)); - if (isQuote(*cur.end)) - { - ++cur.end; - while (*cur.end) - { - if (*cur.end == '\\') - { - ++cur.end; - if (*cur.end) - { - if (*cur.end != 'x' && *cur.end != 'X') - { - ++cur.end; - } - else - { - ++cur.end; - if (*cur.end) - { - ++cur.end; - } - } - } - } - if (isQuote(*cur.end)) - { - ++cur.end; - DEBUG_TRACE_TOKENIZER("Tokenizer result: '%s'", cur.str().c_str()); - return cur; - } - else - { - ++cur.end; - } - } - } - else - { - if (!*cur.end) - { - return cur; - } - - DEBUG_TRACE_TOKENIZER("%c", *cur.end); - if (isWordPart(*cur.end)) - { - do - { - ++cur.end; - } while (isWordPart(*cur.end) != 0); - } - else - { - ++cur.end; - return cur; - } - DEBUG_TRACE_TOKENIZER("Tokenizer result: '%s'", cur.str().c_str()); - return cur; - } - } - DEBUG_TRACE_TOKENIZER("Tokenizer result: '%s'", cur.str().c_str()); - return cur; - } - - - // --------------------------------------------------------------------------- - - JSONIArchive::JSONIArchive() - : IArchive(INPUT | TEXT) - , buffer_(0) - { - } - - JSONIArchive::~JSONIArchive() - { - if (buffer_) - { - free(buffer_); - buffer_ = 0; - } - stack_.clear(); - reader_.reset(); - } - - bool JSONIArchive::open(const char* buffer, size_t length, bool free) - { - if (!length) - { - return false; - } - - if (buffer) - { - reader_.reset(new MemoryReader(buffer, length, free)); - } - buffer_ = 0; - - token_ = Token(reader_->begin(), reader_->begin()); - stack_.clear(); - - stack_.push_back(Level()); - readToken(); - putToken(); - stack_.back().start = token_.end; - return true; - } - - - bool JSONIArchive::load(const char* filename) - { - FILE* file = nullptr; - azfopen(&file, filename, "rb"); - if (file) - { - fseek(file, 0, SEEK_END); - long fileSize = ftell(file); - fseek(file, 0, SEEK_SET); - - void* buffer = 0; - if (fileSize > 0) - { - buffer = CryModuleMalloc(fileSize + 1); - CRY_ASSERT(buffer != 0); - memset(buffer, 0, fileSize + 1); - size_t elementsRead = fread(buffer, fileSize, 1, file); - CRY_ASSERT(((char*)(buffer))[fileSize] == '\0'); - if (elementsRead != 1) - { - CryModuleFree(buffer); - return false; - } - } - fclose(file); - - filename_ = filename; - buffer_ = buffer; - if (fileSize > 0) - { - return open((char*)buffer, fileSize, false); - } - else - { - return false; - } - } - else - { - return false; - } - } - - void JSONIArchive::readToken() - { - JSONTokenizer tokenizer; - token_ = tokenizer(token_.end); - DEBUG_TRACE(" ~ read token '%s' at %i", token_.str().c_str(), token_.start - reader_->begin()); - } - - void JSONIArchive::putToken() - { - DEBUG_TRACE(" putToken: '%s'", token_.str().c_str()); - token_ = Token(token_.start, token_.start); - } - - int JSONIArchive::line(const char* position) const - { - return int(std::count(reader_->begin(), position, '\n') + 1); - } - - bool JSONIArchive::isName(Token token) const - { - if (!token) - { - return false; - } - char firstChar = token.start[0]; - if (firstChar == '"') - { - return true; - } - return false; - } - - - bool JSONIArchive::expect(char token) - { - if (token_ != token) - { - const char* lineEnd = token_.start; - while (lineEnd && *lineEnd != '\0' && *lineEnd != '\r' && *lineEnd != '\n') - { - ++lineEnd; - } - - MemoryWriter msg; - msg << "Error parsing file, expected ':' at line " << line(token_.start) << ":\n" - << string(token_.start, lineEnd).c_str(); - CRY_ASSERT_MESSAGE(0, msg.c_str()); - return false; - } - return true; - } - - void JSONIArchive::skipBlock() - { - DEBUG_TRACE("Skipping block from %i ...", token_.end - reader_->begin()); - if (openBracket() || openContainerBracket()) - { - closeBracket(); // Skipping entire block - } - else - { - readToken(); // Skipping value - } - readToken(); - if (token_ != ',') - { - putToken(); - } - DEBUG_TRACE(" ...till %i", token_.end - reader_->begin()); - } - - bool JSONIArchive::findName(const char* name, Token* outName) - { - DEBUG_TRACE(" * finding name '%s'", name); - DEBUG_TRACE(" started at byte %i", int(token_.start - reader_->begin())); - if (stack_.empty()) - { - // TODO: diagnose - return false; - } - if (stack_.back().isKeyValue) - { - return true; - } - const char* start = 0; - const char* blockBegin = stack_.back().start; - if (*blockBegin == '\0') - { - return false; - } - - readToken(); - if (token_ == ',') - { - readToken(); - } - if (!token_) - { - start = blockBegin; - token_.set(blockBegin, blockBegin); - readToken(); - } - - if (stack_.size() == 1 || stack_.back().isContainer || outName != 0) - { - if (token_ == ']' || token_ == '}') - { - DEBUG_TRACE("Got close bracket..."); - putToken(); - return false; - } - else - { - DEBUG_TRACE("Got unnamed value: '%s'", token_.str().c_str()); - putToken(); - return true; - } - } - else - { - if (isName(token_)) - { - DEBUG_TRACE("Seems to be a name '%s'", token_.str().c_str()); - Token nameContent(token_.start + 1, token_.end - 1); - if (nameContent == name) - { - readToken(); - expect(':'); - DEBUG_TRACE("Got one"); - return true; - } - else - { - start = token_.start; - - readToken(); - expect(':'); - skipBlock(); - } - } - else - { - start = token_.start; - if (token_ == ']' || token_ == '}') - { - token_ = Token(blockBegin, blockBegin); - } - else - { - putToken(); - skipBlock(); - } - } - } - - while (true) - { - readToken(); - if (!token_) - { - token_.set(blockBegin, blockBegin); - continue; - } - //return false; // Reached end of file while searching for name - DEBUG_TRACE("'%s'", token_.str().c_str()); - DEBUG_TRACE("Checking for loop: %i and %i", token_.start - reader_->begin(), start - reader_->begin()); - CRY_ASSERT(start != 0); - if (token_.start == start) - { - putToken(); - DEBUG_TRACE("unable to find..."); - return false; // Reached a full circle: unable to find name - } - - if (token_ == '}' || token_ == ']') // CONVERSION - { - DEBUG_TRACE("Going to begin of block, from %i", token_.start - reader_->begin()); - token_ = Token(blockBegin, blockBegin); - DEBUG_TRACE(" to %i", token_.start - reader_->begin()); - continue; // Reached '}' or ']' while searching for name, continue from begin of block - } - - if (name[0] == '\0') - { - if (isName(token_)) - { - readToken(); - if (!token_) - { - return false; // Reached end of file while searching for name - } - expect(':'); - skipBlock(); - } - else - { - putToken(); // Not a name - put it back - return true; - } - } - else - { - if (isName(token_)) - { - Token nameContent(token_.start + 1, token_.end - 1); - readToken(); - expect(':'); - if (nameContent == name) - { - return true; - } - else - { - skipBlock(); - } - } - else - { - putToken(); - skipBlock(); - } - } - } - - return false; - } - - bool JSONIArchive::openBracket() - { - readToken(); - if (token_ == '{') - { - return true; - } - putToken(); - return false; - } - - bool JSONIArchive::closeBracket() - { - int relativeLevel = 0; - while (true) - { - readToken(); - if (token_ == ',') - { - readToken(); - } - if (!token_) - { - MemoryWriter msg; - CRY_ASSERT(!stack_.empty()); - const char* start = stack_.back().start; - msg << filename_.c_str() << ": " << line(start) << " line"; - msg << ": End of file while no matching bracket found"; - CRY_ASSERT_MESSAGE(0, msg.c_str()); - return false; - } - else if (token_ == '}' || token_ == ']') // CONVERSION - { - if (relativeLevel == 0) - { - return true; - } - else - { - --relativeLevel; - } - } - else if (token_ == '{' || token_ == '[') // CONVERSION - { - ++relativeLevel; - } - } - return false; - } - - bool JSONIArchive::openContainerBracket() - { - readToken(); - if (token_ == '[') - { - return true; - } - putToken(); - return false; - } - - bool JSONIArchive::closeContainerBracket() - { - readToken(); - if (token_ == ']') - { - DEBUG_TRACE("closeContainerBracket(): ok"); - return true; - } - else - { - DEBUG_TRACE("closeContainerBracket(): failed ('%s')", token_.str().c_str()); - putToken(); - return false; - } - } - - bool JSONIArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - if (openBracket()) - { - stack_.push_back(Level()); - stack_.back().start = token_.end; - } - else if (openContainerBracket()) - { - stack_.push_back(Level()); - stack_.back().start = token_.end; - stack_.back().isContainer = true; - } - else - { - return false; - } - - ser(*this); - CRY_ASSERT(!stack_.empty()); - stack_.pop_back(); -#if !defined(NDEBUG) - bool closed = -#endif - closeBracket(); - CRY_ASSERT(closed); - return true; - } - return false; - } - - bool JSONIArchive::operator()(const SBlackBox& box, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - if (openBracket() || openContainerBracket()) - { - const char* start = token_.start; - putToken(); - skipBlock(); - const char* end = token_.start; - if (end < start) - { - CRY_ASSERT(0); - return false; - } - while (end > start && - (*(end - 1) == ' ' - || *(end - 1) == '\r' - || *(end - 1) == '\n' - || *(end - 1) == '\t')) - { - --end; - } - // box has to be const in the interface so we can serialize - // temporary variables (i.e. function call result or structures - // constructed on the stack) - const_cast(box).set("json", (void*)start, end - start); - return true; - } - } - return false; - } - - bool JSONIArchive::operator()(IKeyValue& keyValue, [[maybe_unused]] const char* name, [[maybe_unused]] const char* label) - { - Token nextName; - if (!stack_.empty() && stack_.back().isContainer) - { - readToken(); - if (isName(token_) && checkStringValueToken()) - { - string key; - unescapeString(unescapeBuffer_, key, token_.start + 1, token_.end - 1); - keyValue.set(key.c_str()); - readToken(); - if (!expect(':')) - { - return false; - } - if (!keyValue.serializeValue(*this, "", 0)) - { - return false; - } - return true; - } - else - { - putToken(); - return false; - } - } - else if (findName("", &nextName)) - { - string key; - unescapeString(unescapeBuffer_, key, nextName.start + 1, nextName.end - 1); - keyValue.set(key.c_str()); - stack_.push_back(Level()); - stack_.back().isKeyValue = true; - - bool result = keyValue.serializeValue(*this, "", 0); - if (stack_.empty()) - { - // TODO: diagnose - return false; - } - stack_.pop_back(); - return result; - } - return false; - } - - - bool JSONIArchive::operator()(IPointer& ser, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - if (openBracket()) - { - stack_.push_back(Level()); - stack_.back().start = token_.end; - stack_.back().isKeyValue = true; - - readToken(); - if (isName(token_)) - { - if (checkStringValueToken()) - { - string typeName; - unescapeString(unescapeBuffer_, typeName, token_.start + 1, token_.end - 1); - - if (typeName != ser.registeredTypeName()) - { - ser.create(typeName.c_str()); - } - readToken(); - expect(':'); - operator()(ser.serializer(), "", 0); - } - } - else - { - putToken(); - - ser.create(""); - } - closeBracket(); - stack_.pop_back(); - return true; - } - } - return false; - } - - - bool JSONIArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - bool containerBracket = openContainerBracket(); - bool dictionaryBracket = false; - if (!containerBracket) - { - dictionaryBracket = openBracket(); - } - if (containerBracket || dictionaryBracket) - { - stack_.push_back(Level()); - stack_.back().isContainer = true; - stack_.back().start = token_.end; - - std::size_t size = ser.size(); - std::size_t index = 0; - - while (true) - { - readToken(); - if (token_ == ',') - { - readToken(); - } - if (token_ == '}' || token_ == ']') - { - break; - } - else if (!token_) - { - CRY_ASSERT(0 && "Reached end of file while reading container!"); - return false; - } - putToken(); - if (index == size) - { - size = index + 1; - } - if (index < size) - { - if (!ser(*this, "", "")) - { - // We've got a named item within a container, - // i.e. looks like a dictionary but not a container. - // Bail out, it is nothing we can do here. - closeBracket(); - break; - } - } - else - { - skipBlock(); - } - ser.next(); - ++index; - } - if (size > index) - { - ser.resize(index); - } - - CRY_ASSERT(!stack_.empty()); - stack_.pop_back(); - return true; - } - } - return false; - } - - void JSONIArchive::checkValueToken() - { - if (!token_) - { - CRY_ASSERT(!stack_.empty()); - MemoryWriter msg; - const char* start = stack_.back().start; - msg << filename_.c_str() << ": " << line(start) << " line"; - msg << ": End of file while reading element's value"; - CRY_ASSERT_MESSAGE(0, msg.c_str()); - } - } - - bool JSONIArchive::checkStringValueToken() - { - if (!token_) - { - return false; - MemoryWriter msg; - const char* start = stack_.back().start; - msg << filename_.c_str() << ": " << line(start) << " line"; - msg << ": End of file while reading element's value"; - CRY_ASSERT_MESSAGE(0, msg.c_str()); - return false; - } - if (token_.start[0] != '"' || token_.end[-1] != '"') - { - return false; - MemoryWriter msg; - const char* start = stack_.back().start; - msg << filename_.c_str() << ": " << line(start) << " line"; - msg << ": Expected string"; - CRY_ASSERT_MESSAGE(0, msg.c_str()); - return false; - } - return true; - } - - bool JSONIArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = strtol(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = strtoul(token_.start, 0, 10); - return true; - } - return false; - } - - - bool JSONIArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (int16)strtol(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (uint16)strtoul(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); -#ifdef _MSC_VER - value = _strtoi64(token_.start, 0, 10); -#else - value = strtoll(token_.start, 0, 10); -#endif - return true; - } - return false; - } - - bool JSONIArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); -#ifdef _MSC_VER - value = _strtoui64(token_.start, 0, 10); -#else - value = strtoull(token_.start, 0, 10); -#endif - return true; - } - return false; - } - - bool JSONIArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); -#ifdef _MSC_VER - value = float(std::atof(token_.str().c_str())); -#else - value = strtof(token_.start, 0); -#endif - return true; - } - return false; - } - - bool JSONIArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); -#ifdef _MSC_VER - value = std::atof(token_.str().c_str()); -#else - value = strtod(token_.start, 0); -#endif - return true; - } - return false; - } - - bool JSONIArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - if (checkStringValueToken()) - { - string buf; - unescapeString(unescapeBuffer_, buf, token_.start + 1, token_.end - 1); - value.set(buf.c_str()); - } - else - { - return false; - } - return true; - } - return false; - } - - - inline size_t utf8InUtf16Len(const char* p) - { - size_t result = 0; - - for (; *p; ++p) - { - unsigned char ch = (unsigned char)(*p); - - if (ch < 0x80 || (ch >= 0xC0 && ch < 0xFC)) - { - ++result; - } - } - - return result; - } - - inline const char* readUtf16FromUtf8(unsigned int* ch, const char* s) - { - const unsigned char byteMark = 0x80; - const unsigned char byteMaskRead = 0x3F; - - const unsigned char* str = (const unsigned char*)s; - - size_t len; - if (*str < byteMark) - { - *ch = *str; - return s + 1; - } - else if (*str < 0xC0) - { - *ch = ' '; - return s + 1; - } - else if (*str < 0xE0) - { - len = 2; - } - else if (*str < 0xF0) - { - len = 3; - } - else if (*str < 0xF8) - { - len = 4; - } - else if (*str < 0xFC) - { - len = 5; - } - else - { - *ch = ' '; - return s + 1; - } - - const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - *ch = (*str++ & ~firstByteMark[len]); - - switch (len) - { - case 5: - (*ch) <<= 6; - (*ch) += (*str++ & byteMaskRead); - case 4: - (*ch) <<= 6; - (*ch) += (*str++ & byteMaskRead); - case 3: - (*ch) <<= 6; - (*ch) += (*str++ & byteMaskRead); - case 2: - (*ch) <<= 6; - (*ch) += (*str++ & byteMaskRead); - } - - return (const char*)str; - } - - - inline void utf8ToUtf16(wstring* out, const char* in) - { - out->clear(); - out->reserve(utf8InUtf16Len(in)); - - for (; *in; ) - { - unsigned int character; - in = readUtf16FromUtf8(&character, in); - (*out) += (wchar_t)character; - } - } - - - bool JSONIArchive::operator()(IWString& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - if (checkStringValueToken()) - { - string buf; - unescapeString(unescapeBuffer_, buf, token_.start + 1, token_.end - 1); - wstring wbuf; - utf8ToUtf16(&wbuf, buf.c_str()); - value.set(wbuf.c_str()); - } - else - { - return false; - } - return true; - } - return false; - } - - bool JSONIArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - if (token_ == "true") - { - value = true; - } - else if (token_ == "false") - { - value = false; - } - else - { - CRY_ASSERT(0 && "Invalid boolean value"); - } - return true; - } - return false; - } - - bool JSONIArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (int8)strtol(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (uint8)strtol(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (char)strtol(token_.start, 0, 10); - return true; - } - return false; - } -} -// vim:ts=4 sw=4: diff --git a/Code/CryEngine/CrySystem/Serialization/JSONIArchive.h b/Code/CryEngine/CrySystem/Serialization/JSONIArchive.h deleted file mode 100644 index b38476a597..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/JSONIArchive.h +++ /dev/null @@ -1,95 +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 - -#include "Serialization/IArchive.h" -#include "MemoryReader.h" -#include "Token.h" -#include - -namespace Serialization { - class MemoryReader; - - class JSONIArchive - : public IArchive - { - public: - JSONIArchive(); - ~JSONIArchive(); - - bool load(const char* filename); - bool open(const char* buffer, size_t length, bool free = false); - - // virtuals: - bool operator()(bool& value, const char* name = "", const char* label = 0); - bool operator()(IString& value, const char* name = "", const char* label = 0); - bool operator()(IWString& value, const char* name = "", const char* label = 0); - bool operator()(float& value, const char* name = "", const char* label = 0); - bool operator()(double& value, const char* name = "", const char* label = 0); - bool operator()(int16& value, const char* name = "", const char* label = 0); - bool operator()(uint16& value, const char* name = "", const char* label = 0); - bool operator()(int32& value, const char* name = "", const char* label = 0); - bool operator()(uint32& value, const char* name = "", const char* label = 0); - bool operator()(int64& value, const char* name = "", const char* label = 0); - bool operator()(uint64& value, const char* name = "", const char* label = 0); - - bool operator()(int8& value, const char* name = "", const char* label = 0); - bool operator()(uint8& value, const char* name = "", const char* label = 0); - bool operator()(char& value, const char* name = "", const char* label = 0); - - bool operator()(const SStruct& ser, const char* name = "", const char* label = 0); - bool operator()(const SBlackBox& ser, const char* name = "", const char* label = 0); - bool operator()(IContainer& ser, const char* name = "", const char* label = 0); - bool operator()(IKeyValue& ser, const char* name = "", const char* label = 0); - bool operator()(IPointer& ser, const char* name = "", const char* label = 0); - - using IArchive::operator(); - private: - bool findName(const char* name, Token* outName = 0); - bool openBracket(); - bool closeBracket(); - - bool openContainerBracket(); - bool closeContainerBracket(); - - void checkValueToken(); - bool checkStringValueToken(); - void readToken(); - void putToken(); - int line(const char* position) const; - bool isName(Token token) const; - - bool expect(char token); - void skipBlock(); - - struct Level - { - const char* start; - const char* firstToken; - bool isContainer; - bool isKeyValue; - Level() - : isContainer(false) - , isKeyValue(false) {} - }; - typedef std::vector Stack; - Stack stack_; - - std::unique_ptr reader_; - Token token_; - std::vector unescapeBuffer_; - string filename_; - void* buffer_; - }; -} diff --git a/Code/CryEngine/CrySystem/Serialization/JSONOArchive.cpp b/Code/CryEngine/CrySystem/Serialization/JSONOArchive.cpp deleted file mode 100644 index d1aef5601e..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/JSONOArchive.cpp +++ /dev/null @@ -1,828 +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 "CrySystem_precompiled.h" -#include "JSONOArchive.h" -#include "MemoryWriter.h" -#include "Serialization/KeyValue.h" -#include "Serialization/ClassFactory.h" -#include "Serialization/BlackBox.h" -#include - -namespace Serialization { - // Some of non-latin1 characters here are not escaped to - // keep compatibility with 8-bit local encoding (e.g. windows-1251) - static const char* escapeTable[256] = { - "\\0" /* 0x00: */, - "\\x01" /* 0x01: */, - "\\x02" /* 0x02: */, - "\\x03" /* 0x03: */, - "\\x04" /* 0x04: */, - "\\x05" /* 0x05: */, - "\\x06" /* 0x06: */, - "\\x07" /* 0x07: */, - "\\x08" /* 0x08: */, - "\\t" /* 0x09: \t */, - "\\n" /* 0x0A: \n */, - "\\x0B" /* 0x0B: */, - "\\x0C" /* 0x0C: */, - "\\r" /* 0x0D: */, - "\\x0E" /* 0x0E: */, - "\\x0F" /* 0x0F: */, - - - "\\x10" /* 0x10: */, - "\\x11" /* 0x11: */, - "\\x12" /* 0x12: */, - "\\x13" /* 0x13: */, - "\\x14" /* 0x14: */, - "\\x15" /* 0x15: */, - "\\x16" /* 0x16: */, - "\\x17" /* 0x17: */, - "\\x18" /* 0x18: */, - "\\x19" /* 0x19: */, - "\\x1A" /* 0x1A: */, - "\\x1B" /* 0x1B: */, - "\\x1C" /* 0x1C: */, - "\\x1D" /* 0x1D: */, - "\\x1E" /* 0x1E: */, - "\\x1F" /* 0x1F: */, - - - " " /* 0x20: */, - "!" /* 0x21: ! */, - "\\\"" /* 0x22: " */, - "#" /* 0x23: # */, - "$" /* 0x24: $ */, - "%" /* 0x25: % */, - "&" /* 0x26: & */, - "'" /* 0x27: ' */, - "(" /* 0x28: ( */, - ")" /* 0x29: ) */, - "*" /* 0x2A: * */, - "+" /* 0x2B: + */, - "," /* 0x2C: , */, - "-" /* 0x2D: - */, - "." /* 0x2E: . */, - "/" /* 0x2F: / */, - - - "0" /* 0x30: 0 */, - "1" /* 0x31: 1 */, - "2" /* 0x32: 2 */, - "3" /* 0x33: 3 */, - "4" /* 0x34: 4 */, - "5" /* 0x35: 5 */, - "6" /* 0x36: 6 */, - "7" /* 0x37: 7 */, - "8" /* 0x38: 8 */, - "9" /* 0x39: 9 */, - ":" /* 0x3A: : */, - ";" /* 0x3B: ; */, - "<" /* 0x3C: < */, - "=" /* 0x3D: = */, - ">" /* 0x3E: > */, - "?" /* 0x3F: ? */, - - - "@" /* 0x40: @ */, - "A" /* 0x41: A */, - "B" /* 0x42: B */, - "C" /* 0x43: C */, - "D" /* 0x44: D */, - "E" /* 0x45: E */, - "F" /* 0x46: F */, - "G" /* 0x47: G */, - "H" /* 0x48: H */, - "I" /* 0x49: I */, - "J" /* 0x4A: J */, - "K" /* 0x4B: K */, - "L" /* 0x4C: L */, - "M" /* 0x4D: M */, - "N" /* 0x4E: N */, - "O" /* 0x4F: O */, - - - "P" /* 0x50: P */, - "Q" /* 0x51: Q */, - "R" /* 0x52: R */, - "S" /* 0x53: S */, - "T" /* 0x54: T */, - "U" /* 0x55: U */, - "V" /* 0x56: V */, - "W" /* 0x57: W */, - "X" /* 0x58: X */, - "Y" /* 0x59: Y */, - "Z" /* 0x5A: Z */, - "[" /* 0x5B: [ */, - "\\\\" /* 0x5C: \ */, - "]" /* 0x5D: ] */, - "^" /* 0x5E: ^ */, - "_" /* 0x5F: _ */, - - - "`" /* 0x60: ` */, - "a" /* 0x61: a */, - "b" /* 0x62: b */, - "c" /* 0x63: c */, - "d" /* 0x64: d */, - "e" /* 0x65: e */, - "f" /* 0x66: f */, - "g" /* 0x67: g */, - "h" /* 0x68: h */, - "i" /* 0x69: i */, - "j" /* 0x6A: j */, - "k" /* 0x6B: k */, - "l" /* 0x6C: l */, - "m" /* 0x6D: m */, - "n" /* 0x6E: n */, - "o" /* 0x6F: o */, - - - "p" /* 0x70: p */, - "q" /* 0x71: q */, - "r" /* 0x72: r */, - "s" /* 0x73: s */, - "t" /* 0x74: t */, - "u" /* 0x75: u */, - "v" /* 0x76: v */, - "w" /* 0x77: w */, - "x" /* 0x78: x */, - "y" /* 0x79: y */, - "z" /* 0x7A: z */, - "{" /* 0x7B: { */, - "|" /* 0x7C: | */, - "}" /* 0x7D: } */, - "~" /* 0x7E: ~ */, - "\x7F" /* 0x7F: */, // for utf-8 - - - "\x80" /* 0x80: */, - "\x81" /* 0x81: */, - "\x82" /* 0x82: */, - "\x83" /* 0x83: */, - "\x84" /* 0x84: */, - "\x85" /* 0x85: */, - "\x86" /* 0x86: */, - "\x87" /* 0x87: */, - "\x88" /* 0x88: */, - "\x89" /* 0x89: */, - "\x8A" /* 0x8A: */, - "\x8B" /* 0x8B: */, - "\x8C" /* 0x8C: */, - "\x8D" /* 0x8D: */, - "\x8E" /* 0x8E: */, - "\x8F" /* 0x8F: */, - - - "\x90" /* 0x90: */, - "\x91" /* 0x91: */, - "\x92" /* 0x92: */, - "\x93" /* 0x93: */, - "\x94" /* 0x94: */, - "\x95" /* 0x95: */, - "\x96" /* 0x96: */, - "\x97" /* 0x97: */, - "\x98" /* 0x98: */, - "\x99" /* 0x99: */, - "\x9A" /* 0x9A: */, - "\x9B" /* 0x9B: */, - "\x9C" /* 0x9C: */, - "\x9D" /* 0x9D: */, - "\x9E" /* 0x9E: */, - "\x9F" /* 0x9F: */, - - - "\xA0" /* 0xA0: */, - "\xA1" /* 0xA1: */, - "\xA2" /* 0xA2: */, - "\xA3" /* 0xA3: */, - "\xA4" /* 0xA4: */, - "\xA5" /* 0xA5: */, - "\xA6" /* 0xA6: */, - "\xA7" /* 0xA7: */, - "\xA8" /* 0xA8: */, - "\xA9" /* 0xA9: */, - "\xAA" /* 0xAA: */, - "\xAB" /* 0xAB: */, - "\xAC" /* 0xAC: */, - "\xAD" /* 0xAD: */, - "\xAE" /* 0xAE: */, - "\xAF" /* 0xAF: */, - - - "\xB0" /* 0xB0: */, - "\xB1" /* 0xB1: */, - "\xB2" /* 0xB2: */, - "\xB3" /* 0xB3: */, - "\xB4" /* 0xB4: */, - "\xB5" /* 0xB5: */, - "\xB6" /* 0xB6: */, - "\xB7" /* 0xB7: */, - "\xB8" /* 0xB8: */, - "\xB9" /* 0xB9: */, - "\xBA" /* 0xBA: */, - "\xBB" /* 0xBB: */, - "\xBC" /* 0xBC: */, - "\xBD" /* 0xBD: */, - "\xBE" /* 0xBE: */, - "\xBF" /* 0xBF: */, - - - "\xC0" /* 0xC0: */, - "\xC1" /* 0xC1: */, - "\xC2" /* 0xC2: */, - "\xC3" /* 0xC3: */, - "\xC4" /* 0xC4: */, - "\xC5" /* 0xC5: */, - "\xC6" /* 0xC6: */, - "\xC7" /* 0xC7: */, - "\xC8" /* 0xC8: */, - "\xC9" /* 0xC9: */, - "\xCA" /* 0xCA: */, - "\xCB" /* 0xCB: */, - "\xCC" /* 0xCC: */, - "\xCD" /* 0xCD: */, - "\xCE" /* 0xCE: */, - "\xCF" /* 0xCF: */, - - - "\xD0" /* 0xD0: */, - "\xD1" /* 0xD1: */, - "\xD2" /* 0xD2: */, - "\xD3" /* 0xD3: */, - "\xD4" /* 0xD4: */, - "\xD5" /* 0xD5: */, - "\xD6" /* 0xD6: */, - "\xD7" /* 0xD7: */, - "\xD8" /* 0xD8: */, - "\xD9" /* 0xD9: */, - "\xDA" /* 0xDA: */, - "\xDB" /* 0xDB: */, - "\xDC" /* 0xDC: */, - "\xDD" /* 0xDD: */, - "\xDE" /* 0xDE: */, - "\xDF" /* 0xDF: */, - - - "\xE0" /* 0xE0: */, - "\xE1" /* 0xE1: */, - "\xE2" /* 0xE2: */, - "\xE3" /* 0xE3: */, - "\xE4" /* 0xE4: */, - "\xE5" /* 0xE5: */, - "\xE6" /* 0xE6: */, - "\xE7" /* 0xE7: */, - "\xE8" /* 0xE8: */, - "\xE9" /* 0xE9: */, - "\xEA" /* 0xEA: */, - "\xEB" /* 0xEB: */, - "\xEC" /* 0xEC: */, - "\xED" /* 0xED: */, - "\xEE" /* 0xEE: */, - "\xEF" /* 0xEF: */, - - - "\xF0" /* 0xF0: */, - "\xF1" /* 0xF1: */, - "\xF2" /* 0xF2: */, - "\xF3" /* 0xF3: */, - "\xF4" /* 0xF4: */, - "\xF5" /* 0xF5: */, - "\xF6" /* 0xF6: */, - "\xF7" /* 0xF7: */, - "\xF8" /* 0xF8: */, - "\xF9" /* 0xF9: */, - "\xFA" /* 0xFA: */, - "\xFB" /* 0xFB: */, - "\xFC" /* 0xFC: */, - "\xFD" /* 0xFD: */, - "\xFE" /* 0xFE: */, - "\xFF" /* 0xFF: */ - }; - - static void escapeString(MemoryWriter& dest, const char* begin, const char* end) - { - while (begin != end) - { - const char* str = escapeTable[(unsigned char)(*begin)]; - dest.write(str); - ++begin; - } - } - - // --------------------------------------------------------------------------- - - static const int TAB_WIDTH = 2; - - JSONOArchive::JSONOArchive(int textWidth, const char* header) - : IArchive(OUTPUT | TEXT) - , header_(header) - , textWidth_(textWidth) - , compactOffset_(0) - { - buffer_.reset(new MemoryWriter(1024, true)); - if (header_) - { - (*buffer_) << header_; - } - - YASLI_ASSERT(stack_.empty()); - stack_.push_back(Level(false, 0, 0)); - } - - JSONOArchive::~JSONOArchive() - { - } - - bool JSONOArchive::save(const char* fileName) - { - YASLI_ESCAPE(fileName && strlen(fileName) > 0, return false); - YASLI_ESCAPE(stack_.size() == 1, return false); - YASLI_ESCAPE(buffer_.get() != 0, return false); - YASLI_ESCAPE(buffer_->position() <= buffer_->size(), return false); - stack_.pop_back(); - FILE* file = nullptr; - azfopen(&file, fileName, "wb"); - if (file) - { - if (fwrite(buffer_->c_str(), 1, buffer_->position(), file) != buffer_->position()) - { - fclose(file); - return false; - } - fclose(file); - return true; - } - else - { - return false; - } - } - - const char* JSONOArchive::c_str() const - { - return buffer_->c_str(); - } - - size_t JSONOArchive::length() const - { - return buffer_->position(); - } - - void JSONOArchive::openBracket() - { - *buffer_ << "{"; - } - - void JSONOArchive::closeBracket() - { - *buffer_ << "}"; - } - - void JSONOArchive::openContainerBracket() - { - *buffer_ << "["; - } - - void JSONOArchive::closeContainerBracket() - { - *buffer_ << "]"; - } - - void JSONOArchive::placeName(const char* name) - { - if (stack_.back().isKeyValue) - { - return; - } - if ((name[0] != '\0' || !stack_.back().isContainer) && stack_.size() > 1) - { - *buffer_ << "\""; - *buffer_ << name; - *buffer_ << "\": "; - stack_.back().nameIndex += 1; - } - } - - void JSONOArchive::placeIndent(bool putComma) - { - if (stack_.back().isKeyValue) - { - return; - } - if (putComma && stack_.back().elementIndex > 0) - { - *buffer_ << ","; - } - if (buffer_->position() > 0) - { - *buffer_ << "\n"; - } - int count = int(stack_.size() - 1); - stack_.back().indentCount += count; - stack_.back().elementIndex += 1; - for (int i = 0; i < count; ++i) - { - *buffer_ << "\t"; - } - compactOffset_ = 0; - } - - void JSONOArchive::placeIndentCompact(bool putComma) - { - if (stack_.back().isKeyValue) - { - return; - } - if (putComma && stack_.back().elementIndex > 0) - { - *buffer_ << ","; - } - if ((compactOffset_ % 32) != 0 && stack_.back().isContainer) - { - *buffer_ << " "; - compactOffset_ += 1; - stack_.back().elementIndex += 1; - } - else if (buffer_->size()) - { - *buffer_ << "\n"; - int count = int(stack_.size() - 1); - stack_.back().indentCount += count /* * TAB_WIDTH*/; - stack_.back().elementIndex += 1; - for (int i = 0; i < count; ++i) - { - *buffer_ << "\t"; - } - compactOffset_ = 1; - } - } - - bool JSONOArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - *buffer_ << (value ? "true" : "false"); - return true; - } - - - bool JSONOArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - (*buffer_) << "\""; - const char* str = value.get(); - escapeString(*buffer_, str, str + strlen(value.get())); - (*buffer_) << "\""; - return true; - } - - inline char* writeUtf16ToUtf8(char* s, unsigned int ch) - { - const unsigned char byteMark = 0x80; - const unsigned char byteMask = 0xBF; - - size_t len; - - if (ch < 0x80) - { - len = 1; - } - else if (ch < 0x800) - { - len = 2; - } - else if (ch < 0x10000) - { - len = 3; - } - else if (ch < 0x200000) - { - len = 4; - } - else - { - return s; - } - - s += len; - - const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - switch (len) - { - case 4: - *--s = (char)((ch | byteMark) & byteMask); - ch >>= 6; - case 3: - *--s = (char)((ch | byteMark) & byteMask); - ch >>= 6; - case 2: - *--s = (char)((ch | byteMark) & byteMask); - ch >>= 6; - case 1: - *--s = (char)(ch | firstByteMark[len]); - } - - return s + len; - } - - bool JSONOArchive::operator()(IWString& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - (*buffer_) << "\""; - - const wchar_t* in = value.get(); - for (; *in; ++in) - { - char buf[6]; - escapeString(*buffer_, buf, writeUtf16ToUtf8(buf, *in)); - } - - (*buffer_) << "\""; - return true; - } - - bool JSONOArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - std::size_t position = buffer_->position(); - openBracket(); - stack_.push_back(Level(false, position, int(strlen(name) + 2 * (name[0] & 1) + (stack_.size() - 1) * TAB_WIDTH + 2))); - - YASLI_ASSERT(ser); - ser(*this); - - bool joined = joinLinesIfPossible(); - bool noNames = stack_.back().nameIndex == 0; - if (noNames) - { - if (stack_.size() != 2) - { - buffer_->buffer()[stack_.back().startPosition] = '['; - } - } - stack_.pop_back(); - if (!joined) - { - placeIndent(false); - } - else - { - *buffer_ << " "; - } - if (noNames) - { - closeContainerBracket(); - } - else - { - closeBracket(); - } - return true; - } - - bool JSONOArchive::operator()(const SBlackBox& box, const char* name, [[maybe_unused]] const char* label) - { - if (strcmp(box.format, "json") != 0) - { - return false; - } - if (box.size == 0) - { - return false; - } - - placeIndent(); - placeName(name); - return buffer_->write(box.data, box.size); - } - - bool JSONOArchive::operator()(IKeyValue& keyValue, [[maybe_unused]] const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - - *buffer_ << "\""; - *buffer_ << keyValue.get(); - *buffer_ << "\": "; - stack_.back().nameIndex += 1; - - stack_.back().isKeyValue = true; - keyValue.serializeValue(*this, "", 0); - stack_.back().isKeyValue = false; - if (stack_.back().isContainer) - { - stack_.back().isDictionary = true; - } - return true; - } - - bool JSONOArchive::operator()(IPointer& ser, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - openBracket(); - const char* registeredTypeName = ser.registeredTypeName(); - if (registeredTypeName && registeredTypeName[0] != '\0') - { - *buffer_ << " "; - placeName(registeredTypeName); - stack_.back().isKeyValue = true; - operator()(ser.serializer(), ""); - stack_.back().isKeyValue = false; - *buffer_ << " "; - } - closeBracket(); - return true; - } - - bool JSONOArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - std::size_t position = buffer_->position(); - openContainerBracket(); - stack_.push_back(Level(true, position, int(strlen(name) + 2 * (name[0] & 1) + stack_.size() - 1 * TAB_WIDTH + 2))); - - std::size_t size = ser.size(); - if (size > 0) - { - do - { - ser(*this, "", ""); - } while (ser.next()); - } - - bool joined = joinLinesIfPossible(); - bool isDictionary = stack_.back().isDictionary; - if (isDictionary) - { - buffer_->buffer()[stack_.back().startPosition] = '{'; - } - stack_.pop_back(); - if (!joined) - { - placeIndent(false); - } - else - { - *buffer_ << " "; - } - - if (isDictionary) - { - closeBracket(); - } - else - { - closeContainerBracket(); - } - return true; - } - - static char* joinLines(char* start, char* end) - { - YASLI_ASSERT(start <= end); - char* next = start; - while (next != end) - { - if (*next != '\t' && *next != '\r') - { - if (*next != '\n') - { - *start = *next; - } - else - { - *start = ' '; - } - ++start; - } - ++next; - } - return start; - } - - bool JSONOArchive::joinLinesIfPossible() - { - YASLI_ASSERT(!stack_.empty()); - std::size_t startPosition = stack_.back().startPosition; - YASLI_ASSERT(startPosition < buffer_->size()); - int indentCount = stack_.back().indentCount; - //YASLI_ASSERT(startPosition >= indentCount); - if (buffer_->position() - startPosition - indentCount < std::size_t(textWidth_)) - { - char* buffer = buffer_->buffer(); - char* start = buffer + startPosition; - char* end = buffer + buffer_->position(); - end = joinLines(start, end); - std::size_t newPosition = end - buffer; - YASLI_ASSERT(newPosition <= buffer_->position()); - buffer_->setPosition(newPosition); - return true; - } - return false; - } -} -// vim:ts=4 sw=4: diff --git a/Code/CryEngine/CrySystem/Serialization/JSONOArchive.h b/Code/CryEngine/CrySystem/Serialization/JSONOArchive.h deleted file mode 100644 index 5701c992ac..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/JSONOArchive.h +++ /dev/null @@ -1,102 +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 - -#include -#include "Serialization/IArchive.h" -#include "Serialization/MemoryWriter.h" - -namespace Serialization { - class MemoryWriter; - - class JSONOArchive - : public IArchive - { - public: - // header = 0 - default header, use "" to omit - JSONOArchive(int textWidth = 80, const char* header = 0); - ~JSONOArchive(); - - bool save(const char* fileName); - - const char* c_str() const; - const char* buffer() const { return c_str(); } - size_t length() const; - - // from Archive: - bool operator()(bool& value, const char* name = "", const char* label = 0); - bool operator()(IString& value, const char* name = "", const char* label = 0); - bool operator()(IWString& value, const char* name = "", const char* label = 0); - bool operator()(float& value, const char* name = "", const char* label = 0); - bool operator()(double& value, const char* name = "", const char* label = 0); - bool operator()(int16& value, const char* name = "", const char* label = 0); - bool operator()(uint16& value, const char* name = "", const char* label = 0); - bool operator()(int32& value, const char* name = "", const char* label = 0); - bool operator()(uint32& value, const char* name = "", const char* label = 0); - bool operator()(int64& value, const char* name = "", const char* label = 0); - bool operator()(uint64& value, const char* name = "", const char* label = 0); - - bool operator()(char& value, const char* name = "", const char* label = 0); - bool operator()(int8& value, const char* name = "", const char* label = 0); - bool operator()(uint8& value, const char* name = "", const char* label = 0); - - bool operator()(const SStruct& ser, const char* name = "", const char* label = 0); - bool operator()(const SBlackBox& box, const char* name = "", const char* label = 0); - bool operator()(IContainer& ser, const char* name = "", const char* label = 0); - bool operator()(IKeyValue& keyValue, const char* name = "", const char* label = 0); - bool operator()(IPointer& ser, const char* name = "", const char* label = 0); - // ^^^ - - using IArchive::operator(); - private: - void openBracket(); - void closeBracket(); - void openContainerBracket(); - void closeContainerBracket(); - void placeName(const char* name); - void placeIndent(bool putComma = true); - void placeIndentCompact(bool putComma = true); - - bool joinLinesIfPossible(); - - struct Level - { - Level(bool _isContainer, std::size_t position, int column) - : isKeyValue(false) - , isContainer(_isContainer) - , isDictionary(false) - , startPosition(position) - , nameIndex(0) - , elementIndex(0) - , indentCount(-column) - {} - bool isKeyValue; - bool isContainer; - bool isDictionary; - std::size_t startPosition; - int nameIndex; - int elementIndex; - int indentCount; - }; - - typedef std::vector Stack; - Stack stack_; - std::unique_ptr buffer_; - const char* header_; - int textWidth_; - string fileName_; - int compactOffset_; - bool isKeyValue_; - }; -} diff --git a/Code/CryEngine/CrySystem/Serialization/MemoryReader.cpp b/Code/CryEngine/CrySystem/Serialization/MemoryReader.cpp deleted file mode 100644 index ee424d065f..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/MemoryReader.cpp +++ /dev/null @@ -1,92 +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 "CrySystem_precompiled.h" -#include -#include "Serialization/Assert.h" -#include "MemoryReader.h" -#include -#include - -namespace Serialization { - MemoryReader::MemoryReader() - : size_(0) - , position_(0) - , memory_(0) - , ownedMemory_(false) - { - } - - - MemoryReader::MemoryReader(const void* memory, std::size_t size, bool ownAndFree) - : size_(size) - , position_((const char*)(memory)) - , memory_((const char*)(memory)) - , ownedMemory_(ownAndFree) - { - } - - MemoryReader::~MemoryReader() - { - if (ownedMemory_) - { - free(const_cast(memory_)); - memory_ = 0; - size_ = 0; - } - } - - void MemoryReader::setPosition(const char* position) - { - position_ = position; - } - - void MemoryReader::read(void* data, std::size_t size) - { - YASLI_ASSERT(memory_ && position_); - YASLI_ASSERT(position_ - memory_ + size <= size_); - memcpy(data, position_, size); - position_ += size; - } - - bool MemoryReader::checkedRead(void* data, std::size_t size) - { - if (!memory_ || !position_) - { - return false; - } - if (position_ - memory_ + size > size_) - { - return false; - } - - memcpy(data, position_, size); - position_ += size; - return true; - } - - bool MemoryReader::checkedSkip(std::size_t size) - { - if (!memory_ || !position_) - { - return false; - } - if (position_ - memory_ + size > size_) - { - return false; - } - - position_ += size; - return true; - } -} diff --git a/Code/CryEngine/CrySystem/Serialization/MemoryReader.h b/Code/CryEngine/CrySystem/Serialization/MemoryReader.h deleted file mode 100644 index 88ae1d0060..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/MemoryReader.h +++ /dev/null @@ -1,56 +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 - -#include - -namespace Serialization { - class MemoryReader - { - public: - - MemoryReader(); - MemoryReader(const void* memory, size_t size, bool ownAndFree = false); - ~MemoryReader(); - - void setPosition(const char* position); - const char* position(){ return position_; } - - template - void read(T& value) - { - read(reinterpret_cast(&value), sizoef(value)); - } - void read(void* data, size_t size); - bool checkedSkip(size_t size); - bool checkedRead(void* data, size_t size); - template - bool checkedRead(T& t) - { - return checkedRead((void*)&t, sizeof(t)); - } - - const char* buffer() const{ return memory_; } - size_t size() const{ return size_; } - - const char* begin() const{ return memory_; } - const char* end() const{ return memory_ + size_; } - private: - size_t size_; - const char* position_; - const char* memory_; - bool ownedMemory_; - }; -} -// vim:ts=4 sw=4: diff --git a/Code/CryEngine/CrySystem/Serialization/MemoryWriter.cpp b/Code/CryEngine/CrySystem/Serialization/MemoryWriter.cpp deleted file mode 100644 index c426119812..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/MemoryWriter.cpp +++ /dev/null @@ -1,236 +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 "CrySystem_precompiled.h" -#include -#include "Serialization/Assert.h" -#include -#include -#include -#include -#ifdef _MSC_VER -# include -# define isnan _isnan -#endif - -#include "MemoryWriter.h" - -#undef YASLI_ASSERT -#define YASLI_ASSERT(x) - -namespace Serialization { - MemoryWriter::MemoryWriter(std::size_t size, bool reallocate) - : size_(size) - , reallocate_(reallocate) - , digits_(5) - { - allocate(size); - } - - MemoryWriter::~MemoryWriter() - { - position_ = 0; - CryModuleFree(memory_); - } - - void MemoryWriter::allocate(std::size_t initialSize) - { - memory_ = (char*)CryModuleMalloc(initialSize + 1); - position_ = memory_; - } - - void MemoryWriter::reallocate(std::size_t newSize) - { - YASLI_ASSERT(newSize > size_); - std::size_t pos = position(); - // Supressing the warning as we generally don't handle malloc errors. - // cppcheck-suppress memleakOnRealloc - memory_ = (char*)CryModuleRealloc(memory_, newSize + 1); - YASLI_ASSERT(memory_ != 0); - position_ = memory_ + pos; - size_ = newSize; - } - - MemoryWriter& MemoryWriter::operator<<(int value) - { - // TODO: optimize - char buffer[12]; - sprintf_s(buffer, "%i", value); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(long value) - { - // TODO: optimize - char buffer[12]; -#ifdef _MSC_VER - sprintf_s(buffer, "%i", value); -#else - sprintf_s(buffer, "%li", value); -#endif - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(unsigned long value) - { - // TODO: optimize - char buffer[12]; -#ifdef _MSC_VER - sprintf_s(buffer, "%u", value); -#else - sprintf_s(buffer, "%lu", value); -#endif - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(long long value) - { - // TODO: optimize - char buffer[24]; -#ifdef _MSC_VER - sprintf_s(buffer, "%I64i", value); -#else - sprintf_s(buffer, "%lli", value); -#endif - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(unsigned long long value) - { - // TODO: optimize - char buffer[24]; - sprintf_s(buffer, "%llu", value); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(unsigned int value) - { - // TODO: optimize - char buffer[12]; - sprintf_s(buffer, "%u", value); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(char value) - { - char buffer[12]; - sprintf_s(buffer, "%i", int(value)); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(unsigned char value) - { - char buffer[12]; - sprintf_s(buffer, "%i", int(value)); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(signed char value) - { - char buffer[12]; - sprintf_s(buffer, "%i", int(value)); - return operator<<((const char*)buffer); - } - - inline void cutRightZeros(const char* str) - { - for (char* p = (char*)str + strlen(str) - 1; p >= str; --p) - { - if (*p == '0') - { - *p = 0; - } - else - { - return; - } - } - } - - MemoryWriter& MemoryWriter::operator<<(double value) - { - YASLI_ASSERT(!isnan(value)); - - char buf[64] = { 0 }; - sprintf_s(buf, "%f", value); - operator<<(buf); - return *this; - } - - MemoryWriter& MemoryWriter::operator<<(const char* value) - { - write((void*)value, strlen(value)); - YASLI_ASSERT(position() < size()); - *position_ = '\0'; - return *this; - } - - MemoryWriter& MemoryWriter::operator<<(const wchar_t* value) - { - write((void*)value, wcslen(value) * sizeof(wchar_t)); - YASLI_ASSERT(position() < size()); - *position_ = '\0'; - return *this; - } - - void MemoryWriter::setPosition(std::size_t pos) - { - YASLI_ASSERT(pos < size_); - YASLI_ASSERT(memory_ + pos <= position_); - position_ = memory_ + pos; - } - - void MemoryWriter::write(const char* value) - { - write((void*)value, strlen(value)); - } - - bool MemoryWriter::write(const void* data, std::size_t size) - { - YASLI_ASSERT(memory_ <= position_); - YASLI_ASSERT(position() < this->size()); - if (size_ - position() > size) - { - memcpy(position_, data, size); - position_ += size; - } - else - { - if (!reallocate_) - { - return false; - } - - reallocate(size_ * 2); - write(data, size); - } - YASLI_ASSERT(position() < this->size()); - return true; - } - - void MemoryWriter::write(char c) - { - if (size_ - position() > 1) - { - *(char*)(position_) = c; - ++position_; - } - else - { - YASLI_ESCAPE(reallocate_, return ); - reallocate(size_ * 2); - write(c); - } - YASLI_ASSERT(position() < this->size()); - } -} diff --git a/Code/CryEngine/CrySystem/Serialization/MemoryWriter.h b/Code/CryEngine/CrySystem/Serialization/MemoryWriter.h deleted file mode 100644 index 314a39c2d8..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/MemoryWriter.h +++ /dev/null @@ -1,72 +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 - -#include - -namespace Serialization { - class MemoryWriter - { - public: - MemoryWriter(std::size_t size = 128, bool reallocate = true); - ~MemoryWriter(); - - const char* c_str() { return memory_; }; - const wchar_t* w_str() { return (wchar_t*)memory_; }; - char* buffer() { return memory_; } - const char* buffer() const { return memory_; } - std::size_t size() const{ return size_; } - void clear() { position_ = memory_; } - - // String interface (after this calls '\0' is always written) - MemoryWriter& operator<<(int value); - MemoryWriter& operator<<(long value); - MemoryWriter& operator<<(unsigned long value); - MemoryWriter& operator<<(unsigned int value); - MemoryWriter& operator<<(long long value); - MemoryWriter& operator<<(unsigned long long value); - MemoryWriter& operator<<(float value) { return (*this) << double(value); } - MemoryWriter& operator<<(double value); - MemoryWriter& operator<<(signed char value); - MemoryWriter& operator<<(unsigned char value); - MemoryWriter& operator<<(char value); - MemoryWriter& operator<<(const char* value); - MemoryWriter& operator<<(const wchar_t* value); - - // Binary interface (does not writes trailing '\0') - template - void write(const T& value) - { - write(reinterpret_cast(&value), sizeof(value)); - } - void write(char c); - void write(const char* str); - bool write(const void* data, std::size_t size); - - std::size_t position() const{ return position_ - memory_; } - void setPosition(std::size_t pos); - - MemoryWriter& setDigits(int digits) { digits_ = (unsigned char)digits; return *this; } - - private: - void allocate(std::size_t initialSize); - void reallocate(std::size_t newSize); - - std::size_t size_; - char* position_; - char* memory_; - bool reallocate_; - unsigned char digits_; - }; -} diff --git a/Code/CryEngine/CrySystem/Serialization/Test_ArchiveHost.cpp b/Code/CryEngine/CrySystem/Serialization/Test_ArchiveHost.cpp deleted file mode 100644 index 9608da72c6..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/Test_ArchiveHost.cpp +++ /dev/null @@ -1,492 +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 "CrySystem_precompiled.h" -#include - -#include - -#include "ArchiveHost.h" -#include -#include -#include -#include -#include - -namespace Serialization -{ - struct SMember - { - string name; - float weight; - - SMember() - : weight(0.0f) - {} - - void CheckEquality(const SMember& copy) const - { - EXPECT_TRUE(name == copy.name); - EXPECT_TRUE(weight == copy.weight); - } - - void Change(int index) - { - name = "Changed name "; - name += (index % 10) + '0'; - weight = float(index); - } - - void Serialize(IArchive& ar) - { - ar(name, "name"); - ar(weight, "weight"); - } - }; - - class CPolyBase - : public _i_reference_target_t - { - public: - CPolyBase() - { - baseMember = "Regular base member"; - } - - virtual void Change() - { - baseMember = "Changed base member"; - } - - virtual void Serialize(IArchive& ar) - { - ar(baseMember, "baseMember"); - } - - virtual void CheckEquality(const CPolyBase* copy) const - { - EXPECT_TRUE(baseMember == copy->baseMember); - } - - virtual bool IsDerivedA() const - { - return false; - } - virtual bool IsDerivedB() const - { - return false; - } - protected: - string baseMember; - }; - - class CPolyDerivedA - : public CPolyBase - { - public: - void Serialize(IArchive& ar) - { - CPolyBase::Serialize(ar); - ar(derivedMember, "derivedMember"); - } - - bool IsDerivedA() const override - { - return true; - } - - void CheckEquality(const CPolyBase* copyBase) const - { - EXPECT_TRUE(copyBase->IsDerivedA()); - const CPolyDerivedA* copy = (CPolyDerivedA*)copyBase; - EXPECT_TRUE(derivedMember == copy->derivedMember); - - CPolyBase::CheckEquality(copyBase); - } - protected: - string derivedMember; - }; - - class CPolyDerivedB - : public CPolyBase - { - public: - CPolyDerivedB() - : derivedMember("B Derived") - {} - - bool IsDerivedB() const override - { - return true; - } - - void Serialize(IArchive& ar) - { - CPolyBase::Serialize(ar); - ar(derivedMember, "derivedMember"); - } - - void CheckEquality(const CPolyBase* copyBase) const - { - EXPECT_TRUE(copyBase->IsDerivedB()); - const CPolyDerivedB* copy = (const CPolyDerivedB*)copyBase; - EXPECT_TRUE(derivedMember == copy->derivedMember); - - CPolyBase::CheckEquality(copyBase); - } - protected: - string derivedMember; - }; - - struct SNumericTypes - { - SNumericTypes() - : m_bool(false) - , m_char(0) - , m_int8(0) - , m_uint8(0) - , m_int16(0) - , m_uint16(0) - , m_int32(0) - , m_uint32(0) - , m_int64(0) - , m_uint64(0) - , m_float(0.0f) - , m_double(0.0) - {} - - void Change() - { - m_bool = true; - m_char = -1; - m_int8 = -2; - m_uint8 = 0xff - 3; - m_int16 = -6; - m_uint16 = 0xff - 7; - m_int32 = -4; - m_uint32 = -5; - m_int64 = -8ll; - m_uint64 = 9ull; - m_float = -10.0f; - m_double = -11.0; - } - - void Serialize(IArchive& ar) - { - ar(m_bool, "bool"); - ar(m_char, "char"); - ar(m_int8, "int8"); - ar(m_uint8, "uint8"); - ar(m_int16, "int16"); - ar(m_uint16, "uint16"); - ar(m_int32, "int32"); - ar(m_uint32, "uint32"); - ar(m_int64, "int64"); - ar(m_uint64, "uint64"); - ar(m_float, "float"); - ar(m_double, "double"); - } - - void CheckEquality(const SNumericTypes& rhs) const - { - EXPECT_TRUE(m_bool == rhs.m_bool); - EXPECT_TRUE(m_char == rhs.m_char); - EXPECT_TRUE(m_int8 == rhs.m_int8); - EXPECT_TRUE(m_uint8 == rhs.m_uint8); - EXPECT_TRUE(m_int16 == rhs.m_int16); - EXPECT_TRUE(m_uint16 == rhs.m_uint16); - EXPECT_TRUE(m_int32 == rhs.m_int32); - EXPECT_TRUE(m_uint32 == rhs.m_uint32); - EXPECT_TRUE(m_int64 == rhs.m_int64); - EXPECT_TRUE(m_uint64 == rhs.m_uint64); - EXPECT_TRUE(m_float == rhs.m_float); - EXPECT_TRUE(m_double == rhs.m_double); - } - - bool m_bool; - - char m_char; - int8 m_int8; - uint8 m_uint8; - - int16 m_int16; - uint16 m_uint16; - - int32 m_int32; - uint32 m_uint32; - - int64 m_int64; - uint64 m_uint64; - - float m_float; - double m_double; - }; - - class CComplexClass - { - public: - CComplexClass() - : index(0) - { - name = "Foo"; - stringList.push_back("Choice 1"); - stringList.push_back("Choice 2"); - stringList.push_back("Choice 3"); - - polyPtr.reset(new CPolyDerivedA()); - - polyVector.push_back(new CPolyDerivedB); - polyVector.push_back(new CPolyBase); - - SMember& a = stringToStructMap["a"]; - a.name = "A"; - SMember& b = stringToStructMap["b"]; - b.name = "B"; - - members.resize(13); - - intToString.push_back(std::make_pair(1, "one")); - intToString.push_back(std::make_pair(2, "two")); - intToString.push_back(std::make_pair(3, "three")); - stringToInt.push_back(std::make_pair("one", 1)); - stringToInt.push_back(std::make_pair("two", 2)); - stringToInt.push_back(std::make_pair("three", 3)); - } - - void Change() - { - name = "Slightly changed name"; - index = 2; - polyPtr.reset(new CPolyDerivedB()); - polyPtr->Change(); - - for (size_t i = 0; i < members.size(); ++i) - { - members[i].Change(int(i)); - } - - members.erase(members.begin()); - - for (size_t i = 0; i < polyVector.size(); ++i) - { - polyVector[i]->Change(); - } - - polyVector.resize(4); - polyVector.push_back(new CPolyBase()); - polyVector[4]->Change(); - - const size_t arrayLen = sizeof(array) / sizeof(array[0]); - for (size_t i = 0; i < arrayLen; ++i) - { - array[i].Change(int(arrayLen - i)); - } - - numericTypes.Change(); - - vectorOfStrings.push_back("str1"); - vectorOfStrings.push_back("2str"); - vectorOfStrings.push_back("thirdstr"); - - stringToStructMap.erase("a"); - SMember& c = stringToStructMap["c"]; - c.name = "C"; - - intToString.push_back(std::make_pair(4, "four")); - stringToInt.push_back(std::make_pair("four", 4)); - } - - void Serialize(IArchive& ar) - { - ar(name, "name"); - ar(polyPtr, "polyPtr"); - ar(polyVector, "polyVector"); - ar(members, "members"); - { - StringListValue value(stringList, stringList[index]); - ar(value, "stringList"); - index = value.index(); - if (index == -1) - { - index = 0; - } - } - ar(array, "array"); - ar(numericTypes, "numericTypes"); - ar(vectorOfStrings, "vectorOfStrings"); - ar(stringToInt, "stringToInt"); - } - - void CheckEquality(const CComplexClass& copy) const - { - EXPECT_TRUE(name == copy.name); - EXPECT_TRUE(index == copy.index); - - EXPECT_TRUE(polyPtr != 0); - EXPECT_TRUE(copy.polyPtr != 0); - polyPtr->CheckEquality(copy.polyPtr); - - EXPECT_TRUE(members.size() == copy.members.size()); - for (size_t i = 0; i < members.size(); ++i) - { - members[i].CheckEquality(copy.members[i]); - } - - EXPECT_TRUE(polyVector.size() == copy.polyVector.size()); - for (size_t i = 0; i < polyVector.size(); ++i) - { - if (polyVector[i] == 0) - { - EXPECT_TRUE(copy.polyVector[i] == 0); - continue; - } - EXPECT_TRUE(copy.polyVector[i] != 0); - polyVector[i]->CheckEquality(copy.polyVector[i]); - } - - const size_t arrayLen = sizeof(array) / sizeof(array[0]); - for (size_t i = 0; i < arrayLen; ++i) - { - array[i].CheckEquality(copy.array[i]); - } - - numericTypes.CheckEquality(copy.numericTypes); - - EXPECT_TRUE(stringToInt.size() == copy.stringToInt.size()); - for (size_t i = 0; i < stringToInt.size(); ++i) - { - EXPECT_TRUE(stringToInt[i] == copy.stringToInt[i]); - } - } - protected: - string name; - typedef std::vector Members; - std::vector vectorOfStrings; - std::vector > intToString; - std::vector > stringToInt; - Members members; - int32 index; - SNumericTypes numericTypes; - - StringListStatic stringList; - std::vector< _smart_ptr > polyVector; - _smart_ptr polyPtr; - - std::map stringToStructMap; - - SMember array[5]; - }; - - struct ArchiveHostTests - : ::testing::Test - { - public: - void SetUp() override - { - AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); - - m_classFactoryRTTI = AZStd::make_unique(); - } - - void TearDown() - { - m_classFactoryRTTI.reset(); - - AZ::AllocatorInstance::Destroy(); - AZ::AllocatorInstance::Destroy(); - } - - struct ClassFactoryRTTI - { - ClassFactoryRTTI() - : CPolyBaseCPolyBase_DerivedDescription("base", "Base") - , CPolyBaseCPolyBase_Creator(&CPolyBaseCPolyBase_DerivedDescription) - , TypeCPolyBase_DerivedDescription("derived_a", "Derived A") - , TypeCPolyBase_Creator(&TypeCPolyBase_DerivedDescription) - , CPolyDerivedBCPolyBase_DerivedDescription("derived_b", "Derived B") - , CPolyDerivedBCPolyBase_Creator(&CPolyDerivedBCPolyBase_DerivedDescription) - {} - - ~ClassFactoryRTTI() - { - Serialization::ClassFactory::destroy(); - } - - const Serialization::TypeDescription CPolyBaseCPolyBase_DerivedDescription; - Serialization::ClassFactory::Creator CPolyBaseCPolyBase_Creator; - - const Serialization::TypeDescription TypeCPolyBase_DerivedDescription; - Serialization::ClassFactory::Creator TypeCPolyBase_Creator; - - const Serialization::TypeDescription CPolyDerivedBCPolyBase_DerivedDescription; - Serialization::ClassFactory::Creator CPolyDerivedBCPolyBase_Creator; - }; - AZStd::unique_ptr m_classFactoryRTTI; - }; - - TEST_F(ArchiveHostTests, JsonBasicTypes) - { - std::unique_ptr host(CreateArchiveHost()); - - DynArray bufChanged; - CComplexClass objChanged; - objChanged.Change(); - host->SaveJsonBuffer(bufChanged, SStruct(objChanged)); - EXPECT_TRUE(!bufChanged.empty()); - - DynArray bufResaved; - { - CComplexClass obj; - - EXPECT_TRUE(host->LoadJsonBuffer(SStruct(obj), bufChanged.data(), bufChanged.size())); - EXPECT_TRUE(host->SaveJsonBuffer(bufResaved, SStruct(obj))); - EXPECT_TRUE(!bufResaved.empty()); - - obj.CheckEquality(objChanged); - } - EXPECT_TRUE(bufChanged.size() == bufResaved.size()); - for (size_t i = 0; i < bufChanged.size(); ++i) - { - EXPECT_TRUE(bufChanged[i] == bufResaved[i]); - } - } - - TEST_F(ArchiveHostTests, BinBasicTypes) - { - std::unique_ptr host(CreateArchiveHost()); - - DynArray bufChanged; - CComplexClass objChanged; - objChanged.Change(); - host->SaveBinaryBuffer(bufChanged, SStruct(objChanged)); - EXPECT_TRUE(!bufChanged.empty()); - - DynArray bufResaved; - { - CComplexClass obj; - - EXPECT_TRUE(host->LoadBinaryBuffer(SStruct(obj), bufChanged.data(), bufChanged.size())); - EXPECT_TRUE(host->SaveBinaryBuffer(bufResaved, SStruct(obj))); - EXPECT_TRUE(!bufResaved.empty()); - - obj.CheckEquality(objChanged); - } - EXPECT_TRUE(bufChanged.size() == bufResaved.size()); - for (size_t i = 0; i < bufChanged.size(); ++i) - { - EXPECT_TRUE(bufChanged[i] == bufResaved[i]); - } - } -} - diff --git a/Code/CryEngine/CrySystem/Serialization/Token.h b/Code/CryEngine/CrySystem/Serialization/Token.h deleted file mode 100644 index 4f730054e4..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/Token.h +++ /dev/null @@ -1,89 +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 - -#include - -#include "Serialization/Strings.h" - -namespace Serialization { - struct Token - { - Token(const char* _str = 0) - : start(_str) - , end(_str ? _str + strlen(_str) : 0) - { - } - - Token(const char* _str, size_t _len) - : start(_str) - , end(_str + _len) {} - Token(const char* _start, const char* _end) - : start(_start) - , end(_end) {} - - void set(const char* _start, const char* _end) { start = _start; end = _end; } - std::size_t length() const{ return end - start; } - - bool operator==(const Token& rhs) const - { - if (length() != rhs.length()) - { - return false; - } - return memcmp(start, rhs.start, length()) == 0; - } - bool operator==(const string& rhs) const - { - if (length() != rhs.size()) - { - return false; - } - return memcmp(start, rhs.c_str(), length()) == 0; - } - - bool operator==(const char* text) const - { - if (strncmp(text, start, length()) == 0) - { - return text[length()] == '\0'; - } - return false; - } - bool operator!=(const char* text) const - { - if (strncmp(text, start, length()) == 0) - { - return text[length()] != '\0'; - } - return true; - } - bool operator==(char c) const - { - return length() == 1 && *start == c; - } - bool operator!=(char c) const - { - return length() != 1 || *start != c; - } - - operator bool() const{ - return start != end; - } - string str() const{ return string(start, end); } - - const char* start; - const char* end; - }; -} diff --git a/Code/CryEngine/CrySystem/Serialization/XmlIArchive.cpp b/Code/CryEngine/CrySystem/Serialization/XmlIArchive.cpp deleted file mode 100644 index 914b7857e0..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/XmlIArchive.cpp +++ /dev/null @@ -1,297 +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 "CrySystem_precompiled.h" -#include "CryExtension/Impl/ClassWeaver.h" - -#include -#include - -#include "XmlIArchive.h" - -#include -#include - -namespace XmlUtil -{ - int g_hintSuccess = 0; - int g_hintFail = 0; - - - XmlNodeRef FindChildNode(XmlNodeRef pParent, const int childIndexOverride, int& childIndexHint, const char* const name) - { - CRY_ASSERT(pParent); - - if (0 <= childIndexOverride) - { - CRY_ASSERT(childIndexOverride < pParent->getChildCount()); - return pParent->getChild(childIndexOverride); - } - else - { - CRY_ASSERT(name); - CRY_ASSERT(name[ 0 ]); - CRY_ASSERT(0 <= childIndexHint); - - const int childCount = pParent->getChildCount(); - const bool hasValidChildHint = (childIndexHint < childCount); - if (hasValidChildHint) - { - XmlNodeRef pChildNode = pParent->getChild(childIndexHint); - if (pChildNode->isTag(name)) - { - g_hintSuccess++; - const int nextChildIndexHint = childIndexHint + 1; - childIndexHint = (nextChildIndexHint < childCount) ? nextChildIndexHint : 0; - return pChildNode; - } - else - { - g_hintFail++; - } - } - - for (int i = 0; i < childCount; ++i) - { - XmlNodeRef pChildNode = pParent->getChild(i); - if (pChildNode->isTag(name)) - { - const int nextChildIndexHint = i + 1; - childIndexHint = (nextChildIndexHint < childCount) ? nextChildIndexHint : 0; - return pChildNode; - } - } - } - return XmlNodeRef(); - } - - - template< typename T, typename TOut > - bool ReadChildNodeAs(XmlNodeRef pParent, const int childIndexOverride, int& childIndexHint, const char* const name, TOut& valueOut) - { - XmlNodeRef pChild = FindChildNode(pParent, childIndexOverride, childIndexHint, name); - if (pChild) - { - T tmp; - const bool readValueSuccess = pChild->getAttr("value", tmp); - if (readValueSuccess) - { - valueOut = tmp; - } - return readValueSuccess; - } - return false; - } - - - template< typename T > - bool ReadChildNode(XmlNodeRef pParent, const int childIndexOverride, int& childIndexHint, const char* const name, T& valueOut) - { - return ReadChildNodeAs< T >(pParent, childIndexOverride, childIndexHint, name, valueOut); - } -} - - -Serialization::CXmlIArchive::CXmlIArchive() - : IArchive(INPUT | NO_EMPTY_NAMES) - , m_childIndexOverride(-1) - , m_childIndexHint(0) -{ -} - - -Serialization::CXmlIArchive::CXmlIArchive(XmlNodeRef pRootNode) - : IArchive(INPUT | NO_EMPTY_NAMES) - , m_pRootNode(pRootNode) - , m_childIndexOverride(-1) - , m_childIndexHint(0) -{ - CRY_ASSERT(m_pRootNode); -} - - -Serialization::CXmlIArchive::~CXmlIArchive() -{ -} - - -void Serialization::CXmlIArchive::SetXmlNode(XmlNodeRef pNode) -{ - m_pRootNode = pNode; -} - - -XmlNodeRef Serialization::CXmlIArchive::GetXmlNode() const -{ - return m_pRootNode; -} - - -bool Serialization::CXmlIArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) -{ - XmlNodeRef pChild = XmlUtil::FindChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name); - if (pChild) - { - const char* const stringValue = pChild->getAttr("value"); - if (stringValue) - { - value = (strcmp("true", stringValue) == 0); - value = value || (strcmp("1", stringValue) == 0); - return true; - } - return false; - } - return false; -} - - -bool Serialization::CXmlIArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) -{ - XmlNodeRef pChild = XmlUtil::FindChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name); - if (pChild) - { - const char* const stringValue = pChild->getAttr("value"); - if (stringValue) - { - value.set(stringValue); - return true; - } - return false; - } - return false; -} - - -bool Serialization::CXmlIArchive::operator()([[maybe_unused]] IWString& value, [[maybe_unused]] const char* name, [[maybe_unused]] const char* label) -{ - CryFatalError("CXmlIArchive::operator() with IWString is not implemented"); - return false; -} - - -bool Serialization::CXmlIArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNodeAs< int >(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNodeAs< uint >(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNodeAs< int >(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNodeAs< uint >(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNodeAs< int >(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) -{ - CRY_ASSERT(name); - CRY_ASSERT(name[ 0 ]); - - XmlNodeRef pChild = XmlUtil::FindChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name); - if (pChild) - { - CXmlIArchive childArchive(pChild); - childArchive.SetFilter(GetFilter()); - childArchive.SetInnerContext(GetInnerContext()); - - const bool serializeSuccess = ser(childArchive); - return serializeSuccess; - } - return false; -} - - -bool Serialization::CXmlIArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) -{ - CRY_ASSERT(name); - CRY_ASSERT(name[ 0 ]); - - bool serializeSuccess = true; - - XmlNodeRef pChild = XmlUtil::FindChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name); - if (pChild) - { - const int elementCount = pChild->getChildCount(); - ser.resize(elementCount); - - if (0 < elementCount) - { - CXmlIArchive childArchive(pChild); - childArchive.SetFilter(GetFilter()); - childArchive.SetInnerContext(GetInnerContext()); - - for (int i = 0; i < elementCount; ++i) - { - childArchive.m_childIndexOverride = i; - - serializeSuccess &= ser(childArchive, "Element", "Element"); - ser.next(); - } - } - } - - return serializeSuccess; -} diff --git a/Code/CryEngine/CrySystem/Serialization/XmlIArchive.h b/Code/CryEngine/CrySystem/Serialization/XmlIArchive.h deleted file mode 100644 index dd23febef6..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/XmlIArchive.h +++ /dev/null @@ -1,62 +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 __XML_I_ARCHIVE__H__ -#define __XML_I_ARCHIVE__H__ - -#include - -namespace Serialization -{ - class CXmlIArchive - : public IArchive - { - public: - CXmlIArchive(); - CXmlIArchive(XmlNodeRef pRootNode); - ~CXmlIArchive(); - - void SetXmlNode(XmlNodeRef pNode); - XmlNodeRef GetXmlNode() const; - - // IArchive - bool operator()(bool& value, const char* name = "", const char* label = 0) override; - bool operator()(IString& value, const char* name = "", const char* label = 0) override; - bool operator()(IWString& value, const char* name = "", const char* label = 0) override; - bool operator()(float& value, const char* name = "", const char* label = 0) override; - bool operator()(double& value, const char* name = "", const char* label = 0) override; - bool operator()(int16& value, const char* name = "", const char* label = 0) override; - bool operator()(uint16& value, const char* name = "", const char* label = 0) override; - bool operator()(int32& value, const char* name = "", const char* label = 0) override; - bool operator()(uint32& value, const char* name = "", const char* label = 0) override; - bool operator()(int64& value, const char* name = "", const char* label = 0) override; - bool operator()(uint64& value, const char* name = "", const char* label = 0) override; - - bool operator()(int8& value, const char* name = "", const char* label = 0) override; - bool operator()(uint8& value, const char* name = "", const char* label = 0) override; - bool operator()(char& value, const char* name = "", const char* label = 0) override; - - bool operator()(const SStruct& ser, const char* name = "", const char* label = 0) override; - bool operator()(IContainer& ser, const char* name = "", const char* label = 0) override; - // ~IArchive - - using IArchive::operator(); - - private: - XmlNodeRef m_pRootNode; - int m_childIndexOverride; - int m_childIndexHint; - }; -} - -#endif diff --git a/Code/CryEngine/CrySystem/Serialization/XmlOArchive.cpp b/Code/CryEngine/CrySystem/Serialization/XmlOArchive.cpp deleted file mode 100644 index 1133a7e51e..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/XmlOArchive.cpp +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "CryExtension/Impl/ClassWeaver.h" - -#include -#include - -#include "XmlOArchive.h" - -#include -#include - -namespace XmlUtil -{ - XmlNodeRef CreateChildNode(XmlNodeRef pParent, const char* const name) - { - CRY_ASSERT(pParent); - CRY_ASSERT(name); - CRY_ASSERT(name[ 0 ]); - - XmlNodeRef pChild = pParent->createNode(name); - CRY_ASSERT(pChild); - - pParent->addChild(pChild); - return pChild; - } - - template < typename T, typename TIn > - bool WriteChildNodeAs(XmlNodeRef pParent, const char* const name, const TIn& value) - { - XmlNodeRef pChild = XmlUtil::CreateChildNode(pParent, name); - CRY_ASSERT(pChild); - - pChild->setAttr("value", static_cast< T >(value)); - return true; - } - - template < typename T > - bool WriteChildNode(XmlNodeRef pParent, const char* const name, const T& value) - { - return WriteChildNodeAs< T >(pParent, name, value); - } -} - -Serialization::CXmlOArchive::CXmlOArchive() - : IArchive(OUTPUT | NO_EMPTY_NAMES) -{ -} - - -Serialization::CXmlOArchive::CXmlOArchive(XmlNodeRef pRootNode) - : IArchive(OUTPUT | NO_EMPTY_NAMES) - , m_pRootNode(pRootNode) -{ - CRY_ASSERT(m_pRootNode); -} - - -Serialization::CXmlOArchive::~CXmlOArchive() -{ -} - - -void Serialization::CXmlOArchive::SetXmlNode(XmlNodeRef pNode) -{ - m_pRootNode = pNode; -} - - -XmlNodeRef Serialization::CXmlOArchive::GetXmlNode() const -{ - return m_pRootNode; -} - - -bool Serialization::CXmlOArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) -{ - const char* const stringValue = value ? "true" : "false"; - return XmlUtil::WriteChildNode(m_pRootNode, name, stringValue); -} - - -bool Serialization::CXmlOArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) -{ - const char* const stringValue = value.get(); - return XmlUtil::WriteChildNode(m_pRootNode, name, stringValue); -} - - -bool Serialization::CXmlOArchive::operator()([[maybe_unused]] IWString& value, [[maybe_unused]] const char* name, [[maybe_unused]] const char* label) -{ - CryFatalError("CXmlOArchive::operator() with IWString is not implemented"); - return false; -} - - -bool Serialization::CXmlOArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNode(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNode(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNodeAs< int >(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNodeAs< uint >(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNode(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNode(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNode(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNode(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNodeAs< int >(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNodeAs< uint >(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNodeAs< int >(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) -{ - CRY_ASSERT(name); - CRY_ASSERT(name[ 0 ]); - - XmlNodeRef pChild = XmlUtil::CreateChildNode(m_pRootNode, name); - CXmlOArchive childArchive(pChild); - childArchive.SetFilter(GetFilter()); - childArchive.SetInnerContext(GetInnerContext()); - - const bool serializeSuccess = ser(childArchive); - - return serializeSuccess; -} - - -bool Serialization::CXmlOArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) -{ - CRY_ASSERT(name); - CRY_ASSERT(name[ 0 ]); - - bool serializeSuccess = true; - - XmlNodeRef pChild = XmlUtil::CreateChildNode(m_pRootNode, name); - CXmlOArchive childArchive(pChild); - childArchive.SetFilter(GetFilter()); - childArchive.SetInnerContext(GetInnerContext()); - - const size_t containerSize = ser.size(); - if (0 < containerSize) - { - do - { - serializeSuccess &= ser(childArchive, "Element", "Element"); - } while (ser.next()); - } - - return serializeSuccess; -} diff --git a/Code/CryEngine/CrySystem/Serialization/XmlOArchive.h b/Code/CryEngine/CrySystem/Serialization/XmlOArchive.h deleted file mode 100644 index 4451d2ba75..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/XmlOArchive.h +++ /dev/null @@ -1,60 +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 __XML_O_ARCHIVE__H__ -#define __XML_O_ARCHIVE__H__ - -#include - -namespace Serialization -{ - class CXmlOArchive - : public IArchive - { - public: - CXmlOArchive(); - CXmlOArchive(XmlNodeRef pRootNode); - ~CXmlOArchive(); - - void SetXmlNode(XmlNodeRef pNode); - XmlNodeRef GetXmlNode() const; - - // IArchive - bool operator()(bool& value, const char* name = "", const char* label = 0) override; - bool operator()(IString& value, const char* name = "", const char* label = 0) override; - bool operator()(IWString& value, const char* name = "", const char* label = 0) override; - bool operator()(float& value, const char* name = "", const char* label = 0) override; - bool operator()(double& value, const char* name = "", const char* label = 0) override; - bool operator()(int16& value, const char* name = "", const char* label = 0) override; - bool operator()(uint16& value, const char* name = "", const char* label = 0) override; - bool operator()(int32& value, const char* name = "", const char* label = 0) override; - bool operator()(uint32& value, const char* name = "", const char* label = 0) override; - bool operator()(int64& value, const char* name = "", const char* label = 0) override; - bool operator()(uint64& value, const char* name = "", const char* label = 0) override; - - bool operator()(int8& value, const char* name = "", const char* label = 0) override; - bool operator()(uint8& value, const char* name = "", const char* label = 0) override; - bool operator()(char& value, const char* name = "", const char* label = 0) override; - - bool operator()(const SStruct& ser, const char* name = "", const char* label = 0) override; - bool operator()(IContainer& ser, const char* name = "", const char* label = 0) override; - // ~IArchive - - using IArchive::operator(); - - private: - XmlNodeRef m_pRootNode; - }; -} - -#endif diff --git a/Code/CryEngine/CrySystem/ServiceNetwork.cpp b/Code/CryEngine/CrySystem/ServiceNetwork.cpp deleted file mode 100644 index 4ead14bcba..0000000000 --- a/Code/CryEngine/CrySystem/ServiceNetwork.cpp +++ /dev/null @@ -1,2035 +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 : Service network implementation - - -#include "CrySystem_precompiled.h" -#include "ServiceNetwork.h" -#include "RemoteCommandHelpers.h" - -#include - -//----------------------------------------------------------------------------- - -// network system internal logging -#ifdef RELEASE - #define LOG_VERBOSE(level, txt, ...) -#else - #define LOG_VERBOSE(level, txt, ...) if (GetManager()->CheckVerbose(level)) { GetManager()->Log(txt, __VA_ARGS__); } -#endif - -//----------------------------------------------------------------------------- - -namespace -{ - union AddValueConv - { - struct - { - uint8 ip0, ip1, ip2, ip3; - } bytes; - - uint32 u32; - }; - - inline void TranslateAddress(const ServiceNetworkAddress& addr, AZ::AzSock::AzSocketAddress& outAddr) - { - AddValueConv addr_value; - addr_value.bytes.ip0 = addr.GetAddress().m_ip0; - addr_value.bytes.ip1 = addr.GetAddress().m_ip1; - addr_value.bytes.ip2 = addr.GetAddress().m_ip2; - addr_value.bytes.ip3 = addr.GetAddress().m_ip3; - - outAddr.SetAddress(addr_value.u32, addr.GetAddress().m_port); - } - - inline void TranslateAddress(const AZ::AzSock::AzSocketAddress& addr, ServiceNetworkAddress& outAddr) - { - AddValueConv addr_value; - - const AZSOCKADDR_IN* addrIn = reinterpret_cast(addr.GetTargetAddress()); - addr_value.u32 = AZ::AzSock::NetToHostLong((*addrIn).sin_addr.s_addr); - - outAddr = ServiceNetworkAddress( - addr_value.bytes.ip0, - addr_value.bytes.ip1, - addr_value.bytes.ip2, - addr_value.bytes.ip3, - addr.GetAddrPort()); - } - - inline bool SocketConnectionsFull(AZ::AzSock::AzSockError error) - { - return (error == AZ::AzSock::AzSockError::eASE_NO_ERROR || error == AZ::AzSock::AzSockError::eASE_EWOULDBLOCK || error == AZ::AzSock::AzSockError::eASE_EWOULDBLOCK_CONN); - } -} - -//----------------------------------------------------------------------------- - -CServiceNetworkMessage::CServiceNetworkMessage(const uint32 id, const uint32 size) - : m_refCount(1) - , m_size(size) - , m_id(id) -{ - // Allocate buffer memory - m_pData = CryModuleMalloc(size); -} - -CServiceNetworkMessage::~CServiceNetworkMessage() -{ - // Release the memory buffer - CryModuleFree(m_pData); - m_pData = NULL; -} - -uint32 CServiceNetworkMessage::GetSize() const -{ - return m_size; -} - -uint32 CServiceNetworkMessage::GetId() const -{ - return m_id; -} - -void* CServiceNetworkMessage::GetPointer() -{ - return m_pData; -} - -const void* CServiceNetworkMessage::GetPointer() const -{ - return m_pData; -} - -void CServiceNetworkMessage::AddRef() -{ - CryInterlockedIncrement(&m_refCount); -} - -void CServiceNetworkMessage::Release() -{ - if (0 == CryInterlockedDecrement(&m_refCount)) - { - delete this; - } -} - -IDataReadStream* CServiceNetworkMessage::CreateReader() const -{ - return new CDataReadStreamFormMessage(this); -} - -//----------------------------------------------------------------------------- - -void CServiceNetworkConnection::Header::Swap() -{ - // if we are on big endian system swap data to LE - // NOTE: this is a little bit confusing so see how the eLittleEndian and eBigEndian is defined - SwapEndian(m_size, eLittleEndian); -} - -void CServiceNetworkConnection::InitHeader::Swap() -{ - // if we are on big endian system swap data to LE - // NOTE: this is a little bit confusing so see how the eLittleEndian and eBigEndian is defined - SwapEndian(m_tryCount, eLittleEndian); - SwapEndian(m_guid0, eLittleEndian); - SwapEndian(m_guid1, eLittleEndian); -} - -//----------------------------------------------------------------------------- - -CServiceNetworkConnection::CServiceNetworkConnection( - class CServiceNetwork* manager, - EEndpoint endpointType, - AZSOCKET socket, - const CryGUID& connectionID, - const ServiceNetworkAddress& localAddress, - const ServiceNetworkAddress& remoteAddress) - - : m_pManager(manager) - , m_connectionID(connectionID) - , m_socket(socket) - , m_localAddress(localAddress) - , m_remoteAddress(remoteAddress) - , m_endpointType(endpointType) - , m_state(eState_Initializing) - , m_sendQueueDataSize(0) - , m_receiveQueueDataSize(0) - , m_messageDataSentSoFar(0) - , m_messageDataReceivedSoFar(0) - , m_bCloseRequested(false) - , m_pCurrentReceiveMessage(NULL) - , m_messageReceiveLength(0) - , m_messageDummyReadLength(0) - , m_reconnectTryCount(0) - , m_bDisableCommunication(false) - , m_pSendedMessages(NULL) - , m_refCount(1) -{ - // put the socket back in non blocking mode - AZ::AzSock::SetSocketBlockingMode(m_socket, false); - - // reset stats - m_statsNumDataSend = 0; - m_statsNumDataReceived = 0; - m_statsNumPacketsSend = 0; - m_statsNumPacketsReceived = 0; - - // reset timers to values at the creation time - const uint64 currentNetworkTime = m_pManager->GetNetworkTime(); - m_lastReconnectTime = currentNetworkTime; - m_lastMessageReceivedTime = currentNetworkTime; - m_lastInitializationSendTime = currentNetworkTime; - - // make sure keep alive messages are sent as soon as possible - m_lastKeepAliveSendTime = currentNetworkTime - kKeepAlivePeriod; - - LOG_VERBOSE(3, "Connection(): local='%s', remote='%s', this=%p", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); -} - -CServiceNetworkConnection::~CServiceNetworkConnection() -{ - // in here we must be already closed! - CRY_ASSERT(m_state == eState_Closed); - - LOG_VERBOSE(3, "~Connection(): local='%s', remote='%s', this=%p", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - // can happen - if (m_pCurrentReceiveMessage != NULL) - { - m_pCurrentReceiveMessage->Release(); - m_pCurrentReceiveMessage = NULL; - } -} - -void CServiceNetworkConnection::AddRef() -{ - CryInterlockedIncrement(&m_refCount); -} - -void CServiceNetworkConnection::Release() -{ - if (0 == CryInterlockedDecrement(&m_refCount)) - { - delete this; - } -} - -void CServiceNetworkConnection::Close() -{ - LOG_VERBOSE(2, "Connection local='%s', remote='%s', this=%p: close requested", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - m_bCloseRequested = true; - m_bDisableCommunication = true; -} - -void CServiceNetworkConnection::FlushAndClose(const uint32 timeout) -{ - if (!m_bDisableCommunication) - { - // We don't have any messages on the waiting list, we can close immediately - if (m_pSendQueue.empty()) - { - // Normal close - Close(); - } - else - { - LOG_VERBOSE(2, "Connection local='%s', remote='%s', this=%p: flush and close requested", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - // Disable communication layer so no more new messages can be transmitted - m_bDisableCommunication = true; - - // Register in the manager list of connections to close after sending queue is empty - m_pManager->RegisterForDeferredClose(*this, timeout); - } - } -} - -void CServiceNetworkConnection::FlushAndWait() -{ - // Disable communication layer so no more new messages can be transmitted - m_bDisableCommunication = true; - - // Wait for the connection to be empty - while (IsAlive() && !m_pSendQueue.empty()) - { - Sleep(1); - } - - // Resume communication layer - m_bDisableCommunication = false; -} - -const CryGUID& CServiceNetworkConnection::GetGUID() const -{ - return m_connectionID; -} - -const ServiceNetworkAddress& CServiceNetworkConnection::GetRemoteAddress() const -{ - return m_remoteAddress; -} - -const ServiceNetworkAddress& CServiceNetworkConnection::GetLocalAddress() const -{ - return m_localAddress; -} - -void CServiceNetworkConnection::Reset() -{ - if (m_state == eState_Initializing || m_state == eState_Valid) - { - // Close the socket (we wont be able to use it anyway) - if (AZ::AzSock::IsAzSocketValid(m_socket)) - { - AZ::AzSock::Shutdown(m_socket, SD_BOTH); - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - } - - // Reset messages buffers pointers - m_messageDataSentSoFar = 0; - m_messageDataReceivedSoFar = 0; - - // release current in-flight message - if (m_pCurrentReceiveMessage != NULL) - { - m_pCurrentReceiveMessage->Release(); - m_pCurrentReceiveMessage = NULL; - } - - // reset reconnection timer - m_lastMessageReceivedTime = m_pManager->GetNetworkTime(); - m_lastReconnectTime = m_pManager->GetNetworkTime(); - - // we are in the lost state now, we can try to reconnect - m_state = eState_Lost; - - LOG_VERBOSE(2, "Connection local='%s', remote='%s', this=%p: LOST!", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - } -} - -void CServiceNetworkConnection::Shutdown() -{ - // Close the socket - if (AZ::AzSock::IsAzSocketValid(m_socket)) - { - AZ::AzSock::Shutdown(m_socket, SD_BOTH); - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - } - - // Release all pending messages (they wont be sent anyway) - while (!m_pSendQueue.empty()) - { - CServiceNetworkMessage* message = m_pSendQueue.pop(); - message->Release(); - } - - // release current in-flight message - if (m_pCurrentReceiveMessage != NULL) - { - m_pCurrentReceiveMessage->Release(); - m_pCurrentReceiveMessage = NULL; - } - - // Reset internal send/recv state - m_messageDataSentSoFar = 0; - m_messageDataReceivedSoFar = 0; - - // Force the state - m_state = eState_Closed; - - LOG_VERBOSE(2, "Connection local='%s', remote='%s', this=%p: CLOSED!", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); -} - -void CServiceNetworkConnection::Update() -{ - const uint64 currentNetworkTime = m_pManager->GetNetworkTime(); - - // We requested to close the socket - if (m_bCloseRequested) - { - m_bCloseRequested = false; - Shutdown(); - return; - } - - // State machine - switch (m_state) - { - // Connection is closed, nothing to do - case eState_Closed: - { - break; - } - - // We are still not initialized fully - case eState_Initializing: - { - // receive messages when waiting for connection - ProcessReceivingQueue(); - - // if we are a client send the connection initialization messages - if (m_endpointType == eEndpoint_Client) - { - // General timeout handling - if (HandleTimeout(currentNetworkTime)) - { - // do not send to often - if ((currentNetworkTime - m_lastInitializationSendTime) > kInitializationPerior) - { - // send the initialization message - if (TryInitialize()) - { - // message was sent, wait a moment before sending next one - m_lastInitializationSendTime = currentNetworkTime; - } - } - } - } - else if (m_endpointType == eEndpoint_Server) - { - // Server side when waiting for full initialization is sending the "keep alive" messages - // Note that we cannot time out on this end - ProcessKeepAlive(); - } - - break; - } - - // Connection is lost - case eState_Lost: - { - // if we are the client endpoint we can try to reconnect to the server - if (m_endpointType == eEndpoint_Client) - { - // do not try to reconnect to often (floods the network) - if ((currentNetworkTime - m_lastReconnectTime) > kReconnectTryPerior) - { - // reset timer - m_lastReconnectTime = currentNetworkTime; - - // try to reconnect - if (TryReconnect()) - { - // put the socket back in non blocking mode - AZ::AzSock::SetSocketBlockingMode(m_socket, false); - - // give us some slack with timeout after reconnection - m_lastMessageReceivedTime = currentNetworkTime; - - // yeah, we got reconnected, try to reinitialize the connection - m_messageDataReceivedSoFar = 0; - m_state = eState_Initializing; - } - } - } - else if (m_endpointType == eEndpoint_Server) - { - // wait for the reconnection timeout - if ((currentNetworkTime - m_lastMessageReceivedTime) > hReconnectTimeOut) - { - // reconnection time out has occurred - LOG_VERBOSE(2, "Connection local='%s', remote='%s', this=%p: reconnection timeout", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - // Close - Shutdown(); - } - } - - break; - } - - // Valid connection - case eState_Valid: - { - // Is it time to send a keep alive message? - ProcessKeepAlive(); - - // Process the queue of messages - ProcessSendingQueue(); - ProcessReceivingQueue(); - - // General timeout handling - if (m_endpointType == eEndpoint_Client) - { - HandleTimeout(currentNetworkTime); - } - - break; - } - - default: - { - // should not happen - break; - } - } -} - -bool CServiceNetworkConnection::HandleTimeout(const uint64 currentNetworkTime) -{ - // Connections never time out when there is a debugger attached -#if defined(WIN32) || defined(WIN64) - if (IsDebuggerPresent()) - { - // connection is still alive - return true; - } -#endif - - // Connection time out when there is a long time without any activity from server side (no keep alive or other messages) - const uint64 timeSinceLastMessage = currentNetworkTime - m_lastMessageReceivedTime; - if (timeSinceLastMessage > kTimeout) - { - // Connection has timed out - LOG_VERBOSE(1, "Connection local='%s', remote='%s', this=%p: timed out", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - // Put in lost state, wait a while before reconnecting - m_lastReconnectTime = currentNetworkTime; - m_state = eState_Lost; - - // Close the socket now - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - - // Connection was lost - return false; - } - - // Connection still alive - return true; -} - -bool CServiceNetworkConnection::TryInitialize() -{ - // This is sent only be clients trying to establish connection with server - // Connection ID is sent over to the server so he can easily identify re connections (even when port changes) - - // Initialization data header - InitHeader header; - header.m_cmd = eCommand_Initialize; - header.m_pad0 = 0; - header.m_pad1 = 0; - header.m_pad2 = 0; - header.m_tryCount = m_reconnectTryCount; - header.m_guid0 = m_connectionID.lopart; - header.m_guid1 = m_connectionID.hipart; - - // Swap the endianess in header (for sending) - header.Swap(); - - // Try send - const bool autoHandleErrors = false; // we do not need errors here - const uint32 dataLeft = sizeof(header) - m_messageDataSentSoFar; - const uint32 ret = TrySend(&header, dataLeft, autoHandleErrors); - m_messageDataSentSoFar += ret; - - // Full packet was sent - if (m_messageDataSentSoFar == sizeof(header)) - { - // We sent the initialization message - LOG_VERBOSE(1, "Connection local='%s', remote='%s', this=%p: init message sent, try counter=%d", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - m_reconnectTryCount); - - // we sent the initialization packet, reset - m_messageDataSentSoFar = 0; - return true; - } - - // Still not valid - return false; -} - -bool CServiceNetworkConnection::TryReconnect() -{ - // We can't reconnect with disabled communication - if (m_bDisableCommunication) - { - return false; - } - - // Create new socket if needed - if (!AZ::AzSock::IsAzSocketValid(m_socket)) - { - m_socket = AZ::AzSock::Socket(); - if (!AZ::AzSock::IsAzSocketValid(m_socket)) - { - // We sent the initialization message - LOG_VERBOSE(1, "Connection local='%s', remote='%s', this=%p: failed to recreate socket", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - return false; - } - } - - // Translate remote address - AZ::AzSock::AzSocketAddress addr; - TranslateAddress(m_remoteAddress, addr); - - // When reconnecting always use the blocking mode - AZ::AzSock::SetSocketBlockingMode(m_socket, true); - - // every time we reconnect increment the internal counter so the receiving end (server) - // will be able to identity the up-to-date connection (and discard the older one) - CRY_ASSERT(m_endpointType == eEndpoint_Client); - m_reconnectTryCount += 1; - - // Connect (blocking) - const int result = AZ::AzSock::Connect(m_socket, addr); - if (result == 0) - { - // Spew to log (important info) - LOG_VERBOSE(0, "Connection local='%s', remote='%s', this=%p: SUCCESSFULLY RECONNECTED", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - // When connected put socket in the non blocking mode - AZ::AzSock::SetSocketBlockingMode(m_socket, false); - - // connected! - return true; - } - - // not connection, should not happen often - LOG_VERBOSE(2, "Connection local='%s', remote='%s', this=%p: failed to reconnect", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - // still not connected - return false; -} - -void CServiceNetworkConnection::SendKeepAlive(const uint64 currentNetworkTime) -{ - // Keep alive message is just ONE byte (makes it easier) - uint8 message = eCommand_KeepAlive; - if (1 == TrySend(&message, 1, false)) - { - // Throttle the sending - m_lastKeepAliveSendTime = currentNetworkTime; - - // At high verbose level we need even this :) - LOG_VERBOSE(3, "Connection local='%s', remote='%s', this=%p: keep alive SENT", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - } -} - -void CServiceNetworkConnection::ProcessSendingQueue() -{ - // Get the top message from the send queue - if (NULL == m_pSendedMessages) - { - m_pSendedMessages = m_pSendQueue.pop(); - if (NULL == m_pSendedMessages) - { - return; - } - } - - // Get the size of the data to transmit - const uint32 messageSize = m_pSendedMessages->GetSize(); - const uint32 headerSize = sizeof(Header); - - // Nothing sent yet, send header - if (m_messageDataSentSoFar < headerSize) - { - // prepare header - endian safe - Header header; - header.m_cmd = eCommand_Data; - header.m_size = messageSize; - - // Swap the header for reading - header.Swap(); - - // send the header - const uint32 dataLeft = headerSize - m_messageDataSentSoFar; - const uint32 sent = TrySend((const char*)&header + m_messageDataSentSoFar, dataLeft, true); - m_messageDataSentSoFar += sent; - } - - // Send message data - const uint32 endOfDataOffset = messageSize + headerSize; - if (m_messageDataSentSoFar >= headerSize && m_messageDataSentSoFar < endOfDataOffset) - { - // send and advance - const uint32 dataLeft = endOfDataOffset - m_messageDataSentSoFar; - const uint32 dataOffset = m_messageDataSentSoFar - headerSize; - const uint32 sent = TrySend((const char*)m_pSendedMessages->GetPointer() + dataOffset, dataLeft, true); - m_messageDataSentSoFar += sent; - } - - // All the data from the message was sent, release the message from this queue - // Note: this message may still be in some other sent queues for connections - if (m_messageDataSentSoFar >= endOfDataOffset) - { - // At high verbose level we need even this :) - LOG_VERBOSE(3, "Connection local='%s', remote='%s', this=%p: message ID %d (size=%d) removed from queue", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - m_pSendedMessages->GetId(), - m_pSendedMessages->GetSize()); - - CryInterlockedAdd(&m_sendQueueDataSize, -(int)m_pSendedMessages->GetSize()); - - // stats (not collected in release builds) -#ifndef RELEASE - CryInterlockedIncrement((volatile int*) &m_statsNumPacketsSend); -#endif - - // release local message reference - m_pSendedMessages->Release(); - m_pSendedMessages = NULL; - - // rewind to zero to indicate fresh message - m_messageDataSentSoFar = 0; - } -} - -void CServiceNetworkConnection::ProcessKeepAlive() -{ - const uint64 currentNetworkTime = m_pManager->GetNetworkTime(); - if ((currentNetworkTime - m_lastKeepAliveSendTime) > kKeepAlivePeriod) - { - // Well, if we are in the middle of something make sure we do not interrupt it with KeepAlive - if (m_messageDataSentSoFar == 0) - { - SendKeepAlive(currentNetworkTime); - } - } -} - -void CServiceNetworkConnection::ProcessReceivingQueue() -{ - // To much data already, do not process - const uint32 kReceivedDataLimit = m_pManager->GetReceivedDataQueueLimit(); - if (m_receiveQueueDataSize > kReceivedDataLimit) - { - return; - } - - // Internal offset - const uint32 kOffsetHeader = 1; - const uint32 kOffsetData = 5; - - // Dummy receive - while (m_messageDummyReadLength > 0) - { - // batch size - const uint32 kTempBufferSize = 256; - - // read dummy data - uint8 tempBuffer[ kTempBufferSize ]; - const uint32 maxRead = min(kTempBufferSize, m_messageDummyReadLength); - const uint32 readCount = TryReceive(tempBuffer, maxRead, false); - m_messageDummyReadLength -= readCount; - - // got less - if (readCount < maxRead) - { - break; - } - } - - // Do not process normal messages until we receive all of the bogus data - if (m_messageDummyReadLength > 0) - { - return; - } - - // First byte - header - if (m_messageDataReceivedSoFar == 0) - { - // message header, read type - uint8 messageType = 0; - const int result = TryReceive(&messageType, 1, true); - if (result == 1) - { - // keep alive received, if we are not yet fully initialized it's the signal that we are :) - if (messageType == eCommand_KeepAlive) - { - // we got confirmed by server - if (m_state == eState_Initializing) - { - // change state - CRY_ASSERT(m_endpointType == eEndpoint_Client); - m_state = eState_Valid; - - // At high verbose level we need even this :) - LOG_VERBOSE(1, "Connection local='%s', remote='%s', this=%p: connection confirmed by server", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - } - else - { - // At low-level verbose log even this - LOG_VERBOSE(3, "Connection local='%s', remote='%s', this=%p: keep alive RECEIVED", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - } - - // update the keep alive data timer - m_lastKeepAliveSendTime = m_pManager->GetNetworkTime(); - m_lastMessageReceivedTime = m_pManager->GetNetworkTime(); - } - else if (messageType == eCommand_Data) - { - // wait for the message length - m_messageReceiveLength = 0; - m_messageDataReceivedSoFar = kOffsetHeader; - m_lastMessageReceivedTime = m_pManager->GetNetworkTime(); - - // At low-level verbose log even this - LOG_VERBOSE(3, "Connection local='%s', remote='%s', this=%p: got data message header", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - } - else if (messageType == eCommand_Initialize) - { - // let the system process the message - m_messageDummyReadLength = sizeof(InitHeader) - 1; - - // At low-level verbose log even this - LOG_VERBOSE(3, "Connection local='%s', remote='%s', this=%p: outdated initheader received", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - } - else - { - // Serious error - LOG_VERBOSE(0, "Connection local='%s', remote='%s', this=%p: received invalid command (%d)", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - messageType); - - // reset the connection - Reset(); - } - } - } - - // Message length - if (m_messageDataReceivedSoFar >= kOffsetHeader && m_messageDataReceivedSoFar < kOffsetData) - { - // receive the message length - const uint32 dataOffset = m_messageDataReceivedSoFar - kOffsetHeader; - const uint32 dataLeft = sizeof(uint32) - dataOffset; - const uint32 len = TryReceive((char*)&m_messageReceiveLength + dataOffset, dataLeft, true); - m_messageDataReceivedSoFar += len; - - // Update last message time - if (len > 0) - { - m_lastMessageReceivedTime = m_pManager->GetNetworkTime(); - } - - // full length received - if (m_messageDataReceivedSoFar == 5) - { - // Swap endianess (for BE platforms) - // NOTE: if this is a little bit confusing, see how the eLittleEndian and eBigEndian are defined - SwapEndian(m_messageReceiveLength, eLittleEndian); - - // Sanity check on the message size - if (m_messageReceiveLength > kMaximumMessageSize) - { - // Serious error - LOG_VERBOSE(0, "Connection local='%s', remote='%s', this=%p: unsupported message size (%d)", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - m_messageReceiveLength); - - Reset(); - } - else if (m_messageReceiveLength > 0) - { - // Create new message that we will add the data into - CRY_ASSERT(m_pCurrentReceiveMessage == NULL); - m_pCurrentReceiveMessage = static_cast< CServiceNetworkMessage* >(m_pManager->AllocMessageBuffer(m_messageReceiveLength)); - CRY_ASSERT(m_pCurrentReceiveMessage != NULL); - - // Serious error - LOG_VERBOSE(2, "Connection local='%s', remote='%s', this=%p: created receive buffer ID %d, (size=%d)", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - m_pCurrentReceiveMessage ? m_pCurrentReceiveMessage->GetId() : 0, - m_messageReceiveLength); - } - } - } - - // Message data - if (m_messageDataReceivedSoFar >= kOffsetData) - { - CRY_ASSERT(m_pCurrentReceiveMessage != NULL); - PREFAST_ASSUME(m_pCurrentReceiveMessage); - - // Message fully received, put in the receive queue (at the end!) - const uint32 dataOffset = m_messageDataReceivedSoFar - kOffsetData; - const uint32 dataLeft = m_pCurrentReceiveMessage->GetSize() - dataOffset; - const uint32 len = TryReceive((char*)m_pCurrentReceiveMessage->GetPointer() + dataOffset, dataLeft, true); - m_messageDataReceivedSoFar += len; - - // connection got lost - if (m_state == eState_Lost) - { - return; - } - - // Update last message time - if (len > 0) - { - m_lastMessageReceivedTime = m_pManager->GetNetworkTime(); - } - - // Full message received! - if (m_messageDataReceivedSoFar == (kOffsetData + m_pCurrentReceiveMessage->GetSize())) - { - // Serious error - LOG_VERBOSE(2, "Connection local='%s', remote='%s', this=%p: full message received(%d), adding to queue", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - m_pCurrentReceiveMessage->GetSize()); - - // Put in the receive queue, only if no communication is disabled - if (m_bDisableCommunication) - { - m_pCurrentReceiveMessage->Release(); - } - else - { - m_pReceiveQueue.push(m_pCurrentReceiveMessage); - } - - // Stats (not collected in release builds) -#ifndef RELEASE - CryInterlockedIncrement((volatile int*) &m_statsNumPacketsReceived); -#endif - - // Reset - m_pCurrentReceiveMessage = NULL; - m_messageDataReceivedSoFar = 0; - } - } -} - -uint32 CServiceNetworkConnection::TrySend(const void* dataBuffer, uint32 dataSize, bool autoHandleErrors /*=true*/) -{ - // Send the data - const int ret = AZ::AzSock::Send(m_socket, (const char*) dataBuffer, dataSize, 0); - if (AZ::AzSock::SocketErrorOccured(ret)) - { - // We would block, that's not an error - if (ret == static_cast(AZ::AzSock::AzSockError::eASE_EWOULDBLOCK)) - { - return 0; - } - - // Report connection problems - LOG_VERBOSE(1, "Connection local='%s', remote='%s', this=%p: send() error: %d", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - ret); - - // Put connection in the lost state - if (autoHandleErrors) - { - Reset(); - } - - // Nothing was sent (according to our logic) - return 0; - } - - // Update stats -#ifndef RELEASE - CryInterlockedAdd((volatile int*) &m_statsNumDataSend, ret); -#endif - - // Return the true amount of data sent - return ret; -} - -uint32 CServiceNetworkConnection::TryReceive(void* dataBuffer, uint32 dataSize, bool autoHandleErrors) -{ - // Send the data - const int ret = AZ::AzSock::Recv(m_socket, (char*) dataBuffer, dataSize, 0); - if (AZ::AzSock::SocketErrorOccured(ret)) - { - // We would block, that's not an error - if (ret == static_cast(AZ::AzSock::AzSockError::eASE_EWOULDBLOCK)) - { - return 0; - } - - // Connection was closed - if (ret == static_cast(AZ::AzSock::AzSockError::eASE_ECONNRESET)) - { - // Report connection problems - LOG_VERBOSE(1, "Connection local='%s', remote='%s', this=%p: CLOSED BY PEER", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - // Shutdown socket - Shutdown(); - return 0; - } - - // Report connection problems - LOG_VERBOSE(1, "Connection local='%s', remote='%s', this=%p: recv() error: %d", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - ret); - - // Put connection in the lost state - if (autoHandleErrors) - { - Reset(); - } - - // Nothing was sent (according to our logic) - return 0; - } - - // Update stats -#ifndef RELEASE - CryInterlockedAdd((volatile int*) &m_statsNumDataReceived, ret); -#endif - - // Return the true amount of data sent - return ret; -} - -bool CServiceNetworkConnection::SendMsg(IServiceNetworkMessage* message) -{ - // Invalid message - if (NULL == message || message->GetSize() == 0) - { - return false; - } - - // Communication layer is disabled, not possible to send any more messages - if (m_bDisableCommunication) - { - return false; - } - - // Process data size limits - { - const uint32 sizeAfterThisMessage = m_sendQueueDataSize + message->GetSize(); - const uint32 sendQueueLimit = m_pManager->GetSendDataQueueLimit(); - if (sizeAfterThisMessage > sendQueueLimit) - { - // Report connection problems - LOG_VERBOSE(0, "Connection local='%s', remote='%s', this=%p: to much data on send queue", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - // To much data on the queue already, we will not be sending this message - return false; - } - - // Keep the local reference so the source data does not get deleted - message->AddRef(); - - // Update the queue data size - CryInterlockedAdd(&m_sendQueueDataSize, message->GetSize()); - - // Append the message to the sending queue - m_pSendQueue.push(static_cast< CServiceNetworkMessage* >(message)); - } - - // Well, we can't tell any more than that - return true; -} - -IServiceNetworkMessage* CServiceNetworkConnection::ReceiveMsg() -{ - // Anything on the queue ? - IServiceNetworkMessage* message = NULL; - if (!m_pReceiveQueue.empty()) - { - message = m_pReceiveQueue.pop(); - - // Report connection problems - LOG_VERBOSE(3, "Connection local='%s', remote='%s', this=%p: message ID %d (size=%d) popped by receive end", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - message->GetId(), - message->GetSize()); - } - - return message; -} - -bool CServiceNetworkConnection::IsAlive() const -{ - return m_state != eState_Closed; -} - -uint32 CServiceNetworkConnection::GetMessageSendCount() const -{ - return m_statsNumPacketsSend; -} - -uint32 CServiceNetworkConnection::GetMessageReceivedCount() const -{ - return m_statsNumPacketsReceived; -} - -uint64 CServiceNetworkConnection::GetMessageSendDataSize() const -{ - return m_statsNumDataSend; -} - -uint64 CServiceNetworkConnection::GetMessageReceivedDataSize() const -{ - return m_statsNumDataReceived; -} - -bool CServiceNetworkConnection::HandleReconnect(AZSOCKET socket, const uint32 tryCount) -{ - CRY_ASSERT(m_endpointType == eEndpoint_Server); - - // connection is older - if (tryCount < m_reconnectTryCount) - { - LOG_VERBOSE(3, "Connection local='%s', remote='%s', this=%p: reconnection request OLDER (%d<%d)", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - tryCount, - m_reconnectTryCount); - - return false; - } - - // should not happen - if (tryCount == m_reconnectTryCount) - { - LOG_VERBOSE(0, "Connection local='%s', remote='%s', this=%p: reconnection request COLLISION (%d==%d)", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - tryCount, - m_reconnectTryCount); - - return false; - } - - // newer connection, close current socket - AZ::AzSock::Shutdown(m_socket, SD_BOTH); - AZ::AzSock::CloseSocket(m_socket); - - // reset send/receive counters (will resend last message from the queue) - m_messageDataReceivedSoFar = 0; - m_messageDataSentSoFar = 0; - - // Set new socket and update reconnection counter - m_socket = socket; - m_reconnectTryCount = tryCount; - - // revive the connection - m_state = eState_Valid; - - LOG_VERBOSE(0, "Connection local='%s', remote='%s', this=%p: successfull reconnection with counter (%d)", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - m_reconnectTryCount); - - // processed - return true; -} - -//----------------------------------------------------------------------------- - -CServiceNetworkListener::CServiceNetworkListener(CServiceNetwork* pManager, AZSOCKET socket, const ServiceNetworkAddress& address) - : m_pManager(pManager) - , m_socket(socket) - , m_localAddress(address) - , m_closeRequestReceived(false) - , m_refCount(1) -{ - LOG_VERBOSE(3, "Listener() local='%s', this=%p", - m_localAddress.ToString().c_str(), - (UINT_PTR) this); -} - -CServiceNetworkListener::~CServiceNetworkListener() -{ - AZ_Assert(!AZ::AzSock::IsAzSocketValid(m_socket), "AZSocket still valid on ServiceNetworkListener destructor"); - - LOG_VERBOSE(3, "~Listener() local='%s', this=%p", - m_localAddress.ToString().c_str(), - (UINT_PTR) this); -} - -void CServiceNetworkListener::Update() -{ - // We requested to close this listener - if (m_closeRequestReceived) - { - LOG_VERBOSE(3, "Listener local='%s', this=%p: closing due to request", - m_localAddress.ToString().c_str(), - (UINT_PTR) this); - - // Close the socket - if (AZ::AzSock::IsAzSocketValid(m_socket)) - { - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - } - - // Close all connections - for (TConnectionList::iterator it = m_pLocalConnections.begin(); - it != m_pLocalConnections.end(); ++it) - { - (*it)->Close(); - (*it)->Release(); - } - - m_pLocalConnections.clear(); - m_closeRequestReceived = false; - - return; - } - - // Process connection requests - ProcessIncomingConnections(); - - // Service the pending connection - ProcessPendingConnections(); - - // Remove any local connection that got dead - for (TConnectionList::iterator it = m_pLocalConnections.begin(); - it != m_pLocalConnections.end(); /*++it*/) - { - if (!(*it)->IsAlive()) - { - LOG_VERBOSE(2, "Listener local='%s', this=%p: removing dead connection '%s' (%p)", - m_localAddress.ToString().c_str(), - (UINT_PTR) this, - (*it)->GetRemoteAddress().ToString().c_str(), - (UINT_PTR) (*it)); - - (*it)->Release(); - it = m_pLocalConnections.erase(it); - } - else - { - ++it; - } - } -} - -const ServiceNetworkAddress& CServiceNetworkListener::GetLocalAddress() const -{ - return m_localAddress; -} - -uint32 CServiceNetworkListener::GetConnectionCount() const -{ - // not safe ? - return m_pLocalConnections.size(); -} - -IServiceNetworkConnection* CServiceNetworkListener::Accept() -{ - // Look for any connection on the list that is in the "initialized" state - { - CryAutoLock lock(m_accessLock); - for (TConnectionList::iterator it = m_pLocalConnections.begin(); - it != m_pLocalConnections.end(); ++it) - { - // we are looking for connections in the "eState_Initializing" which mean that they are valid but not yet recognized by the outside world - CServiceNetworkConnection* con = (*it); - if (con->m_state == CServiceNetworkConnection::eState_Initializing) - { - LOG_VERBOSE(1, "Listener local='%s', this=%p: accepting connection from '%s' (%p)", - m_localAddress.ToString().c_str(), - (UINT_PTR) this, - con->GetRemoteAddress().ToString().c_str(), - (UINT_PTR) con); - - // switch state to "valid" - con->m_state = CServiceNetworkConnection::eState_Valid; - - // when returning outside increment the ref count (we still want to keep our internal reference) - con->AddRef(); - return con; - } - } - } - - // No pending connections - return NULL; -} - -bool CServiceNetworkListener::IsAlive() const -{ - return AZ::AzSock::IsAzSocketValid(m_socket); -} - -void CServiceNetworkListener::AddRef() -{ - CryInterlockedIncrement(&m_refCount); -} - -void CServiceNetworkListener::Release() -{ - if (0 == CryInterlockedDecrement(&m_refCount)) - { - delete this; - } -} - -void CServiceNetworkListener::Close() -{ - LOG_VERBOSE(2, "Listener local='%s', this=%p: close requested", - m_localAddress.ToString().c_str(), - (UINT_PTR) this); - - m_closeRequestReceived = true; -} - -void CServiceNetworkListener::ProcessIncomingConnections() -{ - // Accept all possible connections as soon as possible (the connect side is blocking) - for (;; ) - { - // Get the pending connection from TCP/IP layers - AZ::AzSock::AzSocketAddress remoteAddrInet; - AZSOCKET sock = AZ::AzSock::Accept(m_socket, remoteAddrInet); - - // No more connections - if (SocketConnectionsFull(AZ::AzSock::AzSockError(sock))) - { - break; - } - - // Different error - if (!AZ::AzSock::IsAzSocketValid(sock)) - { - // Connection has other problems - LOG_VERBOSE(1, "Listener local='%s', this=%p: accept() error: %d", - m_localAddress.ToString().c_str(), - (UINT_PTR) this, - (int)sock); - - break; - } - - // Get the remote address - ServiceNetworkAddress remoteAddress; - TranslateAddress(remoteAddrInet, remoteAddress); - - // Any way create a new pending connection information - PendingConnection* pendingConnection = new PendingConnection; - pendingConnection->m_remoteAddress = remoteAddress; - pendingConnection->m_dataReceivedSoFar = 0; - pendingConnection->m_socket = sock; - - // Connection has other problems - LOG_VERBOSE(2, "Listener local='%s', this=%p: new pending connection from '%s'", - m_localAddress.ToString().c_str(), - (UINT_PTR) this, - remoteAddress.ToString().c_str()); - - // Add to list (not locked because its used only from net thread) - m_pPendingConnections.push_back(pendingConnection); - } -} - -void CServiceNetworkListener::ProcessPendingConnections() -{ - // Process only pending connections, not locked because its used only from net thread - for (TPendingConnectionList::iterator it = m_pPendingConnections.begin(); - it != m_pPendingConnections.end(); /*++it*/) - { - PendingConnection& con = *(*it); - - // Read the incoming data - CRY_ASSERT(con.m_dataReceivedSoFar < sizeof(con.m_initHeader)); - const uint32 dataLeft = sizeof(con.m_initHeader) - con.m_dataReceivedSoFar; - const int size = AZ::AzSock::Recv(con.m_socket, (char*)&con.m_initHeader + con.m_dataReceivedSoFar, dataLeft, 0); - - // The only no-action case: no data yet - if (size == static_cast(AZ::AzSock::AzSockError::eASE_EWOULDBLOCK)) - { - ++it; - continue; - } - - // Something more important - if (AZ::AzSock::SocketErrorOccured(size)) - { - // well, some problem on the way, remove the pending connection from the list (client will resend) - LOG_VERBOSE(1, "Listener local='%s', this=%p: pending connection from '%s' lost: %d", - m_localAddress.ToString().c_str(), - (UINT_PTR) this, - con.m_remoteAddress.ToString().c_str(), - (int)size); - } - else - { - // data was received - CRY_ASSERT(size < (int)dataLeft); - con.m_dataReceivedSoFar += size; - - // still not enough data - if (con.m_dataReceivedSoFar < sizeof(con.m_initHeader)) - { - ++it; - continue; - } - - // validate header - if (con.m_initHeader.m_cmd == CServiceNetworkConnection::eCommand_Initialize) - { - // Swap the header after reading - con.m_initHeader.Swap(); - - // Extract the connection ID - const CryGUID connectionId = CryGUID::Construct(con.m_initHeader.m_guid0, con.m_initHeader.m_guid1); - - // try find existing connection with the same connection GUID (reconnection) - CServiceNetworkConnection* existingConnection = NULL; - for (TConnectionList::const_iterator jt = m_pLocalConnections.begin(); - jt != m_pLocalConnections.end(); ++jt) - { - if ((*jt)->GetGUID() == connectionId) - { - existingConnection = *jt; - break; - } - } - - // if existing connection was found that we probably were trying to reconnect - if (existingConnection != NULL) - { - // we already have this connection on our list and we got reconnected with the some GUID - // this usually means that the client has lost communication with server for some time - LOG_VERBOSE(1, "Listener local='%s', this=%p: reconnection from '%s'", - m_localAddress.ToString().c_str(), - (UINT_PTR) this, - con.m_remoteAddress.ToString().c_str()); - - // substitute the connection with newer one (if it is really newer) - if (!existingConnection->HandleReconnect(con.m_socket, con.m_initHeader.m_tryCount)) - { - // well, we didn't use this connect (it was older than the current one, close it) - AZ::AzSock::Shutdown(con.m_socket, SD_BOTH); - AZ::AzSock::CloseSocket(con.m_socket); - } - else - { - // add to global list of active debug connections (so we can start receiving data) - m_pManager->RegisterConnection(*existingConnection); - } - } - else - { - // no previous connection registered, create one now - CServiceNetworkConnection* newConnection = new CServiceNetworkConnection( - m_pManager, - CServiceNetworkConnection::eEndpoint_Server, // this connection is created from listener side which is considered the "server" - con.m_socket, - connectionId, - m_localAddress, - con.m_remoteAddress); - - // this is the first time we see this connection on set the proper connection counter - newConnection->m_reconnectTryCount = con.m_initHeader.m_tryCount; - - // happy moment, log it - LOG_VERBOSE(0, "Listener local='%s', this=%p: confirmed connection from '%s'", - m_localAddress.ToString().c_str(), - (UINT_PTR) this, - con.m_remoteAddress.ToString().c_str()); - - // make sure connection is in valid state - CRY_ASSERT(newConnection->m_state == CServiceNetworkConnection::eState_Initializing); - - // add to local list - CRY_ASSERT(newConnection->IsInitialized() == false); - { - CryAutoLock lock(m_accessLock); - m_pLocalConnections.push_back(newConnection); - newConnection->AddRef(); - } - - // add to global list of active debug connections (so we can start receiving data) - m_pManager->RegisterConnection(*newConnection); - } - } - else - { - // well, some problem on the way, remove the pending connection from the list (client will resend) - LOG_VERBOSE(0, "Listener local='%s', this=%p: invalid connection data received from '%s'", - m_localAddress.ToString().c_str(), - (UINT_PTR) this, - con.m_remoteAddress.ToString().c_str()); - - // close the socket - AZ::AzSock::Shutdown(con.m_socket, SD_BOTH); - AZ::AzSock::CloseSocket(con.m_socket); - } - } - - // any way, delete the connection from the pending list - delete (*it); - it = m_pPendingConnections.erase(it); - } -} - -//----------------------------------------------------------------------------- - -CServiceNetwork::CServiceNetwork() - : m_networkTime(0) - , m_bExitRequested(false) - , m_bufferID(1) -{ - // Create the CVAR - m_pVerboseLevel = gEnv->pConsole->RegisterInt("net_debugVerboseLevel", 0, VF_DEV_ONLY); - - // Send/receive Queue size limits - m_pReceiveDataQueueLimit = gEnv->pConsole->RegisterInt("net_receiveQueueSize", 20 << 20, VF_DEV_ONLY); - m_pSendDataQueueLimit = gEnv->pConsole->RegisterInt("net_sendQueueSize", 5 << 20, VF_DEV_ONLY); - - // Reinitialize the random number generator with independent seed value - m_guidGenerator.Seed((uint32)GetNetworkTime()); - - // Start thread - m_pThread = new TServiceNetworkThread(); - m_pThread->Start(*this); -} - -CServiceNetwork::~CServiceNetwork() -{ - // Signal the network thread to stop - if (NULL != m_pThread) - { - m_pThread->Cancel(); - m_pThread->WaitForThread(); - delete m_pThread; - } - - // Release all closeing connections - for (TConnectionsToCloseArray::const_iterator it = m_connectionsToClose.begin(); - it != m_connectionsToClose.end(); ++it) - { - (*it).pConnection->Release(); - } - - // Release and close all connections - for (TConnectionArray::const_iterator it = m_pConnections.begin(); - it != m_pConnections.end(); ++it) - { - (*it)->Close(); - (*it)->Release(); - } - - // Release all listeners - for (TListenerArray::const_iterator it = m_pListeners.begin(); - it != m_pListeners.end(); ++it) - { - (*it)->Release(); - } - - // Release the CVars - SAFE_RELEASE(m_pVerboseLevel); - SAFE_RELEASE(m_pReceiveDataQueueLimit); - SAFE_RELEASE(m_pSendDataQueueLimit); -} - -#ifndef RELEASE -bool CServiceNetwork::CheckVerbose(const uint32 level) const -{ - const int verboseLevel = m_pVerboseLevel->GetIVal(); - return (int)level < verboseLevel; -} - -void CServiceNetwork::Log(const char* txt, ...) const -{ - // format the print buffer - char buffer[512]; - va_list ap; - va_start(ap, txt); - vsprintf_s(buffer, sizeof(buffer), txt, ap); - va_end(ap); - - // pass to log - gEnv->pLog->LogAlways(buffer); -} -#endif - -void CServiceNetwork::Cancel() -{ - m_bExitRequested = true; - - if (m_pThread) - { - m_pThread->Stop(); - } -} - -void CServiceNetwork::Run() -{ - CryThreadSetName(THREADID_NULL, "ServiceNetworkThread"); - -#if defined(AZ_RESTRICTED_PLATFORM) -#include AZ_RESTRICTED_FILE(ServiceNetwork_cpp) -#endif - - TListenerArray updatingListeners; - TConnectionArray updatingConnections; - TConnectionsToCloseArray updatingConnectionsToClose; - - // Process messages - while (!m_bExitRequested) - { - // Well, copy the lists for the duration of update - { - CryAutoLock lock(m_accessMutex); - updatingListeners = m_pListeners; - updatingConnections = m_pConnections; - updatingConnectionsToClose = m_connectionsToClose; - } - - if ((!gEnv) || (!gEnv->pTimer)) - { - Sleep(5); - continue; - } - - // Update network time - m_networkTime = gEnv->pTimer->GetAsyncTime().GetMilliSecondsAsInt64(); - - // Process the listeners (accepts and pending connections) - for (TListenerArray::const_iterator it = updatingListeners.begin(); - it != updatingListeners.end(); ++it) - { - (*it)->Update(); - - // Remove dead listeners from the main list - if (!(*it)->IsAlive()) - { - CryAutoLock lock(m_accessMutex); - - // remove from array - TListenerArray::iterator jt = std::find(m_pListeners.begin(), m_pListeners.end(), *it); - CRY_ASSERT(jt != m_pListeners.end()); - m_pListeners.erase(jt); - - // release internal reference (may delete object if no longer used on main thread) - (*it)->Release(); - } - } - - - // Process the closing connections - for (TConnectionsToCloseArray::const_iterator it = updatingConnectionsToClose.begin(); - it != updatingConnectionsToClose.end(); ++it) - { - const ConnectionToClose& info = *it; - - bool bTimeout = false; - if (info.maxWaitTime && m_networkTime > info.maxWaitTime) - { - bTimeout = true; - } - - // should we close it now ? - if (bTimeout || !it->pConnection->IsAlive() || it->pConnection->IsSendingQueueEmpty()) - { - info.pConnection->Close(); - info.pConnection->Release(); - - // erase from list - { - CryAutoLock lock(m_accessMutex); - for (TConnectionsToCloseArray::iterator jt = m_connectionsToClose.begin(); - jt != m_connectionsToClose.end(); ++jt) - { - if ((*jt).pConnection == info.pConnection) - { - m_connectionsToClose.erase(jt); - break; - } - } - } - } - } - - // Process the connections - for (TConnectionArray::const_iterator it = updatingConnections.begin(); - it != updatingConnections.end(); ++it) - { - (*it)->Update(); - - // Remove dead connections from the main list - if (!(*it)->IsAlive()) - { - CryAutoLock lock(m_accessMutex); - - // remove from array - TConnectionArray::iterator jt = std::find(m_pConnections.begin(), m_pConnections.end(), *it); - CRY_ASSERT(jt != m_pConnections.end()); - m_pConnections.erase(jt); - - // release internal reference (may delete object if no longer used on main thread) - (*it)->Release(); - } - } - - // Internal delay - // TODO: this is guess work right now - Sleep(5); - } -} - -void CServiceNetwork::SetVerbosityLevel(const uint32 level) -{ - // propagate the value to CVar (so it is consistent across the engine) - if (NULL != m_pVerboseLevel) - { - m_pVerboseLevel->Set((int)level); - } -} - -IServiceNetworkMessage* CServiceNetwork::AllocMessageBuffer(const uint32 size) -{ - // Allocate message with new ID - const uint32 bufferID = CryInterlockedIncrement(&m_bufferID); - return new CServiceNetworkMessage(bufferID, size); -} - -IDataWriteStream* CServiceNetwork::CreateMessageWriter() -{ - return new CDataWriteStreamBuffer(); -} - -IDataReadStream* CServiceNetwork::CreateMessageReader(const void* pData, const uint32 dataSize) -{ - if (pData != NULL && dataSize > 0) - { - return new CDataReadStreamMemoryBuffer(pData, dataSize); - } - - return NULL; -} - -ServiceNetworkAddress CServiceNetwork::GetHostAddress(const string& addressString, uint16 optionalPort /*=0*/) const -{ - // cut the address into base and port part - string hostname = addressString.c_str(); - - const int pos = addressString.rfind(':'); - if (pos != -1) - { - // substitute the port number from the part in string - if (optionalPort == 0) - { - const char* portNumberStr = addressString.c_str() + pos + 1; - optionalPort = (uint16)atoi(portNumberStr); - } - - // remove the port part from base address - hostname = addressString.Left(pos); - } - - AZ::AzSock::AzSocketAddress socketAddress; - socketAddress.SetAddress(hostname.c_str(), optionalPort); - - // log on hi verbose mode - LOG_VERBOSE(3, "GetHostAddress(%s) -> %s", addressString.c_str(), socketAddress.GetAddress().c_str()); - - // format the network address - ServiceNetworkAddress out; - TranslateAddress(socketAddress, out); - return out; -} - -IServiceNetworkListener* CServiceNetwork::CreateListener(uint16 localPort) -{ - // Create socket - AZSOCKET createdSocket = AZ::AzSock::Socket(); - if (!AZ::AzSock::IsAzSocketValid(createdSocket)) - { - // Connection has other problems - LOG_VERBOSE(0, "CreateListener(%d): socket() failed: %s", localPort, AZ::AzSock::GetStringForError(createdSocket)); - return NULL; - } - - // Disable merging of small blocks to fight high latency connection - // NOTE: consoles support this mode by default - const int ret3 = AZ::AzSock::EnableTCPNoDelay(createdSocket, true); - if (AZ::AzSock::SocketErrorOccured(ret3)) - { - // Connection has other problems - LOG_VERBOSE(0, "CreateListener(%d): setsockopt() failed: %s", localPort, AZ::AzSock::GetStringForError(ret3)); - - AZ::AzSock::CloseSocket(createdSocket); - return NULL; - } - - // Reuse address - { - const int optRet = AZ::AzSock::SetSocketOption(createdSocket, AZ::AzSock::AzSocketOption::REUSEADDR, true); - if (AZ::AzSock::SocketErrorOccured(optRet)) - { - // Connection has other problems - LOG_VERBOSE(0, "CreateListener(%d): setsockopt() (reuse) failed", localPort); - - // cleanup - AZ::AzSock::CloseSocket(createdSocket); - return NULL; - } - } - - // Put the listener socket in the non blocking mode - if (!AZ::AzSock::SetSocketBlockingMode(createdSocket, false)) - { - // Connection has other problems - LOG_VERBOSE(0, "CreateListener(%d): setsockopt() failed", localPort); - - // cleanup - AZ::AzSock::CloseSocket(createdSocket); - return NULL; - } - - // Setup local bind address - AZ::AzSock::AzSocketAddress service; - service.SetAddrPort(localPort); - - // Bind socket - const int ret = AZ::AzSock::Bind(createdSocket, service); - if (AZ::AzSock::SocketErrorOccured(ret)) - { - // Connection has other problems - LOG_VERBOSE(0, "CreateListener(%d): bind() failed: %s", localPort, AZ::AzSock::GetStringForError(createdSocket)); - - // cleanup - AZ::AzSock::CloseSocket(createdSocket); - return NULL; - } - - // Listen for incoming connection requests on the created socket - const int ret2 = AZ::AzSock::Listen(createdSocket, 64 /*backLogSize*/); - if (AZ::AzSock::SocketErrorOccured(ret2)) - { - // Connection has other problems - LOG_VERBOSE(0, "CreateListener(%d): listen() failed: %s", localPort, AZ::AzSock::GetStringForError(createdSocket)); - - // cleanup - AZ::AzSock::CloseSocket(createdSocket); - return NULL; - } - - // Get our local address - AZ::AzSock::AzSocketAddress localAddressInet; - AZ::AzSock::GetSockName(createdSocket, localAddressInet); - - // Translate to debug network address data - ServiceNetworkAddress localAddress; - TranslateAddress(localAddressInet, localAddress); - - // Spew to log (important info) - LOG_VERBOSE(0, "bind() to '%s'", localAddress.ToString().c_str()); - - // Create the listener wrapper - CServiceNetworkListener* listener = new CServiceNetworkListener(this, createdSocket, localAddress); - - // Listener was created - LOG_VERBOSE(0, "CreateListener(%d): listener created, local address=%s", localPort, listener->GetLocalAddress().ToString().c_str()); - - // Add to list of local listeners - { - CryAutoLock lock(m_accessMutex); - m_pListeners.push_back(listener); - listener->AddRef(); - } - - // Return wrapping interface - return listener; -} - -void CServiceNetwork::RegisterConnection(CServiceNetworkConnection& con) -{ - CryAutoLock lock(m_accessMutex); - - // Make sure to register each connection only once - TConnectionArray::const_iterator it = std::find(m_pConnections.begin(), m_pConnections.end(), &con); - if (it == m_pConnections.end()) - { - // Low-level info - LOG_VERBOSE(3, "RegisterConnection(): registered connection from '%s' to '%s', %p", - con.GetLocalAddress().ToString().c_str(), - con.GetRemoteAddress().ToString().c_str(), - (UINT_PTR) &con); - - // add to connections list, that means we need to also increment the refcount - m_pConnections.push_back(&con); - con.AddRef(); - } -} - -void CServiceNetwork::RegisterForDeferredClose(CServiceNetworkConnection& con, const uint32 timeout) -{ - CryAutoLock lock(m_accessMutex); - - // Low-level info - LOG_VERBOSE(3, "RegisterConnection(): registered connection from '%s' to '%s', %p for defered close, timeout=%d", - con.GetLocalAddress().ToString().c_str(), - con.GetRemoteAddress().ToString().c_str(), - (UINT_PTR) &con, - timeout); - - // Add to connections list, that means we need to also increment the refcount - ConnectionToClose info; - info.pConnection = &con; - info.maxWaitTime = (timeout > 0) ? (GetNetworkTime() + timeout) : 0; - m_connectionsToClose.push_back(info); - - // Keep internal reference - con.AddRef(); -} - -IServiceNetworkConnection* CServiceNetwork::Connect(const ServiceNetworkAddress& remoteAddress) -{ - // Create new socket if needed - AZSOCKET socket = AZ::AzSock::Socket(); - if (!AZ::AzSock::IsAzSocketValid(socket)) - { - // Connection has problems - LOG_VERBOSE(0, "Connect(%s): socket() failed: %s", remoteAddress.ToString().c_str(), AZ::AzSock::GetStringForError(socket)); - return NULL; - } - - // Translate remote address - AZ::AzSock::AzSocketAddress addr; - TranslateAddress(remoteAddress, addr); - - // Spew to log (important info) - LOG_VERBOSE(1, "Connecting to '%s'...", remoteAddress.ToString().c_str()); - - // Connect (blocking) - const int result = AZ::AzSock::Connect(socket, addr); - if (AZ::AzSock::SocketErrorOccured(result)) - { - // Spew to log (important info) - LOG_VERBOSE(0, "connect() to '%s' failed: %s", remoteAddress.ToString().c_str(), AZ::AzSock::GetStringForError(result)); - return NULL; - } - - // Get the address of local socket endpoint - // Get our local address - AZ::AzSock::AzSocketAddress localAddressInet; - AZ::AzSock::GetSockName(socket, localAddressInet); - - // Translate to debug network address data - ServiceNetworkAddress localAddress; - TranslateAddress(localAddressInet, localAddress); - - // Spew to log (important info) - LOG_VERBOSE(1, "connected() from '%s' to '%s'", localAddress.ToString().c_str(), remoteAddress.ToString().c_str()); - - // Allocate some connection ID - const uint64 loPart = m_guidGenerator.GenerateUint64(); - const uint64 hiPart = m_guidGenerator.GenerateUint64(); - const CryGUID connectionID = CryGUID::Construct(loPart, hiPart); - - // Spew to log (important info) - LOG_VERBOSE(3, "New connection GUID: %08x-%08x-%08x-%08x", (uint64)(hiPart >> 32), (uint64)(hiPart & 0xFFFFFFFF), (uint64)(loPart >> 32), (uint64)(loPart & 0xFFFFFFFF)); - - // Create connection wrapper - CServiceNetworkConnection* newConnection = new CServiceNetworkConnection( - this, - CServiceNetworkConnection::eEndpoint_Client, // we are the client, we are connecting to remove destination - socket, - connectionID, - localAddress, - remoteAddress); - - // Add to list of connections - { - CryAutoLock lock(m_accessMutex); - m_pConnections.push_back(newConnection); - - // since we add the object to our internal list keep an extra reference to it - newConnection->AddRef(); - } - - // Well, good luck and have fun :) - return newConnection; -} - -//----------------------------------------------------------------------------- - -// Do not remove (can mess up the uber file builds) -#undef LOG_VERBOSE - -//----------------------------------------------------------------------------- diff --git a/Code/CryEngine/CrySystem/ServiceNetwork.h b/Code/CryEngine/CrySystem/ServiceNetwork.h deleted file mode 100644 index 23c3500082..0000000000 --- a/Code/CryEngine/CrySystem/ServiceNetwork.h +++ /dev/null @@ -1,475 +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 : Service network implementation - - -#pragma once - - -//----------------------------------------------------------------------------- - -#include "IServiceNetwork.h" -#include - -class CServiceNetwork; - -//----------------------------------------------------------------------------- - -// General message buffer -class CServiceNetworkMessage - : public IServiceNetworkMessage -{ -private: - void* m_pData; - uint32 m_id; - uint32 m_size; - int volatile m_refCount; - -public: - CServiceNetworkMessage(const uint32 id, const uint32 size); - virtual ~CServiceNetworkMessage(); - - // IServiceNetworMessage interface - virtual uint32 GetId() const; - virtual uint32 GetSize() const; - virtual void* GetPointer(); - virtual const void* GetPointer() const; - virtual struct IDataReadStream* CreateReader() const; - virtual void AddRef(); - virtual void Release(); -}; - -//----------------------------------------------------------------------------- - -// General network TCP/IP connection -class CServiceNetworkConnection - : public IServiceNetworkConnection -{ -public: - friend class CServiceNetworkListener; - - // maximum size of a single message (0.5MB by default) - static const uint32 kMaximumMessageSize = 5 << 19; - - // initialization message send period (ms) - static const uint64 kInitializationPerior = 1000; - - // keep alive period (ms), by default every 2s - static const uint64 kKeepAlivePeriod = 2000; - - // reconnection retries period (ms) - static const uint64 kReconnectTryPerior = 1000; - - // timeout for assuming server side connection dead (reconnection timeout) - static const uint64 hReconnectTimeOut = 30 * 1000; - - // communication time out (ms) - static const uint64 kTimeout = 5000; - - // Type of endpoint - enum EEndpoint - { - // This is the server side of the connection (on the side of the listening socket) - eEndpoint_Server, - - // This is the client side of the connection (we connected to the listening socket) - eEndpoint_Client, - }; - - // Internal state machine - enum EState - { - // Connection is initializing - eState_Initializing, - - // Connection is valid - eState_Valid, - - // Operation on the socket failed (we may need to reconnect) - eState_Lost, - - // Connection is closed - eState_Closed, - }; - - // Command IDs, do not change the numerical values - enum ECommand - { - // Data block command - eCommand_Data = 1, - - // Keep alive command - eCommand_KeepAlive = 2, - - // Initialize communication channel (sent only once) - eCommand_Initialize = 3, - }; - - #pragma pack(push) - #pragma pack(1) - - struct Header - { - uint8 m_cmd; - uint32 m_size; - - void Swap(); - }; - - struct InitHeader - { - uint8 m_cmd; - uint8 m_pad0; - uint8 m_pad1; - uint8 m_pad2; - uint32 m_tryCount; - uint64 m_guid0; - uint64 m_guid1; - - void Swap(); - }; - - #pragma pack(pop) - -private: - CServiceNetwork* m_pManager; - - // Type of endpoint (client/server) - EEndpoint m_endpointType; - - // Connection state (internal) - EState m_state; - - // Reference count (updated using CryInterlocked* functions) - int volatile m_refCount; - - // Internal socket data - AZSOCKET m_socket; - - // Local address - ServiceNetworkAddress m_localAddress; - - // Remote connection address - ServiceNetworkAddress m_remoteAddress; - - // Internal connection ID (unique) - CryGUID m_connectionID; - - // Internal time counters - uint64 m_lastReconnectTime; - uint64 m_lastKeepAliveSendTime; - uint64 m_lastMessageReceivedTime; - uint64 m_lastInitializationSendTime; - uint32 m_reconnectTryCount; - - // Statistics (updated from threads using CryIntelocked* functions) - volatile uint32 m_statsNumPacketsSend; - volatile uint32 m_statsNumPacketsReceived; - volatile uint32 m_statsNumDataSend; - volatile uint32 m_statsNumDataReceived; - - // Queue of messages to send (thread access possible) - typedef CryMT::CLocklessPointerQueue< CServiceNetworkMessage > TSendQueue; - CServiceNetworkMessage* m_pSendedMessages; - TSendQueue m_pSendQueue; - uint32 m_messageDataSentSoFar; - volatile int m_sendQueueDataSize; - - // Queue of received message - typedef CryMT::CLocklessPointerQueue< CServiceNetworkMessage > TReceiveQueue; - TReceiveQueue m_pReceiveQueue; - uint32 m_receiveQueueDataSize; - uint32 m_messageDataReceivedSoFar; - uint32 m_messageReceiveLength; - - // Message being received "right now" - CServiceNetworkMessage* m_pCurrentReceiveMessage; - uint32 m_messageDummyReadLength; - - // External request to close this connection was issued - bool m_bCloseRequested; - - // Do not accept any new data for sending or receiving - bool m_bDisableCommunication; - -public: - ILINE bool IsInitialized() const - { - return m_state != eState_Initializing; - } - - ILINE bool IsSendingQueueEmpty() const - { - return m_pSendQueue.empty(); - } - - ILINE CServiceNetwork* GetManager() const - { - return m_pManager; - } - -public: - CServiceNetworkConnection( - class CServiceNetwork* manager, - EEndpoint endpointType, - AZSOCKET socket, - const CryGUID& connectionID, - const ServiceNetworkAddress& localAddress, - const ServiceNetworkAddress& remoteAddress); - - virtual ~CServiceNetworkConnection(); - - // IServiceNetworkConnection interface implementation - virtual const ServiceNetworkAddress& GetRemoteAddress() const; - virtual const ServiceNetworkAddress& GetLocalAddress() const; - virtual const CryGUID& GetGUID() const; - virtual bool IsAlive() const; - virtual uint32 GetMessageSendCount() const; - virtual uint32 GetMessageReceivedCount() const; - virtual uint64 GetMessageSendDataSize() const; - virtual uint64 GetMessageReceivedDataSize() const; - virtual bool SendMsg(IServiceNetworkMessage* message); - virtual IServiceNetworkMessage* ReceiveMsg(); - virtual void FlushAndClose(const uint32 timeout); - virtual void FlushAndWait(); - virtual void Close(); - virtual void AddRef(); - virtual void Release(); - - // All remote connections are updated on the client side - // This is called from service network update thread, try not to call by hand :) - void Update(); - -private: - void ProcessSendingQueue(); - void ProcessReceivingQueue(); - - // Keep alive message handling - void ProcessKeepAlive(); - void SendKeepAlive(const uint64 currentNetworkTime); - bool HandleTimeout(const uint64 currentNetworkTime); - - // Handle the reconnection request - bool HandleReconnect(AZSOCKET socket, const uint32 tryCount); - - // General send/receive functions with error handling. - // If socket error occurs the connection will be put in the lost state. - uint32 TrySend(const void* dataBuffer, uint32 dataSize, bool autoHandleErrors); - - // Internal receive function with error handling - uint32 TryReceive(void* dataBuffer, uint32 dataSize, bool autoHandleErrors); - - // Try to reconnect to the remote address - bool TryReconnect(); - - // Try to send the initialization header - bool TryInitialize(); - - // Low-level socket shutdown (hash way) - void Shutdown(); - - // Reset the connection (put in the lost state and reconnect) - void Reset(); -}; - -//----------------------------------------------------------------------------- - -// TCP/IP listener -class CServiceNetworkListener - : public IServiceNetworkListener -{ - typedef CServiceNetworkConnection::InitHeader TInitHeader; - - struct PendingConnection - { - // Connection socket - AZSOCKET m_socket; - - // Initialization of initialization header received so far - uint32 m_dataReceivedSoFar; - - // Initialization header - TInitHeader m_initHeader; - - // Remote address (as returned from accept) - ServiceNetworkAddress m_remoteAddress; - }; - -protected: - // Owner (the manager) - CServiceNetwork* m_pManager; - - // Reference count, updated using CryInterlocked* functions - int volatile m_refCount; - - // Listening socket - AZSOCKET m_socket; - - // Local address (usually has the IP in 127.0.0.1:port form) - ServiceNetworkAddress m_localAddress; - - // Request to close this listener was received - bool m_closeRequestReceived; - - // Pending connections (but not yet initialized) - typedef std::vector< PendingConnection* > TPendingConnectionList; - TPendingConnectionList m_pPendingConnections; - - // All active connections spawned from this listener - typedef std::vector< CServiceNetworkConnection* > TConnectionList; - TConnectionList m_pLocalConnections; - - // Access lock for the class members (thread safe) - CryMutex m_accessLock; - -public: - ILINE CServiceNetwork* GetManager() const - { - return m_pManager; - } - -public: - CServiceNetworkListener(CServiceNetwork* pManager, AZSOCKET socket, const ServiceNetworkAddress& address); - virtual ~CServiceNetworkListener(); - - void Update(); - - // IServiceNetworkListener interface implementation - virtual const ServiceNetworkAddress& GetLocalAddress() const; - virtual uint32 GetConnectionCount() const; - virtual IServiceNetworkConnection* Accept(); - virtual bool IsAlive() const; - virtual void AddRef(); - virtual void Release(); - virtual void Close(); - -private: - void ProcessIncomingConnections(); - void ProcessPendingConnections(); -}; - -//----------------------------------------------------------------------------- - -// TCP/IP manager for service connection channels -class CServiceNetwork - : public IServiceNetwork - , public CryRunnable -{ -#if defined(AZ_RESTRICTED_PLATFORM) -#include AZ_RESTRICTED_FILE(ServiceNetwork_h) -#endif - -protected: - struct ConnectionToClose - { - CServiceNetworkConnection* pConnection; - - // timeout for forded close - uint64 maxWaitTime; - }; - -protected: - // Local listeners - typedef std::vector< CServiceNetworkListener* > TListenerArray; - TListenerArray m_pListeners; - - // Local connections - typedef std::vector< CServiceNetworkConnection* > TConnectionArray; - TConnectionArray m_pConnections; - - // Connections that are waiting for all of their data to be sent before closing - typedef std::vector< ConnectionToClose > TConnectionsToCloseArray; - TConnectionsToCloseArray m_connectionsToClose; - - // We are running on threads, needed to sync the access to arrays - CryMutex m_accessMutex; - - // Current network time (ms) - uint64 m_networkTime; - - // Exit was requested - bool m_bExitRequested; - - // Message verbose level - ICVar* m_pVerboseLevel; - - // Thread - typedef CryThread< CServiceNetwork > TServiceNetworkThread; - TServiceNetworkThread* m_pThread; - - // Buffer ID allocator (unique, incremented atomically using CryInterlockedIncrement) - volatile int m_bufferID; - - // Random number generator for GUID creation - CRndGen m_guidGenerator; - - // Send/Receive queue size limit - ICVar* m_pReceiveDataQueueLimit; - ICVar* m_pSendDataQueueLimit; - -public: - ILINE const uint64 GetNetworkTime() const - { - return m_networkTime; - } - - ILINE const CServiceNetwork* GetManager() const - { - return this; - } - - ILINE const uint32 GetReceivedDataQueueLimit() const - { - return m_pReceiveDataQueueLimit->GetIVal(); - } - - ILINE const uint32 GetSendDataQueueLimit() const - { - return m_pSendDataQueueLimit->GetIVal(); - } - -public: - CServiceNetwork(); - virtual ~CServiceNetwork(); - - // IServiceNetwork interface implementation - virtual void SetVerbosityLevel(const uint32 level); - virtual IServiceNetworkMessage* AllocMessageBuffer(const uint32 size); - virtual struct IDataWriteStream* CreateMessageWriter(); - virtual struct IDataReadStream* CreateMessageReader(const void* pData, const uint32 dataSize); - virtual ServiceNetworkAddress GetHostAddress(const string& addressString, uint16 optionalPort = 0) const; - virtual IServiceNetworkListener* CreateListener(uint16 localPort); - virtual IServiceNetworkConnection* Connect(const ServiceNetworkAddress& remoteAddress); - - // CryRunnable - virtual void Run(); - virtual void Cancel(); - - // Register connection in the connection list (thread safe) - void RegisterConnection(CServiceNetworkConnection& con); - - // Register connection for closing one all of the outgoing messages are sent - void RegisterForDeferredClose(CServiceNetworkConnection& con, const uint32 timeout); - - // Debug print -#ifdef RELEASE - void Log([[maybe_unused]] const char* txt, ...) const {}; - bool CheckVerbose([[maybe_unused]] const uint32 level) const { return false; } -#else - void Log(const char* txt, ...) const; - bool CheckVerbose(const uint32 level) const; -#endif -}; - -//----------------------------------------------------------------------------- diff --git a/Code/CryEngine/CrySystem/System.cpp b/Code/CryEngine/CrySystem/System.cpp index 31eb286a17..8a8cf14d91 100644 --- a/Code/CryEngine/CrySystem/System.cpp +++ b/Code/CryEngine/CrySystem/System.cpp @@ -121,7 +121,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include #include -#include #include #include #include @@ -145,7 +144,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include "LocalizedStringManager.h" #include "XML/XmlUtils.h" -#include "Serialization/ArchiveHost.h" #include "SystemEventDispatcher.h" #include "ServerThrottle.h" #include "ResourceManager.h" @@ -445,7 +443,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_pXMLUtils = new CXmlUtils(this); - m_pArchiveHost = Serialization::CreateArchiveHost(); m_pMemoryManager = CryGetIMemoryManager(); m_pThreadTaskManager = new CThreadTaskManager; m_pResourceManager = new CResourceManager; @@ -499,7 +496,6 @@ CSystem::~CSystem() CRY_ASSERT(m_windowMessageHandlers.empty() && "There exists a dangling window message handler somewhere"); SAFE_DELETE(m_pXMLUtils); - SAFE_DELETE(m_pArchiveHost); SAFE_DELETE(m_pThreadTaskManager); SAFE_DELETE(m_pResourceManager); SAFE_DELETE(m_pSystemEventDispatcher); @@ -671,7 +667,6 @@ void CSystem::ShutDown() SAFE_DELETE(m_env.pResourceCompilerHelper); SAFE_RELEASE(m_env.pMovieSystem); - SAFE_DELETE(m_env.pServiceNetwork); SAFE_RELEASE(m_env.pLyShine); SAFE_RELEASE(m_env.pCryFont); if (m_env.pConsole) diff --git a/Code/CryEngine/CrySystem/System.h b/Code/CryEngine/CrySystem/System.h index 5f87fd1ad1..c4f3bfabd6 100644 --- a/Code/CryEngine/CrySystem/System.h +++ b/Code/CryEngine/CrySystem/System.h @@ -42,7 +42,6 @@ namespace AzFramework struct IConsoleCmdArgs; class CServerThrottle; -struct ICryFactoryRegistryImpl; struct IZLibCompressor; class CWatchdogThread; class CThreadManager; @@ -486,8 +485,6 @@ public: virtual IXmlUtils* GetXmlUtils(); ////////////////////////////////////////////////////////////////////////// - virtual Serialization::IArchiveHost* GetArchiveHost() const { return m_pArchiveHost; } - void SetViewCamera(CCamera& Camera){ m_ViewCamera = Camera; } CCamera& GetViewCamera() { return m_ViewCamera; } @@ -584,15 +581,11 @@ public: // static as memReplay needs it before CSystem has been setup - expose a ISystem interface to this function if you need it outside CrySystem static void debug_GetCallStackRaw(void** callstack, uint32& callstackLength); - virtual ICryFactoryRegistry* GetCryFactoryRegistry() const; - public: #if !defined(RELEASE) void SetVersionInfo(const char* const szVersion); #endif - virtual bool InitializeEngineModule(const char* dllName, const char* moduleClassName, const SSystemInitParams& initParams) override; - virtual bool UnloadEngineModule(const char* dllName, const char* moduleClassName); virtual const IImageHandler* GetImageHandler() const override { return m_imageHandler.get(); } void ShutdownModuleLibraries(); @@ -809,8 +802,6 @@ private: // ------------------------------------------------------ // XML Utils interface. class CXmlUtils* m_pXMLUtils; - Serialization::IArchiveHost* m_pArchiveHost; - int m_iApplicationInstance; //! to hold the values stored in system.cfg diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index 83ef4fcd2b..8bf2fb8930 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -46,8 +46,6 @@ #include #include -#include -#include #include // for AZ_MAX_PATH_LEN #include #include @@ -113,16 +111,12 @@ #include "ResourceManager.h" #include "MTSafeAllocator.h" #include "NotificationNetwork.h" -#include "ExtensionSystem/CryFactoryRegistryImpl.h" -#include "ExtensionSystem/TestCases/TestExtensions.h" #include "ProfileLogSystem.h" #include "SoftCode/SoftCodeMgr.h" #include "ZLibCompressor.h" #include "ZLibDecompressor.h" #include "ZStdDecompressor.h" #include "LZ4Decompressor.h" -#include "ServiceNetwork.h" -#include "RemoteCommand.h" #include "LevelSystem/LevelSystem.h" #include "LevelSystem/SpawnableLevelSystem.h" #include "ViewSystem/ViewSystem.h" @@ -856,148 +850,6 @@ bool CSystem::UnloadDLL(const char* dllName) return isSuccess; } -////////////////////////////////////////////////////////////////////////// -bool CSystem::InitializeEngineModule(const char* dllName, const char* moduleClassName, const SSystemInitParams& initParams) -{ - bool bResult = false; - - stack_string msg; - msg = "Initializing "; - AZStd::string dll = dllName; - - // Strip off Cry if the dllname is Cry - if (dll.find("Cry") == 0) - { - msg += dll.substr(3).c_str(); - } - else - { - msg += dllName; - } - msg += "..."; - - if (m_pUserCallback) - { - m_pUserCallback->OnInitProgress(msg.c_str()); - } - AZ_TracePrintf(moduleClassName, "%s", msg.c_str()); - - IMemoryManager::SProcessMemInfo memStart, memEnd; - if (GetIMemoryManager()) - { - GetIMemoryManager()->GetProcessMemInfo(memStart); - } - else - { - ZeroStruct(memStart); - } - - stack_string dllfile = ""; - - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_16 -#include AZ_RESTRICTED_FILE(SystemInit_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - - dllfile.append(dllName); - -#if defined(LINUX) - dllfile = "lib" + PathUtil::ReplaceExtension(dllfile, "so"); -#ifndef LINUX - dllfile.MakeLower(); -#endif -#elif defined(AZ_PLATFORM_MAC) - dllfile = "lib" + PathUtil::ReplaceExtension(dllfile, "dylib"); -#elif defined(AZ_PLATFORM_IOS) - PathUtil::RemoveExtension(dllfile); -#else - dllfile = PathUtil::ReplaceExtension(dllfile, "dll"); -#endif - -#endif - -#if !defined(AZ_MONOLITHIC_BUILD) - - m_moduleDLLHandles.insert(std::make_pair(dllfile.c_str(), LoadDLL(dllfile.c_str()))); - if (!m_moduleDLLHandles[dllfile.c_str()]) - { - return bResult; - } - -#endif // #if !defined(AZ_MONOLITHIC_BUILD) - - AZStd::shared_ptr pModule; - if (CryCreateClassInstance(moduleClassName, pModule)) - { - bResult = pModule->Initialize(m_env, initParams); - - // After initializing the module, give it a chance to register any AZ console vars - // declared within the module. - pModule->RegisterConsoleVars(); - } - - if (GetIMemoryManager()) - { - GetIMemoryManager()->GetProcessMemInfo(memEnd); - -#if defined(AZ_ENABLE_TRACING) - uint64 memUsed = memEnd.WorkingSetSize - memStart.WorkingSetSize; -#endif - AZ_TracePrintf(AZ_TRACE_SYSTEM_WINDOW, "Initializing %s %s, MemUsage=%uKb", dllName, pModule ? "done" : "failed", uint32(memUsed / 1024)); - } - - return bResult; -} - -////////////////////////////////////////////////////////////////////////// -bool CSystem::UnloadEngineModule(const char* dllName, const char* moduleClassName) -{ - bool isSuccess = false; - - // Remove the factory. - ICryFactoryRegistryImpl* const pReg = static_cast(GetCryFactoryRegistry()); - - if (pReg != nullptr) - { - ICryFactory* pICryFactory = pReg->GetFactory(moduleClassName); - - if (pICryFactory != nullptr) - { - pReg->UnregisterFactory(pICryFactory); - } - } - - stack_string msg; - msg = "Unloading "; - msg += dllName; - msg += "..."; - - AZ_TracePrintf(AZ_TRACE_SYSTEM_WINDOW, "%s", msg.c_str()); - - stack_string dllfile = dllName; - -#if defined(LINUX) - dllfile = "lib" + PathUtil::ReplaceExtension(dllfile, "so"); -#ifndef LINUX - dllfile.MakeLower(); -#endif -#elif defined(APPLE) - dllfile = "lib" + PathUtil::ReplaceExtension(dllfile, "dylib"); -#else - dllfile = PathUtil::ReplaceExtension(dllfile, "dll"); -#endif - -#if !defined(AZ_MONOLITHIC_BUILD) - isSuccess = UnloadDLL(dllfile.c_str()); -#endif // #if !defined(AZ_MONOLITHIC_BUILD) - - return isSuccess; -} - ////////////////////////////////////////////////////////////////////////// void CSystem::ShutdownModuleLibraries() { @@ -1872,12 +1724,6 @@ bool CSystem::Init(const SSystemInitParams& startupParams) AZ_Assert(CryMemory::IsHeapValid(), "Memory heap must be valid before continuing SystemInit."); -#ifdef EXTENSION_SYSTEM_INCLUDE_TESTCASES - TestExtensions(&CCryFactoryRegistryImpl::Access()); -#endif - - //_controlfp(0, _EM_INVALID|_EM_ZERODIVIDE | _PC_64 ); - #if defined(WIN32) || defined(WIN64) // check OS version - we only want to run on XP or higher - talk to Martin Mittring if you want to change this { @@ -2412,8 +2258,6 @@ AZ_POP_DISABLE_WARNING } InlineInitializationProcessing("CSystem::Init InitShine"); - - ////////////////////////////////////////////////////////////////////////// // CONSOLE ////////////////////////////////////////////////////////////////////////// if (!InitConsole()) @@ -2421,22 +2265,6 @@ AZ_POP_DISABLE_WARNING return false; } - ////////////////////////////////////////////////////////////////////////// - // SERVICE NETWORK - ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bSkipNetwork && !startupParams.bMinimal) - { - m_env.pServiceNetwork = new CServiceNetwork(); - } - - ////////////////////////////////////////////////////////////////////////// - // REMOTE COMMAND SYTSTEM - ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bSkipNetwork && !startupParams.bMinimal) - { - m_env.pRemoteCommandManager = new CRemoteCommandManager(); - } - if (m_pUserCallback) { m_pUserCallback->OnInitProgress("Initializing additional systems..."); diff --git a/Code/CryEngine/CrySystem/XConsole.cpp b/Code/CryEngine/CrySystem/XConsole.cpp index ee5b500b0b..3b30a7eeed 100644 --- a/Code/CryEngine/CrySystem/XConsole.cpp +++ b/Code/CryEngine/CrySystem/XConsole.cpp @@ -28,7 +28,6 @@ #include #include #include -#include #include #include "ConsoleHelpGen.h" // CConsoleHelpGen diff --git a/Code/CryEngine/CrySystem/crysystem_files.cmake b/Code/CryEngine/CrySystem/crysystem_files.cmake index 0b62483e43..5dc8a68f8b 100644 --- a/Code/CryEngine/CrySystem/crysystem_files.cmake +++ b/Code/CryEngine/CrySystem/crysystem_files.cmake @@ -55,13 +55,7 @@ set(FILES SystemScheduler.h UnixConsole.h SystemInit.h - Serialization/MemoryReader.h XML/ReadWriteXMLSink.h - Serialization/ArchiveHost.h - Serialization/MemoryWriter.h - Serialization/JSONIArchive.h - Serialization/JSONOArchive.h - Serialization/BinArchive.h AZCrySystemInitLogSink.h AZCoreLogSink.h CmdLine.h @@ -127,10 +121,6 @@ set(FILES ThreadConfigManager.h ThreadConfigManager.cpp SystemThreading.cpp - ExtensionSystem/CryFactoryRegistryImpl.cpp - ExtensionSystem/CryFactoryRegistryImpl.h - ExtensionSystem/TestCases/TestExtensions.cpp - ExtensionSystem/TestCases/TestExtensions.h ZLibCompressor.cpp ZLibCompressor.h SoftCode/SoftCodeMgr.cpp @@ -141,14 +131,6 @@ set(FILES RemoteConsole/RemoteConsole.h RemoteConsole/RemoteConsole_impl.inl RemoteConsole/RemoteConsole_none.inl - ServiceNetwork.cpp - ServiceNetwork.h - RemoteCommand.cpp - RemoteCommand.h - RemoteCommandHelpers.cpp - RemoteCommandHelpers.h - RemoteCommandServer.cpp - RemoteCommandClient.cpp ZLibDecompressor.h ZLibDecompressor.cpp LZ4Decompressor.h @@ -165,17 +147,6 @@ set(FILES ViewSystem/ViewSystem.h ZStdDecompressor.h ZStdDecompressor.cpp - Serialization/ArchiveHost.cpp - Serialization/BinArchive.cpp - Serialization/JSONIArchive.cpp - Serialization/JSONOArchive.cpp - Serialization/MemoryReader.cpp - Serialization/MemoryWriter.cpp - Serialization/Token.h - Serialization/XmlIArchive.cpp - Serialization/XmlIArchive.h - Serialization/XmlOArchive.cpp - Serialization/XmlOArchive.h StreamEngine/StreamAsyncFileRequest.cpp StreamEngine/StreamAsyncFileRequest_Jobs.cpp StreamEngine/StreamEngine.cpp diff --git a/Code/CryEngine/CrySystem/crysystem_test_files.cmake b/Code/CryEngine/CrySystem/crysystem_test_files.cmake index fc236afcf3..a57ba57f77 100644 --- a/Code/CryEngine/CrySystem/crysystem_test_files.cmake +++ b/Code/CryEngine/CrySystem/crysystem_test_files.cmake @@ -11,7 +11,6 @@ set(FILES Components/MathConversionTests.cpp - Serialization/Test_ArchiveHost.cpp Tests/Test_CLog.cpp Tests/Test_CommandRegistration.cpp Tests/Test_CryPrimitives.cpp diff --git a/Code/Sandbox/Editor/Controls/CurveEditorCtrl.cpp b/Code/Sandbox/Editor/Controls/CurveEditorCtrl.cpp deleted file mode 100644 index f66943b07d..0000000000 --- a/Code/Sandbox/Editor/Controls/CurveEditorCtrl.cpp +++ /dev/null @@ -1,821 +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 "CurveEditorCtrl.h" - -// Qt -#include -#include - -namespace CurveEditor -{ - const int kHandleSize = 6; - const int kHandleSizeHalf = kHandleSize / 2; - const int kDefaultPadding = 10; - const int kInfoFontSize = 7; - const int kGrid = 4; - const QColor kColor_SelectCross(132, 132, 132); - const QColor kColor_DisabledCross(90, 90, 90); - const QColor kColor_MiddleLines(80, 80, 80); - const QColor kColor_Background(41, 41, 41); - const QColor kColor_Disabled(60, 60, 60); - const QColor kColor_PaddingBorder(128, 128, 128); - const QColor kColor_Text(128, 128, 128); - const QColor kColor_TextCrtPos(187, 187, 187); - const QColor kColor_Curve(255, 0, 0); - const QColor kColor_SelHandle(200, 200, 200); - const QColor kColor_NormalHandle(30, 30, 30); - const QColor kColor_HandleLight(60, 60, 60); - const QColor kColor_HandleShadow(0, 0, 0); - const QColor kColor_MarkLines(0, 255, 0); -} - - -CCurveEditorCtrl::CCurveEditorCtrl(QWidget* parent) - : QWidget(parent) -{ - m_domainMinX = 0.0f; - m_domainMinY = 0.0f; - m_domainMaxX = 1.0f; - m_domainMaxY = 1.0f; - m_bMouseDown = m_bDragging = false; - m_bAllowMouse = true; - m_padding = CurveEditor::kDefaultPadding; - m_flags = eFlag_ShowVerticalRuler - | eFlag_ShowHorizontalRuler - | eFlag_ShowVerticalRulerText - | eFlag_ShowHorizontalRulerText - | eFlag_ShowPaddingBorder - | eFlag_ShowMovingPointAxis - | eFlag_ShowPointHandles; - m_gridSplits.set(CurveEditor::kGrid, CurveEditor::kGrid); - m_fntInfo.setFamily("Arial"); - m_fntInfo.setPointSize(CurveEditor::kInfoFontSize); - m_bHovered = false; - m_selCrossPen = QPen(CurveEditor::kColor_SelectCross); - - GenerateDefaultCurve(); -} - -CCurveEditorCtrl::~CCurveEditorCtrl() -{ -} - -void CCurveEditorCtrl::SetFlags(UINT aFlags) -{ - m_flags = aFlags; -} - -UINT CCurveEditorCtrl::GetFlags() const -{ - return m_flags; -} - -bool CCurveEditorCtrl::SetDomainBounds(float aMinX, float aMinY, float aMaxX, float aMaxY) -{ - assert(aMinX < aMaxX); - assert(aMinY < aMaxY); - - if (aMinX >= aMaxX) - { - return false; - } - - if (aMinY >= aMaxY) - { - return false; - } - - m_domainMinX = aMinX; - m_domainMinY = aMinY; - m_domainMaxX = aMaxX; - m_domainMaxY = aMaxY; - - return true; -} - -void CCurveEditorCtrl::GetDomainBounds(float& rMinX, float& rMinY, float& rMaxX, float& rMaxY) const -{ - rMinX = m_domainMinX; - rMinY = m_domainMinY; - rMaxX = m_domainMaxX; - rMaxY = m_domainMaxY; -} - -void CCurveEditorCtrl::SetGrid(UINT aHorizontalSplits, UINT aVerticalSplits, const QStringList& labelsX, const QStringList& labelsY) -{ - assert(aHorizontalSplits); - assert(aVerticalSplits); - - if (!aHorizontalSplits) - { - // defaults - aHorizontalSplits = 2; - } - - if (!aVerticalSplits) - { - // defaults - aVerticalSplits = 2; - } - - m_gridSplits.x = aHorizontalSplits; - m_gridSplits.y = aVerticalSplits; - - if (!labelsX.isEmpty()) - { - m_labelsX = labelsX; - } - - if (!labelsY.isEmpty()) - { - m_labelsY = labelsY; - } -} - -QPoint CCurveEditorCtrl::ProjectPoint(float x, float y) -{ - QPoint pt; - - pt.setX(m_padding + (width() - m_padding * 2) * (x - m_domainMinX) / (m_domainMaxX - m_domainMinX)); - pt.setY(m_padding + (height() - m_padding * 2) * (1.0f - (y - m_domainMinY) / (m_domainMaxY - m_domainMinY))); - - return pt; -} - -Vec2 CCurveEditorCtrl::UnprojectPoint(const QPoint& pt) -{ - Vec2 vec; - int y = height() - pt.y(); - float dx = (width() - m_padding * 2); - float dy = (height() - m_padding * 2); - const float kEpsilon = 0.00000001f; - - if (fabs(dx) <= kEpsilon) - { - dx = 1.0f; - } - - if (fabs(dy) <= kEpsilon) - { - dy = 1.0f; - } - - vec.x = m_domainMinX + (float)(pt.x() - m_padding) / dx * (m_domainMaxX - m_domainMinX); - vec.y = m_domainMinY + (float)(y - m_padding) / dy * (m_domainMaxY - m_domainMinY); - - return vec; -} - -void CCurveEditorCtrl::SetControlPointCount(UINT aCount) -{ - m_points.resize(aCount); - m_projectedPoints.clear(); -} - -UINT CCurveEditorCtrl::GetControlPointCount() const -{ - return m_points.size(); -} - -void CCurveEditorCtrl::AddControlPoint(const Vec2& rPosition) -{ - m_points.push_back(CurvePoint(rPosition.x, rPosition.y)); -} - -void CCurveEditorCtrl::ClearControlPoints() -{ - m_points.clear(); -} - -void CCurveEditorCtrl::SetControlPoint(UINT aIndex, const Vec2& rPosition) -{ - assert(aIndex < m_points.size()); - - if (aIndex >= m_points.size()) - { - return; - } - - m_points[aIndex].pos = rPosition; -} - -void CCurveEditorCtrl::SetControlPointTangents(UINT aIndex, const Vec2& rLeft, const Vec2& rRight) -{ - assert(aIndex < m_points.size()); - - if (aIndex >= m_points.size()) - { - return; - } - - m_points[aIndex].tanA = rLeft; - m_points[aIndex].tanB = rRight; -} - -void CCurveEditorCtrl::GetControlPoint(UINT aIndex, Vec2& rOutPosition) const -{ - assert(aIndex < m_points.size()); - - if (aIndex >= m_points.size()) - { - return; - } - - rOutPosition = m_points[aIndex].pos; -} - -void CCurveEditorCtrl::GetControlPointTangents(UINT aIndex, Vec2& rOutLeft, Vec2& rOutRight) const -{ - assert(aIndex < m_points.size()); - - if (aIndex >= m_points.size()) - { - return; - } - - rOutLeft = m_points[aIndex].tanA; - rOutRight = m_points[aIndex].tanB; -} - -void CCurveEditorCtrl::paintEvent(QPaintEvent* event) -{ - QWidget::paintEvent(event); - - QPainter dc(this); - - QRect rc = geometry(); - QString str; - QRect textSize; - - dc.setFont(m_fntInfo); - QFontMetrics fntMetrics(m_fntInfo); - - if (m_flags & eFlag_Disabled) - { - // If disabled, just draw a blank square. - dc.fillRect(rc, CurveEditor::kColor_Disabled); - - dc.setPen(CurveEditor::kColor_DisabledCross); - dc.drawLine(0, 0, rc.width(), rc.height()); - - dc.drawLine(rc.width(), 0, 0, rc.height()); - return; - } - - dc.fillRect(rc, CurveEditor::kColor_Background); - - dc.setPen(CurveEditor::kColor_MiddleLines); - - if (m_flags & eFlag_ShowVerticalRuler) - { - float y = m_domainMinY; - float grid = (m_domainMaxY - m_domainMinY) / m_gridSplits.y; - QPoint p; - - for (int i = 0; i <= m_gridSplits.y; ++i) - { - p = ProjectPoint(0, y); - dc.drawLine(m_padding, p.y(), rc.width() - m_padding, p.y()); - - if (m_flags & eFlag_ShowVerticalRulerText) - { - if (m_labelsY.empty()) - { - str.asprintf("%0.2f", y); - } - else - { - str = m_labelsY[i]; - } - textSize = fntMetrics.tightBoundingRect(str); - dc.drawText(2, p.y(), str); - } - - y += grid; - } - } - - if (m_flags & eFlag_ShowHorizontalRuler) - { - float x = m_domainMinX; - float grid = (m_domainMaxX - m_domainMinX) / m_gridSplits.x; - QPoint p; - - for (int i = 0; i <= m_gridSplits.x; ++i) - { - p = ProjectPoint(x, 0); - dc.drawLine(p.x(), m_padding, p.x(), rc.height() - m_padding); - - if (m_flags & eFlag_ShowHorizontalRulerText) - { - if (m_labelsX.empty()) - { - str.asprintf("%0.2f", x); - } - else - { - str = m_labelsX[i]; - } - textSize = fntMetrics.tightBoundingRect(str); - - p.setX(p.x() + 2); - - if (p.x() + textSize.width() > width()) - { - p.setX(width() - textSize.width()); - } - - dc.drawText(p.x(), height() - m_padding + textSize.height() + 2, str); - } - - x += grid; - } - } - - dc.setPen(CurveEditor::kColor_MarkLines); - - if (m_flags & eFlag_ShowVerticalRuler) - { - QPoint p; - for (size_t i = 0; i < m_marksY.size(); ++i) - { - float v = m_marksY[i]; - if (v < m_domainMinY || v > m_domainMaxY) - { - continue; - } - p = ProjectPoint(0, v); - dc.drawLine(m_padding, p.y(), width() - m_padding, p.y()); - } - } - - if (m_flags & eFlag_ShowHorizontalRuler) - { - QPoint p; - for (size_t i = 0; i < m_marksX.size(); ++i) - { - float v = m_marksX[i]; - if (v < m_domainMinX || v > m_domainMaxX) - { - continue; - } - p = ProjectPoint(v, 0); - dc.drawLine(p.x(), m_padding, p.x(), height() - m_padding); - } - } - - if (m_flags & eFlag_ShowPaddingBorder) - { - dc.setPen(CurveEditor::kColor_PaddingBorder); - dc.drawRect(m_padding, m_padding, width() - m_padding * 2, height() - m_padding * 2); - } - - if (m_bDragging - && !m_selectedIndices.empty() - && (m_flags & eFlag_ShowMovingPointAxis)) - { - const Vec2& crtPos = m_points[m_selectedIndices[0]].pos; - - dc.setBrush(CurveEditor::kColor_TextCrtPos); - str.asprintf("(%0.2f,%0.2f)", crtPos.x, crtPos.y); - textSize = fntMetrics.tightBoundingRect(str); - const int kOffsetFromPointer = 5; - QPoint txtPos(m_lastMousePoint.x() + kOffsetFromPointer, m_lastMousePoint.y() + kOffsetFromPointer); - - if (txtPos.x() + textSize.width() > width()) - { - txtPos.setX(width() - textSize.width()); - } - - if (txtPos.y() + textSize.height() > height()) - { - txtPos.setY(height() - textSize.height()); - } - - dc.drawText(txtPos, str); - } - - ComputeTangents(); - UpdateProjectedPoints(); - - // for curve debug, tangents poly, don't delete - // dc.setPen(Qt::black); - // dc.drawPolyline(m_projectedPoints.data(), m_projectedPoints.size()); - - dc.setPen(CurveEditor::kColor_Curve); - - // curve - QPainterPath bezierPath; - bezierPath.moveTo(m_projectedPoints[0]); - for (int i = 1; i < m_projectedPoints.size(); i += 3) - { - bezierPath.cubicTo(m_projectedPoints[i], m_projectedPoints[i + 1], m_projectedPoints[i + 2]); - } - dc.drawPath(bezierPath); - - // curve control point handles - if (m_flags & eFlag_ShowPointHandles) - { - for (size_t i = 0; i < m_points.size(); ++i) - { - QPoint ptProj = ProjectPoint(m_points[i].pos.x, m_points[i].pos.y); - QRect rcHandle(0, 0, CurveEditor::kHandleSize, CurveEditor::kHandleSize); - rcHandle.moveCenter(ptProj); - - std::vector::iterator iter = - std::find(m_selectedIndices.begin(), m_selectedIndices.end(), i); - - bool bSelected = (iter != m_selectedIndices.end()); - - if (bSelected && m_bDragging) - { - dc.setPen(m_selCrossPen); - dc.drawLine(0, ptProj.y(), width(), ptProj.y()); - dc.drawLine(ptProj.x(), 0, ptProj.x(), height()); - } - - dc.fillRect(rcHandle, bSelected - ? CurveEditor::kColor_SelHandle - : CurveEditor::kColor_NormalHandle); - - dc.setPen(CurveEditor::kColor_HandleLight); - dc.drawLine(ptProj.x() - CurveEditor::kHandleSizeHalf, ptProj.y() - CurveEditor::kHandleSizeHalf, - ptProj.x() - CurveEditor::kHandleSizeHalf, ptProj.y() + CurveEditor::kHandleSizeHalf); - dc.drawLine(ptProj.x() - CurveEditor::kHandleSizeHalf, ptProj.y() + CurveEditor::kHandleSizeHalf, - ptProj.x() + CurveEditor::kHandleSizeHalf, ptProj.y() + CurveEditor::kHandleSizeHalf); - dc.setPen(CurveEditor::kColor_HandleShadow); - dc.drawLine(ptProj.x() + CurveEditor::kHandleSizeHalf, ptProj.y() + CurveEditor::kHandleSizeHalf, - ptProj.x() + CurveEditor::kHandleSizeHalf, ptProj.y() - CurveEditor::kHandleSizeHalf); - dc.drawLine(ptProj.x() + CurveEditor::kHandleSizeHalf, ptProj.y() - CurveEditor::kHandleSizeHalf, - ptProj.x() - CurveEditor::kHandleSizeHalf, ptProj.y() - CurveEditor::kHandleSizeHalf); - } - } -} - -void CCurveEditorCtrl::ComputeTangents() -{ - for (size_t i = 0; i < m_points.size(); ++i) - { - m_points[i].tanA = m_points[i].pos; - m_points[i].tanB = m_points[i].pos; - } - - int maxIndex = m_points.size() - 1; - - for (size_t i = 0; i < m_points.size(); ++i) - { - if (i > maxIndex) - { - break; - } - - Vec2& p2 = m_points[i].pos; - Vec2& back = m_points[i].tanA; - Vec2& forw = m_points[i].tanB; - const float kEpsilon = 0.000001f; - - // first point - if (i == 0) - { - back = p2; - - if (maxIndex == 1) - { - Vec2& p3 = m_points[i + 1].pos; - forw = p2 + (p3 - p2) / 3.0f; - } - else if (maxIndex > 0) - { - Vec2& p3 = m_points[i + 1].pos; - Vec2& pb3 = m_points[i + 1].tanA; - - float lenOsn = (pb3 - p2).GetLength(); - float lenb = (p3 - p2).GetLength(); - - if (lenOsn > kEpsilon && lenb > kEpsilon) - { - forw = p2 + (pb3 - p2) / (lenOsn / lenb * 3.0f); - } - else - { - forw = p2; - } - } - } - - if (i == maxIndex) - { - forw = p2; - - if (i > 0) - { - Vec2& p1 = m_points[i - 1].pos; - Vec2& pf1 = m_points[i - 1].tanB; - - float lenOsn = (pf1 - p2).GetLength(); - float lenf = (p1 - p2).GetLength(); - - if (lenOsn > kEpsilon && lenf > kEpsilon) - { - back = p2 + (pf1 - p2) / (lenOsn / lenf * 3.0f); - } - else - { - back = p2; - } - } - } - else if (i >= 1 && i <= maxIndex - 1) - { - Vec2& p1 = m_points[i - 1].pos; - Vec2& p3 = m_points[i + 1].pos; - - float lenOsn = (p3 - p1).GetLength(); - float lenb = (p1 - p2).GetLength(); - float lenf = (p3 - p2).GetLength(); - - if (lenOsn > kEpsilon - && lenf > kEpsilon - && lenb > kEpsilon) - { - back = p2 + (p1 - p3) * (lenb / lenOsn / 3.0f); - forw = p2 + (p3 - p1) * (lenf / lenOsn / 3.0f); - } - } - - ClampToDomain(back); - ClampToDomain(forw); - } - - // fix tangents in relation of one to another - for (size_t i = 0; i < m_points.size(); ++i) - { - Vec2& p = m_points[i].pos; - Vec2& tanA = m_points[i].tanA; - Vec2& tanB = m_points[i].tanB; - - if (i < m_points.size() - 1) - { - if (tanB.x > m_points[i + 1].tanA.x) - { - tanB.x = (m_points[i + 1].pos.x + p.x) * 0.5f; - } - } - if (i > 0) - { - if (tanA.x < m_points[i - 1].tanB.x) - { - tanA.x = (m_points[i - 1].pos.x + p.x) * 0.5f; - } - } - } -} - -void CCurveEditorCtrl::UpdateProjectedPoints() -{ - m_projectedPoints.resize(m_points.size() * 3 - 2); - - int numPts = 0; - - for (size_t i = 0; i < m_points.size(); ++i) - { - if (i == 0) - { - m_projectedPoints[numPts++] = ProjectPoint(m_points[i].pos.x, m_points[i].pos.y); - m_projectedPoints[numPts++] = ProjectPoint(m_points[i].tanB.x, m_points[i].tanB.y); - } - else if (i == m_points.size() - 1) - { - m_projectedPoints[numPts++] = ProjectPoint(m_points[i].tanA.x, m_points[i].tanA.y); - m_projectedPoints[numPts++] = ProjectPoint(m_points[i].pos.x, m_points[i].pos.y); - } - else - { - m_projectedPoints[numPts++] = ProjectPoint(m_points[i].tanA.x, m_points[i].tanA.y); - m_projectedPoints[numPts++] = ProjectPoint(m_points[i].pos.x, m_points[i].pos.y); - m_projectedPoints[numPts++] = ProjectPoint(m_points[i].tanB.x, m_points[i].tanB.y); - } - } -} - -void CCurveEditorCtrl::ClampToDomain(Vec2& rVec) -{ - if (rVec.x < m_domainMinX) - { - rVec.x = m_domainMinX; - } - else if (rVec.x > m_domainMaxX) - { - rVec.x = m_domainMaxX; - } - - if (rVec.y < m_domainMinY) - { - rVec.y = m_domainMinY; - } - else if (rVec.y > m_domainMaxY) - { - rVec.y = m_domainMaxY; - } -} - -void CCurveEditorCtrl::GenerateDefaultCurve() -{ - m_points.clear(); - m_domainMinX = 0.0f; - m_domainMinY = 0.0f; - m_domainMaxX = 1.0f; - m_domainMaxY = 1.0f; - m_points.push_back(CurvePoint(0.00f, 0.00f)); - m_points.push_back(CurvePoint(0.25f, 0.25f)); - m_points.push_back(CurvePoint(0.50f, 0.50f)); - m_points.push_back(CurvePoint(0.75f, 0.75f)); - m_points.push_back(CurvePoint(1.00f, 1.00f)); -} - -void CCurveEditorCtrl::mousePressEvent(QMouseEvent* event) -{ - QWidget::mousePressEvent(event); - if (event->button() != Qt::LeftButton) - { - return; - } - - const QPoint point = event->pos(); - if (m_bAllowMouse) - { - bool bSimpleSelect = !(event->modifiers() & Qt::ShiftModifier) && !(event->modifiers() & Qt::ControlModifier); - - if (bSimpleSelect) - { - m_selectedIndices.clear(); - } - - for (size_t i = 0; i < m_points.size(); ++i) - { - QPoint ptProj = ProjectPoint(m_points[i].pos.x, m_points[i].pos.y); - - QRect rcHandle(0, 0, CurveEditor::kHandleSize, CurveEditor::kHandleSize); - rcHandle.moveCenter(ptProj); - - if (rcHandle.contains(point)) - { - if (bSimpleSelect) - { - m_selectedIndices.push_back(i); - break; - } - - if (event->modifiers() & Qt::ShiftModifier) - { - m_selectedIndices.push_back(i); - } - else if (event->modifiers() & Qt::ControlModifier) - { - std::vector::iterator iter = - std::find(m_selectedIndices.begin(), m_selectedIndices.end(), i); - - if (iter == m_selectedIndices.end()) - { - m_selectedIndices.push_back(i); - } - else - { - m_selectedIndices.erase(iter); - } - } - } - } - - m_bMouseDown = true; - m_lastMousePoint = point; - } - - grabMouse(); - update(); -} - -void CCurveEditorCtrl::mouseReleaseEvent(QMouseEvent* event) -{ - QWidget::mouseReleaseEvent(event); - if (event->button() != Qt::LeftButton) - { - return; - } - - m_bMouseDown = false; - m_bDragging = false; - m_selectedIndices.clear(); - - releaseMouse(); - update(); -} - -void CCurveEditorCtrl::mouseMoveEvent(QMouseEvent* event) -{ - if (m_bMouseDown && !m_bDragging) - { - m_bDragging = true; - } - - m_bHovered = true; - if (m_flags & eFlag_ShowCursorAlways) - { - m_bHovered = true; - } - else - { - m_bHovered = false; - - for (size_t i = 0; i < m_points.size(); ++i) - { - QPoint ptProj = ProjectPoint(m_points[i].pos.x, m_points[i].pos.y); - QRect rcHandle(0, 0, CurveEditor::kHandleSize, CurveEditor::kHandleSize); - rcHandle.moveCenter(ptProj); - - if (rcHandle.contains(event->pos())) - { - m_bHovered = true; - break; - } - } - } - - if (m_bDragging) - { - Vec2 v1 = UnprojectPoint(m_lastMousePoint); - Vec2 v2 = UnprojectPoint(event->pos()); - Vec2 v = v1 - v2; - - for (size_t i = 0; i < m_selectedIndices.size(); ++i) - { - int index = m_selectedIndices[i]; - CurvePoint& cpt = m_points[index]; - - // do not move first and last points on X - if (index > 0 && index < m_points.size() - 1) - { - cpt.pos.x -= v.x; - } - - cpt.pos.y -= v.y; - - // lets check if the point is overlapping its neighbours - if (index > 0 && (index - 1) > 0) - { - if (cpt.pos.x < m_points[index - 1].pos.x) - { - CurvePoint p = m_points[index]; - - // swap! - m_points[index] = m_points[index - 1]; - m_points[index - 1] = p; - m_selectedIndices[i] = index - 1; - } - } - - if (index < m_points.size() - 1 && (index + 1) < m_points.size() - 1) - { - if (cpt.pos.x > m_points[index + 1].pos.x) - { - CurvePoint p = m_points[index]; - - // swap! - m_points[index] = m_points[index + 1]; - m_points[index + 1] = p; - m_selectedIndices[i] = index + 1; - } - } - - ClampToDomain(cpt.pos); - } - - update(); - m_lastMousePoint = event->pos(); - } - - QWidget::mouseMoveEvent(event); -} - -void CCurveEditorCtrl::MarkX(float value) -{ - m_marksX.push_back(value); -} - -void CCurveEditorCtrl::MarkY(float value) -{ - m_marksY.push_back(value); -} diff --git a/Code/Sandbox/Editor/Controls/CurveEditorCtrl.h b/Code/Sandbox/Editor/Controls/CurveEditorCtrl.h deleted file mode 100644 index 52082febd7..0000000000 --- a/Code/Sandbox/Editor/Controls/CurveEditorCtrl.h +++ /dev/null @@ -1,112 +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_CURVEEDITORCTRL_H -#define CRYINCLUDE_EDITOR_CONTROLS_CURVEEDITORCTRL_H -#pragma once -#include "Util/GdiUtil.h" -#include -#include - - -class CCurveEditorCtrl - : public QWidget -{ -public: - enum EFlags - { - eFlag_ShowVerticalRuler = (1 << 0), - eFlag_ShowHorizontalRuler = (1 << 1), - eFlag_ShowVerticalRulerText = (1 << 2), - eFlag_ShowHorizontalRulerText = (1 << 3), - eFlag_ShowPaddingBorder = (1 << 4), - eFlag_ShowMovingPointAxis = (1 << 5), - eFlag_ShowPointHandles = (1 << 6), - eFlag_ShowCursorAlways = (1 << 7), - eFlag_Disabled = (1 << 8) // special case, when disabling preview window. - }; - - CCurveEditorCtrl(QWidget* parent); - virtual ~CCurveEditorCtrl(); - - void SetFlags(UINT aFlags); - UINT GetFlags() const; - void SetMouseEnable(bool bEnable = true) { m_bAllowMouse = bEnable; } - bool GetMouseEnable() const {return m_bAllowMouse; } - bool SetDomainBounds(float aMinX, float aMinY, float aMaxX, float aMaxY); - void GetDomainBounds(float& rMinX, float& rMinY, float& rMaxX, float& rMaxY) const; - // labelsX/labelsY must be null (to use default labels) - // or contain aHorizontalSplits+1/aVerticalSplits+1 items. - void SetGrid(UINT aHorizontalSplits, UINT aVerticalSplits, const QStringList& labelsX = QStringList(), const QStringList& labelsY = QStringList()); - void SetPadding(float padding) { m_padding = padding; } - void MarkX(float value); - void MarkY(float value); - void AddControlPoint(const Vec2& rPosition); - void ClearControlPoints(); - void SetControlPointCount(UINT aCount); - UINT GetControlPointCount() const; - void SetControlPoint(UINT aIndex, const Vec2& rPosition); - void SetControlPointTangents(UINT aIndex, const Vec2& rLeft, const Vec2& rRight); - void GetControlPoint(UINT aIndex, Vec2& rOutPosition) const; - void GetControlPointTangents(UINT aIndex, Vec2& rOutLeft, Vec2& rOutRight) const; - QPoint ProjectPoint(float x, float y); - Vec2 UnprojectPoint(const QPoint& pt); - void UpdateProjectedPoints(); - -protected: - struct CurvePoint - { - CurvePoint(float aX = 0.0f, float aY = 0.0f) - { - pos.x = aX; - pos.y = aY; - } - - Vec2 pos; - Vec2 tanA, tanB; - }; - - void ComputeTangents(); - void ClampToDomain(Vec2& rVec); - void GenerateDefaultCurve(); - - void paintEvent(QPaintEvent* event) override; - - std::vector m_points; - std::vector m_projectedPoints; - float m_domainMinX; - float m_domainMinY; - float m_domainMaxX; - float m_domainMaxY; - Vec2 m_gridSplits; - int m_padding; - bool m_bMouseDown, m_bDragging, m_bAllowMouse; - bool m_bHovered; - QPoint m_lastMousePoint; - std::vector m_selectedIndices; - QFont m_fntInfo; - QPen m_pen, m_selCrossPen; - UINT m_flags; - QStringList m_labelsX; - QStringList m_labelsY; - std::vector m_marksX; - std::vector m_marksY; - - void mousePressEvent(QMouseEvent* event) override; - void mouseReleaseEvent(QMouseEvent* event) override; - void mouseMoveEvent(QMouseEvent* event) override; -}; - - - -#endif // CRYINCLUDE_EDITOR_CONTROLS_CURVEEDITORCTRL_H diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index db37653cf1..8afcddd144 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -659,9 +659,6 @@ CBaseObject* EditorViewportWidget::GetCameraObject() const ////////////////////////////////////////////////////////////////////////// void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) { - static ICVar* outputToHMD = gEnv->pConsole->GetCVar("output_to_hmd"); - AZ_Assert(outputToHMD, "cvar output_to_hmd is undeclared"); - switch (event) { case eNotify_OnBeginGameMode: @@ -683,7 +680,6 @@ void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) if (deviceInfo) { // Note: This may also need to adjust the viewport size - outputToHMD->Set(1); SetActiveWindow(); SetFocus(); SetSelected(true); @@ -703,10 +699,6 @@ void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) if (GetIEditor()->GetViewManager()->GetGameViewport() == this) { SetCurrentCursor(STD_CURSOR_DEFAULT); - if (gSettings.bEnableGameModeVR) - { - outputToHMD->Set(0); - } m_bInRotateMode = false; m_bInMoveMode = false; m_bInOrbitMode = false; diff --git a/Code/Sandbox/Editor/IEditorImpl.cpp b/Code/Sandbox/Editor/IEditorImpl.cpp index 95091a5992..fb9b737733 100644 --- a/Code/Sandbox/Editor/IEditorImpl.cpp +++ b/Code/Sandbox/Editor/IEditorImpl.cpp @@ -71,7 +71,6 @@ AZ_POP_DISABLE_WARNING #include "EditorFileMonitor.h" #include "MainStatusBar.h" -#include "SettingsBlock.h" #include "ResourceSelectorHost.h" #include "Util/FileUtil_impl.h" #include "Util/ImageUtil_impl.h" @@ -1624,8 +1623,6 @@ ESystemConfigPlatform CEditorImpl::GetEditorConfigPlatform() const void CEditorImpl::InitFinished() { - SProjectSettingsBlock::Load(); - if (!m_bInitialized) { m_bInitialized = true; diff --git a/Code/Sandbox/Editor/Include/IResourceSelectorHost.h b/Code/Sandbox/Editor/Include/IResourceSelectorHost.h index f9245f97a4..43586f6cba 100644 --- a/Code/Sandbox/Editor/Include/IResourceSelectorHost.h +++ b/Code/Sandbox/Editor/Include/IResourceSelectorHost.h @@ -28,16 +28,6 @@ // } // REGISTER_RESOURCE_SELECTOR("Sound", SoundFileSelector, "Icons/sound_16x16.png") // -// To expose it to serialization: -// -// #include "Serialization/Decorators/Resources.h" -// template -// ResourceSelector SoundName(TString& s) { return ResourceSelector(s, "Sound"); } -// -// To use in serialization: -// -// ar(Serialization::SoundName(soundString), "soundString", "Sound String"); -// // Here is how it can be invoked directly: // // SResourceSelectorContext x; @@ -56,19 +46,7 @@ // // QString SoundFileSelector(const SResourceSelectorContext& x, const QString& previousValue, // SoundFileList* list) // your context argument -// -// And provide this value through serialization context: -// -// struct SourceFileList -// { -// void Serialize(IArchive& ar) -// { -// Serialization::SContext context(ar, this); -// ... -// } -// } -#include #include class QWidget; @@ -82,7 +60,6 @@ struct SResourceSelectorContext unsigned int entityId; void* contextObject; - Serialization::TypeID contextObjectType; SResourceSelectorContext() : parentWidget(0) @@ -107,7 +84,6 @@ struct IResourceSelectorHost virtual ~IResourceSelectorHost() = default; virtual QString SelectResource(const SResourceSelectorContext& context, const QString& previousValue) = 0; virtual const char* ResourceIconPath(const char* typeName) const = 0; - virtual Serialization::TypeID ResourceContextType(const char* typeName) const = 0; virtual void RegisterResourceSelector(const SStaticResourceSelectorEntry* entry) = 0; @@ -128,7 +104,6 @@ struct SStaticResourceSelectorEntry TResourceSelectionFunction function; TResourceSelectionFunctionWithContext functionWithContext; const char* iconPath; - Serialization::TypeID contextType; static SStaticResourceSelectorEntry*& GetFirst() { static SStaticResourceSelectorEntry* first; return first; } SStaticResourceSelectorEntry* next; @@ -150,7 +125,6 @@ struct SStaticResourceSelectorEntry , functionWithContext(TResourceSelectionFunctionWithContext(function)) , iconPath(icon) { - contextType = Serialization::TypeID::get(); next = GetFirst(); GetFirst() = this; } diff --git a/Code/Sandbox/Editor/ResourceSelectorHost.cpp b/Code/Sandbox/Editor/ResourceSelectorHost.cpp index 6711af0af0..cf08d7f4d4 100644 --- a/Code/Sandbox/Editor/ResourceSelectorHost.cpp +++ b/Code/Sandbox/Editor/ResourceSelectorHost.cpp @@ -72,16 +72,6 @@ public: return ""; } - Serialization::TypeID ResourceContextType(const char* typeName) const override - { - TTypeMap::const_iterator it = m_typeMap.find(typeName); - if (it != m_typeMap.end()) - { - return it->second->contextType; - } - return Serialization::TypeID(); - } - void RegisterResourceSelector(const SStaticResourceSelectorEntry* entry) override { m_typeMap[entry->typeName] = entry; diff --git a/Code/Sandbox/Editor/Serialization.h b/Code/Sandbox/Editor/Serialization.h deleted file mode 100644 index 85dfc35dc6..0000000000 --- a/Code/Sandbox/Editor/Serialization.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_EDITOR_SERIALIZATION_H -#define CRYINCLUDE_EDITOR_SERIALIZATION_H - -#include -#include -#include -#include -#include - -using Serialization::IArchive; - -#endif // CRYINCLUDE_EDITOR_SERIALIZATION_H diff --git a/Code/Sandbox/Editor/Serialization/VariableIArchive.cpp b/Code/Sandbox/Editor/Serialization/VariableIArchive.cpp deleted file mode 100644 index 235ec9a6b0..0000000000 --- a/Code/Sandbox/Editor/Serialization/VariableIArchive.cpp +++ /dev/null @@ -1,283 +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 "VariableIArchive.h" - -// Editor -#include "Serialization/Decorators/Resources.h" -#include "Serialization/Decorators/Range.h" - - -using Serialization::CVariableIArchive; - -namespace VarUtil -{ - _smart_ptr< IVariable > FindChildVariable(const _smart_ptr< IVariable >& pParent, const int childIndexOverride, const char* const name) - { - if (0 <= childIndexOverride) - { - return pParent->GetVariable(childIndexOverride); - } - else - { - const bool shouldSearchRecursively = false; - return pParent->FindVariable(name, shouldSearchRecursively); - } - } - - - template< typename T, typename TOut > - bool ReadChildVariableAs(const _smart_ptr< IVariable >& pParent, const int childIndexOverride, const char* const name, TOut& valueOut) - { - _smart_ptr< IVariable > pVariable = FindChildVariable(pParent, childIndexOverride, name); - if (pVariable) - { - T tmp; - pVariable->Get(tmp); - valueOut = static_cast< TOut >(tmp); - return true; - } - return false; - } - - - template< typename T > - bool ReadChildVariable(const _smart_ptr< IVariable >& pParent, const int childIndexOverride, const char* const name, T& valueOut) - { - return ReadChildVariableAs< T >(pParent, childIndexOverride, name, valueOut); - } -} - - - -CVariableIArchive::CVariableIArchive(const _smart_ptr< IVariable >& pVariable) - : IArchive(IArchive::INPUT | IArchive::EDIT | IArchive::NO_EMPTY_NAMES) - , m_pVariable(pVariable) - , m_childIndexOverride(-1) -{ - CRY_ASSERT(m_pVariable); - - m_structHandlers[ TypeID::get < Serialization::IResourceSelector > ().name() ] = &CVariableIArchive::SerializeResourceSelector; - m_structHandlers[ TypeID::get < Serialization::RangeDecorator < float >> ().name() ] = &CVariableIArchive::SerializeRangeFloat; - m_structHandlers[ TypeID::get < Serialization::RangeDecorator < int >> ().name() ] = &CVariableIArchive::SerializeRangeInt; - m_structHandlers[ TypeID::get < Serialization::RangeDecorator < unsigned int >> ().name() ] = &CVariableIArchive::SerializeRangeUInt; - m_structHandlers[ TypeID::get < StringListStaticValue > ().name() ] = &CVariableIArchive::SerializeStringListStaticValue; -} - - -CVariableIArchive::~CVariableIArchive() -{ -} - - -bool CVariableIArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< bool >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(Serialization::IString& value, const char* name, [[maybe_unused]] const char* label) -{ - QString stringValue; - const bool readSuccess = VarUtil::ReadChildVariableAs< QString >(m_pVariable, m_childIndexOverride, name, stringValue); - if (readSuccess) - { - value.set(stringValue.toUtf8().data()); - return true; - } - return false; -} - - -bool CVariableIArchive::operator()([[maybe_unused]] Serialization::IWString& value, [[maybe_unused]] const char* name, [[maybe_unused]] const char* label) -{ - CryFatalError("CVariableIArchive::operator() with IWString is not implemented"); - return false; -} - - -bool CVariableIArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< float >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< float >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(const Serialization::SStruct& ser, const char* name, const char* label) -{ - const char* const typeName = ser.type().name(); - HandlersMap::const_iterator it = m_structHandlers.find(typeName); - const bool handlerFound = (it != m_structHandlers.end()); - if (handlerFound) - { - StructHandlerFunctionPtr pHandler = it->second; - return (this->*pHandler)(ser, name, label); - } - - return SerializeStruct(ser, name, label); -} - - -bool CVariableIArchive::operator()(Serialization::IContainer& ser, const char* name, [[maybe_unused]] const char* label) -{ - _smart_ptr< IVariable > pChild = VarUtil::FindChildVariable(m_pVariable, m_childIndexOverride, name); - if (pChild) - { - const int elementCount = pChild->GetNumVariables(); - ser.resize(elementCount); - - if (0 < elementCount) - { - CVariableIArchive childArchive(pChild); - childArchive.SetFilter(GetFilter()); - childArchive.SetInnerContext(GetInnerContext()); - - for (int i = 0; i < elementCount; ++i) - { - childArchive.m_childIndexOverride = i; - - ser(childArchive, "", ""); - ser.next(); - } - } - return true; - } - return false; -} - - -bool CVariableIArchive::SerializeStruct(const Serialization::SStruct& ser, const char* name, [[maybe_unused]] const char* label) -{ - _smart_ptr< IVariable > pChild = VarUtil::FindChildVariable(m_pVariable, m_childIndexOverride, name); - if (pChild) - { - CVariableIArchive childArchive(pChild); - childArchive.SetFilter(GetFilter()); - childArchive.SetInnerContext(GetInnerContext()); - - ser(childArchive); - return true; - } - return false; -} - -bool CVariableIArchive::SerializeResourceSelector(const Serialization::SStruct& ser, const char* name, [[maybe_unused]] const char* label) -{ - Serialization::IResourceSelector* pSelector = reinterpret_cast< Serialization::IResourceSelector* >(ser.pointer()); - - QString stringValue; - const bool readSuccess = VarUtil::ReadChildVariableAs< QString >(m_pVariable, m_childIndexOverride, name, stringValue); - if (readSuccess) - { - pSelector->SetValue(stringValue.toUtf8().data()); - return true; - } - return false; -} - - -bool CVariableIArchive::SerializeStringListStaticValue(const Serialization::SStruct& ser, const char* name, [[maybe_unused]] const char* label) -{ - StringListStaticValue* const pStringListStaticValue = reinterpret_cast< StringListStaticValue* >(ser.pointer()); - - _smart_ptr< IVariable > pChild = VarUtil::FindChildVariable(m_pVariable, m_childIndexOverride, name); - if (pChild) - { - int index = -1; - pChild->Get(index); - *pStringListStaticValue = index; - return true; - } - return false; -} - - -bool CVariableIArchive::SerializeRangeFloat(const Serialization::SStruct& ser, const char* name, [[maybe_unused]] const char* label) -{ - const Serialization::RangeDecorator< float >* const pRange = reinterpret_cast< Serialization::RangeDecorator< float >* >(ser.pointer()); - return VarUtil::ReadChildVariableAs< float >(m_pVariable, m_childIndexOverride, name, *pRange->value); -} - - -bool CVariableIArchive::SerializeRangeInt(const Serialization::SStruct& ser, const char* name, [[maybe_unused]] const char* label) -{ - const Serialization::RangeDecorator< int >* const pRange = reinterpret_cast< Serialization::RangeDecorator< int >* >(ser.pointer()); - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, *pRange->value); -} - -bool CVariableIArchive::SerializeRangeUInt(const Serialization::SStruct& ser, const char* name, [[maybe_unused]] const char* label) -{ - const Serialization::RangeDecorator< unsigned int >* const pRange = reinterpret_cast< Serialization::RangeDecorator< unsigned int >* >(ser.pointer()); - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, *pRange->value); -} diff --git a/Code/Sandbox/Editor/Serialization/VariableIArchive.h b/Code/Sandbox/Editor/Serialization/VariableIArchive.h deleted file mode 100644 index ac7c0532e4..0000000000 --- a/Code/Sandbox/Editor/Serialization/VariableIArchive.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include "Util/Variable.h" -#include "Serialization.h" - -namespace Serialization -{ - class CVariableIArchive - : public IArchive - { - public: - CVariableIArchive(const _smart_ptr< IVariable >& pVariable); - virtual ~CVariableIArchive(); - - // IArchive - virtual bool operator()(bool& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(IString& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(IWString& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(float& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(double& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(int16& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(uint16& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(int32& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(uint32& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(int64& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(uint64& value, const char* name = "", const char* label = 0) override; - - virtual bool operator()(int8& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(uint8& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(char& value, const char* name = "", const char* label = 0); - - virtual bool operator()(const SStruct& ser, const char* name = "", const char* label = 0) override; - virtual bool operator()(IContainer& ser, const char* name = "", const char* label = 0) override; - //virtual bool operator()( IPointer& ptr, const char* name = "", const char* label = 0 ) override; - // ~IArchive - - using IArchive::operator(); - - private: - bool SerializeResourceSelector(const SStruct& ser, const char* name, const char* label); - - bool SerializeStruct(const SStruct& ser, const char* name, const char* label); - - bool SerializeStringListStaticValue(const SStruct& ser, const char* name, const char* label); - - bool SerializeRangeFloat(const SStruct& ser, const char* name, const char* label); - bool SerializeRangeInt(const SStruct& ser, const char* name, const char* label); - bool SerializeRangeUInt(const SStruct& ser, const char* name, const char* label); - - private: - _smart_ptr< IVariable > m_pVariable; - int m_childIndexOverride; - - typedef bool ( CVariableIArchive::* StructHandlerFunctionPtr )(const SStruct&, const char*, const char*); - typedef std::map< string, StructHandlerFunctionPtr > HandlersMap; - HandlersMap m_structHandlers; // TODO: have only one of these. - }; -} diff --git a/Code/Sandbox/Editor/Serialization/VariableOArchive.cpp b/Code/Sandbox/Editor/Serialization/VariableOArchive.cpp deleted file mode 100644 index d5c53d1966..0000000000 --- a/Code/Sandbox/Editor/Serialization/VariableOArchive.cpp +++ /dev/null @@ -1,416 +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 "VariableOArchive.h" - -// Editor -#include "Serialization/Decorators/Resources.h" -#include "Serialization/Decorators/Range.h" - - -using Serialization::CVariableOArchive; - -namespace VarUtil -{ - template< typename T > - _smart_ptr< IVariable > AddChildVariable(const _smart_ptr< IVariable >& pVariableArray, const T& value, const char* const name, const char* label) - { - CRY_ASSERT(pVariableArray); - - _smart_ptr< IVariable > pVariable = new CVariable< T >(); - pVariable->SetName(name); - pVariable->SetHumanName(label); - pVariable->Set(value); - - pVariableArray->AddVariable(pVariable); - - return pVariable; - } - - template< typename TMin, typename TMax > - void SetLimits(const _smart_ptr< IVariable >& pVariable, const TMin minValue, const TMax maxValue) - { - pVariable->SetLimits(static_cast< float >(minValue), static_cast< float >(maxValue)); - } -} - -CVariableOArchive::CVariableOArchive() - : IArchive(IArchive::OUTPUT | IArchive::EDIT | IArchive::NO_EMPTY_NAMES) - , m_pVariable(new CVariableArray()) -{ - m_resourceHandlers[ "Animation" ] = &CVariableOArchive::SerializeAnimationName; - m_resourceHandlers[ "Sound" ] = &CVariableOArchive::SerializeSoundName; - m_resourceHandlers[ "Model" ] = &CVariableOArchive::SerializeObjectFilename; - - m_structHandlers[ TypeID::get < Serialization::IResourceSelector > ().name() ] = &CVariableOArchive::SerializeIResourceSelector; - m_structHandlers[ TypeID::get < Serialization::RangeDecorator < float >> ().name() ] = &CVariableOArchive::SerializeRangeFloat; - m_structHandlers[ TypeID::get < Serialization::RangeDecorator < int >> ().name() ] = &CVariableOArchive::SerializeRangeInt; - m_structHandlers[ TypeID::get < Serialization::RangeDecorator < unsigned int >> ().name() ] = &CVariableOArchive::SerializeRangeUInt; - m_structHandlers[ TypeID::get < StringListStaticValue > ().name() ] = &CVariableOArchive::SerializeStringListStaticValue; -} - - -CVariableOArchive::~CVariableOArchive() -{ -} - - -_smart_ptr< IVariable > CVariableOArchive::GetIVariable() const -{ - return m_pVariable; -} - - -CVarBlockPtr CVariableOArchive::GetVarBlock() const -{ - CVarBlockPtr pVarBlock = new CVarBlock(); - pVarBlock->AddVariable(m_pVariable); - return pVarBlock; -} - - -bool CVariableOArchive::operator()(bool& value, const char* name, const char* label) -{ - VarUtil::AddChildVariable< bool >(m_pVariable, value, name, label); - return true; -} - - -bool CVariableOArchive::operator()(Serialization::IString& value, const char* name, const char* label) -{ - const QString valueString = value.get(); - VarUtil::AddChildVariable< QString >(m_pVariable, valueString, name, label); - return true; -} - - -bool CVariableOArchive::operator()([[maybe_unused]] Serialization::IWString& value, [[maybe_unused]] const char* name, [[maybe_unused]] const char* label) -{ - CryFatalError("CVarBlockOArchive::operator() with IWString is not implemented"); - return false; -} - - -bool CVariableOArchive::operator()(float& value, const char* name, const char* label) -{ - VarUtil::AddChildVariable< float >(m_pVariable, value, name, label); - return true; -} - - -bool CVariableOArchive::operator()(double& value, const char* name, const char* label) -{ - VarUtil::AddChildVariable< float >(m_pVariable, value, name, label); - return true; -} - - -bool CVariableOArchive::operator()(int16& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, SHRT_MIN, SHRT_MAX); - return true; -} - - -bool CVariableOArchive::operator()(uint16& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, 0, USHRT_MAX); - return true; -} - - -bool CVariableOArchive::operator()(int32& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, INT_MIN, INT_MAX); - return true; -} - - -bool CVariableOArchive::operator()(uint32& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, 0, INT_MAX); - return true; -} - - -bool CVariableOArchive::operator()(int64& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, INT_MIN, INT_MAX); - return true; -} - - -bool CVariableOArchive::operator()(uint64& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, 0, INT_MAX); - return true; -} - - -bool CVariableOArchive::operator()(int8& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, SCHAR_MIN, SCHAR_MAX); - return true; -} - - -bool CVariableOArchive::operator()(uint8& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, 0, UCHAR_MAX); - return true; -} - - -bool CVariableOArchive::operator()(char& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, CHAR_MIN, CHAR_MAX); - return true; -} - - -bool CVariableOArchive::operator()(const Serialization::SStruct& ser, const char* name, const char* label) -{ - const char* const typeName = ser.type().name(); - HandlersMap::const_iterator it = m_structHandlers.find(typeName); - const bool handlerFound = (it != m_structHandlers.end()); - if (handlerFound) - { - StructHandlerFunctionPtr pHandler = it->second; - return (this->*pHandler)(ser, name, label); - } - - return SerializeStruct(ser, name, label); -} - -static const char* gVec4Names[] = { "X", "Y", "Z", "W" }; -static const char* gEmptyNames[] = { "" }; - -bool CVariableOArchive::operator()(Serialization::IContainer& ser, const char* name, const char* label) -{ - CVariableOArchive childArchive; - childArchive.SetFilter(GetFilter()); - childArchive.SetInnerContext(GetInnerContext()); - - _smart_ptr< IVariable > pChildVariable = childArchive.GetIVariable(); - pChildVariable->SetName(name); - pChildVariable->SetHumanName(label); - - m_pVariable->AddVariable(pChildVariable); - - const size_t containerSize = ser.size(); - - const char** nameArray = gEmptyNames; - size_t nameArraySize = 1; - if (containerSize >= 2 && containerSize <= 4) - { - nameArray = gVec4Names; - nameArraySize = containerSize; - } - - size_t index = 0; - if (0 < containerSize) - { - do - { - ser(childArchive, nameArray[index % nameArraySize], nameArray[index % nameArraySize]); - ++index; - } while (ser.next()); - } - - return true; -} - - -bool CVariableOArchive::SerializeStruct(const Serialization::SStruct& ser, const char* name, const char* label) -{ - CVariableOArchive childArchive; - childArchive.SetFilter(GetFilter()); - childArchive.SetInnerContext(GetInnerContext()); - - _smart_ptr< IVariable > pChildVariable = childArchive.GetIVariable(); - pChildVariable->SetName(name); - pChildVariable->SetHumanName(label); - - m_pVariable->AddVariable(pChildVariable); - - const bool serializeSuccess = ser(childArchive); - - return serializeSuccess; -} - - -bool CVariableOArchive::SerializeAnimationName(const Serialization::IResourceSelector* pSelector, const char* name, const char* label) -{ - const QString valueString = pSelector->GetValue(); - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< QString >(m_pVariable, valueString, name, label); - pVariable->SetDataType(IVariable::DT_ANIMATION); - - return true; -} - - -bool CVariableOArchive::SerializeSoundName(const Serialization::IResourceSelector* pSelector, const char* name, const char* label) -{ - const QString valueString = pSelector->GetValue(); - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< QString >(m_pVariable, valueString, name, label); - pVariable->SetDataType(IVariable::DT_AUDIO_TRIGGER); - - return true; -} - -void CVariableOArchive::CreateChildEnumVariable(const QStringList& enumValues, const QString& value, const char* name, const char* label) -{ - if (enumValues.empty()) - { - VarUtil::AddChildVariable< QString >(m_pVariable, value, name, label); - } - else - { - _smart_ptr< CVariableEnum< QString > > pVariable = new CVariableEnum< QString >(); - pVariable->SetName(name); - pVariable->SetHumanName(label); - - pVariable->AddEnumItem("", ""); - - const size_t enumValuesCount = enumValues.size(); - for (size_t i = 0; i < enumValuesCount; ++i) - { - pVariable->AddEnumItem(enumValues[ i ], enumValues[ i ]); - } - - pVariable->Set(value); - - m_pVariable->AddVariable(pVariable); - } -} - -bool CVariableOArchive::SerializeObjectFilename(const Serialization::IResourceSelector* pSelector, const char* name, const char* label) -{ - const QString valueString = pSelector->GetValue(); - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< QString >(m_pVariable, valueString, name, label); - pVariable->SetDataType(IVariable::DT_OBJECT); - - return true; -} - - -bool CVariableOArchive::SerializeStringListStaticValue(const Serialization::SStruct& ser, const char* name, const char* label) -{ - const StringListStaticValue* const pStringListStaticValue = reinterpret_cast< StringListStaticValue* >(ser.pointer()); - const StringListStatic& stringListStatic = pStringListStaticValue->stringList(); - const int index = pStringListStaticValue->index(); - - _smart_ptr< CVariableEnum< int > > pVariable = new CVariableEnum< int >(); - pVariable->SetName(name); - pVariable->SetHumanName(label); - - const size_t stringListStaticSize = stringListStatic.size(); - for (size_t i = 0; i < stringListStaticSize; ++i) - { - pVariable->AddEnumItem(stringListStatic[ i ], static_cast< int >(i)); - } - - if (0 <= index) - { - CRY_ASSERT(index < stringListStaticSize); - pVariable->Set(static_cast< int >(index)); - } - - m_pVariable->AddVariable(pVariable); - - return true; -} - -bool CVariableOArchive::SerializeIResourceSelector(const Serialization::SStruct& ser, const char* name, const char* label) -{ - const Serialization::IResourceSelector* pSelector = reinterpret_cast< Serialization::IResourceSelector* >(ser.pointer()); - - ResourceHandlersMap::iterator it = m_resourceHandlers.find(pSelector->resourceType); - if (it != m_resourceHandlers.end()) - { - return (this->*(it->second))(pSelector, name, label); - } - return false; -} - -template -static void SetLimits(IVariable* pVariable, const Serialization::RangeDecorator* pRange, float stepValue) -{ - if (pRange->softMin != std::numeric_limits::lowest() || pRange->softMax != std::numeric_limits::max()) - { - float minimal = (float)pRange->softMin; - float maximal = (float)pRange->softMax; - bool hardMin = false; - bool hardMax = false; - if (pRange->hardMin != std::numeric_limits::lowest()) - { - minimal = pRange->hardMin; - hardMin = true; - } - if (pRange->hardMax != std::numeric_limits::max()) - { - maximal = pRange->hardMax; - hardMax = true; - } - pVariable->SetLimits(minimal, maximal, stepValue, hardMin, hardMax); - } - else - { - float minimal = 0.0f; - float maximal = 0.0f; - float oldStep = 0.0f; - bool hardMin = false; - bool hardMax = false; - pVariable->GetLimits(minimal, maximal, oldStep, hardMin, hardMax); - pVariable->SetLimits(minimal, maximal, stepValue, hardMin, hardMax); - } -} - -bool CVariableOArchive::SerializeRangeFloat(const Serialization::SStruct& ser, const char* name, const char* label) -{ - const Serialization::RangeDecorator< float >* const pRange = reinterpret_cast< Serialization::RangeDecorator< float >* >(ser.pointer()); - - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< float >(m_pVariable, *pRange->value, name, label); - - SetLimits(pVariable.get(), pRange, 0.01f); - return true; -} - -bool CVariableOArchive::SerializeRangeInt(const Serialization::SStruct& ser, const char* name, const char* label) -{ - const Serialization::RangeDecorator< int >* const pRange = reinterpret_cast< Serialization::RangeDecorator< int >* >(ser.pointer()); - - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, *pRange->value, name, label); - SetLimits(pVariable.get(), pRange, 1.0f); - return true; -} - -bool CVariableOArchive::SerializeRangeUInt(const Serialization::SStruct& ser, const char* name, const char* label) -{ - const Serialization::RangeDecorator< unsigned int >* const pRange = reinterpret_cast< Serialization::RangeDecorator< unsigned int >* >(ser.pointer()); - - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, *pRange->value, name, label); - SetLimits(pVariable, pRange, 1.0f); - return true; -} diff --git a/Code/Sandbox/Editor/Serialization/VariableOArchive.h b/Code/Sandbox/Editor/Serialization/VariableOArchive.h deleted file mode 100644 index 60de8f84ac..0000000000 --- a/Code/Sandbox/Editor/Serialization/VariableOArchive.h +++ /dev/null @@ -1,83 +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 - -#include "Util/Variable.h" -#include "Serialization.h" - - -namespace Serialization -{ - struct IResourceSelector; - - class CVariableOArchive - : public IArchive - { - public: - CVariableOArchive(); - virtual ~CVariableOArchive(); - - _smart_ptr< IVariable > GetIVariable() const; - CVarBlockPtr GetVarBlock() const; - - // IArchive - virtual bool operator()(bool& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(IString& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(IWString& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(float& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(double& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(int16& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(uint16& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(int32& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(uint32& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(int64& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(uint64& value, const char* name = "", const char* label = 0) override; - - virtual bool operator()(int8& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(uint8& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(char& value, const char* name = "", const char* label = 0); - - virtual bool operator()(const SStruct& ser, const char* name = "", const char* label = 0) override; - virtual bool operator()(IContainer& ser, const char* name = "", const char* label = 0) override; - //virtual bool operator()( IPointer& ptr, const char* name = "", const char* label = 0 ) override; - // ~IArchive - - using IArchive::operator(); - - private: - bool SerializeStruct(const SStruct& ser, const char* name, const char* label); - bool SerializeStringListStaticValue(const SStruct& ser, const char* name, const char* label); - bool SerializeRangeFloat(const SStruct& ser, const char* name, const char* label); - bool SerializeRangeInt(const SStruct& ser, const char* name, const char* label); - bool SerializeRangeUInt(const SStruct& ser, const char* name, const char* label); - bool SerializeIResourceSelector(const SStruct& ser, const char* name, const char* label); - - bool SerializeAnimationName(const IResourceSelector* pSelector, const char* name, const char* label); - bool SerializeSoundName(const IResourceSelector* pSelector, const char* name, const char* label); - bool SerializeObjectFilename(const IResourceSelector* pSelector, const char* name, const char* label); - - void CreateChildEnumVariable(const QStringList& enumValues, const QString& value, const char* name, const char* label); - - private: - _smart_ptr< IVariable > m_pVariable; - - typedef bool ( CVariableOArchive::* StructHandlerFunctionPtr )(const SStruct&, const char*, const char*); - typedef std::map< string, StructHandlerFunctionPtr > HandlersMap; - HandlersMap m_structHandlers; // TODO: have only one of these. - - typedef bool ( CVariableOArchive::* ResourceHandlerFunctionPtr )(const IResourceSelector*, const char*, const char*); - typedef std::map< string, ResourceHandlerFunctionPtr > ResourceHandlersMap; - ResourceHandlersMap m_resourceHandlers; - }; -} diff --git a/Code/Sandbox/Editor/SettingsBlock.cpp b/Code/Sandbox/Editor/SettingsBlock.cpp deleted file mode 100644 index d9f596c2d0..0000000000 --- a/Code/Sandbox/Editor/SettingsBlock.cpp +++ /dev/null @@ -1,177 +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 "SettingsBlock.h" - -// CryCommon -#include -#include - -// Editor -#include "Serialization.h" - -using std::vector; - -SProjectSettingsBlock* SProjectSettingsBlock::s_pLastBlock; - -SProjectSettingsBlock::SProjectSettingsBlock(const char* name, const char* label) - : m_name(name) - , m_label(label) -{ - m_pPrevious = s_pLastBlock; - s_pLastBlock = this; -} - - -struct SAllSettingsSerializer -{ - void Serialize(Serialization::IArchive& ar) - { - SProjectSettingsBlock* pCurrent = SProjectSettingsBlock::s_pLastBlock; - while (pCurrent != 0) - { - ar(*pCurrent, pCurrent->GetName(), pCurrent->GetLabel()); - pCurrent = pCurrent->m_pPrevious; - } - } -} static gAllSettingsSerializer; - -void SProjectSettingsBlock::GetAllSettingsSerializer(Serialization::SStruct* pSerializer) -{ - *pSerializer = Serialization::SStruct(gAllSettingsSerializer); -} - -SProjectSettingsBlock* SProjectSettingsBlock::Find(const char* blockName) -{ - SProjectSettingsBlock* pCurrent = SProjectSettingsBlock::s_pLastBlock; - while (pCurrent != 0) - { - if (_stricmp(pCurrent->GetName(), blockName) == 0) - { - return pCurrent; - } - } - return 0; -} - -static bool ReadFileContent(vector* pBuffer, const char* filename) -{ - AZ::IO::HandleType fileHandle = gEnv->pCryPak->FOpen(filename, "rb"); - if (fileHandle == AZ::IO::InvalidHandle) - { - return false; - } - - size_t size = gEnv->pCryPak->FGetSize(fileHandle); - pBuffer->resize(size); - - bool result = true; - if (gEnv->pCryPak->FRead(&(*pBuffer)[0], size, fileHandle) != size) - { - result = false; - } - gEnv->pCryPak->FClose(fileHandle); - return result; -} - -static bool SaveFileContent(const char* filename, const char* pBuffer, size_t length) -{ - string fullpath = Path::GamePathToFullPath(filename).toUtf8().data(); - - AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; - if (!gEnv->pFileIO->Open(fullpath.c_str(), AZ::IO::GetOpenModeFromStringMode("wb"), fileHandle)) - { - return false; - } - - bool result = true; - if (!gEnv->pFileIO->Write(fileHandle, pBuffer, length)) - { - result = false; - } - - gEnv->pFileIO->Close(fileHandle); - return result; -} - -static bool SaveFileContentIfDiffers(const char* filename, const char* pBuffer, size_t length) -{ - vector content; - ReadFileContent(&content, filename); - - bool needToWrite = true; - if (!content.empty() && content.size() == length) - { - needToWrite = memcmp(&content[0], pBuffer, length) != 0; - } - - if (needToWrite) - { - return SaveFileContent(filename, pBuffer, length); - } - else - { - return true; - } -} - -bool SProjectSettingsBlock::Load() -{ - const char* filename = GetFilename(); - - vector content; - if (!ReadFileContent(&content, filename)) - { - return false; - } - - auto pArchive(Serialization::CreateTextInputArchive()); - if (!pArchive) - { - return false; - } - - if (!pArchive->AttachMemory(&content[0], content.size())) - { - return false; - } - - Serialization::SStruct serializer; - GetAllSettingsSerializer(&serializer); - serializer(*pArchive); - return true; -} - -bool SProjectSettingsBlock::Save() -{ - const char* filename = GetFilename(); - auto pArchive(Serialization::CreateTextOutputArchive()); - if (!pArchive) - { - return false; - } - - Serialization::SStruct serializer; - GetAllSettingsSerializer(&serializer); - serializer(*pArchive); - - return SaveFileContentIfDiffers(filename, pArchive->GetBuffer(), pArchive->GetBufferLength()); -} - -const char* SProjectSettingsBlock::GetFilename() -{ - return "SandboxSettings.json"; -} - diff --git a/Code/Sandbox/Editor/SettingsBlock.h b/Code/Sandbox/Editor/SettingsBlock.h deleted file mode 100644 index b67e1d3d7e..0000000000 --- a/Code/Sandbox/Editor/SettingsBlock.h +++ /dev/null @@ -1,76 +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 - -// --------------------------------------------------------------------------- -// Following utility can be used to add blocks of per-project settings. -// Example: -// -// MyComponent.cpp: -// -// struct SProjectSettingsMy : SProjectSettingsBlock -// { -// bool bMyOption; -// -// SProjectSettingsMy() -// : SProjectSettingsBlock("my", "My") -// , bMyOption(false) -// {} -// -// void Serialize(Serialization::IArchive& ar) -// { -// ar(bMyOption, "myOption", "My Option"); -// } -// -// } static gMySettings; -// -// -// Now gMySettings will be loaded and saved automatically and available for -// editing through: -// -// GetIEditor()->OpenProjectSettings("my"); -// -// --------------------------------------------------------------------------- -#ifndef CRYINCLUDE_EDITOR_SETTINGSBLOCK_H -#define CRYINCLUDE_EDITOR_SETTINGSBLOCK_H - -namespace Serialization -{ - class IArchive; - struct SStruct; -}; - -struct SProjectSettingsBlock -{ - SProjectSettingsBlock(const char* name, const char* label); - - virtual void Serialize(Serialization::IArchive& ar) = 0; - - const char* GetName() const{ return m_name; } - const char* GetLabel() const{ return m_label; } - - static void GetAllSettingsSerializer(Serialization::SStruct* serializer); - static SProjectSettingsBlock* Find(const char* name); - static bool Load(); - static bool Save(); - static const char* GetFilename(); -private: - const char* m_name; - const char* m_label; - SProjectSettingsBlock* m_pPrevious; - static SProjectSettingsBlock* s_pLastBlock; - friend struct SAllSettingsSerializer; -}; - -#endif // CRYINCLUDE_EDITOR_SETTINGSBLOCK_H diff --git a/Code/Sandbox/Editor/editor_lib_files.cmake b/Code/Sandbox/Editor/editor_lib_files.cmake index 4832e2b8c2..3d6112d186 100644 --- a/Code/Sandbox/Editor/editor_lib_files.cmake +++ b/Code/Sandbox/Editor/editor_lib_files.cmake @@ -357,8 +357,6 @@ set(FILES Controls/ConsoleSCB.h Controls/ConsoleSCB.ui Controls/ConsoleSCB.qrc - Controls/CurveEditorCtrl.cpp - Controls/CurveEditorCtrl.h Controls/FolderTreeCtrl.cpp Controls/FolderTreeCtrl.h Controls/HotTrackingTreeCtrl.cpp @@ -575,11 +573,6 @@ set(FILES QtUI/WaitCursor.cpp RenderHelpers/AxisHelper.cpp RenderHelpers/AxisHelper.h - Serialization.h - Serialization/VariableOArchive.cpp - Serialization/VariableOArchive.h - Serialization/VariableIArchive.cpp - Serialization/VariableIArchive.h CustomizeKeyboardDialog.h CustomizeKeyboardDialog.cpp CustomizeKeyboardDialog.ui @@ -738,8 +731,6 @@ set(FILES TrackView/TrackViewEventNode.h ConfigGroup.cpp ConfigGroup.h - SettingsBlock.cpp - SettingsBlock.h Util/AffineParts.h Util/AutoLogTime.cpp Util/AutoLogTime.h diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin.cpp index e5ad2a2872..54ac71db16 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin.cpp @@ -15,7 +15,6 @@ #include #include "IResourceSelectorHost.h" -#include "CryExtension/ICryFactoryRegistry.h" #include "UI/QComponentEntityEditorMainWindow.h" #include "UI/QComponentEntityEditorOutlinerWindow.h" diff --git a/Code/Sandbox/Plugins/EditorCommon/BatchFileDialog.cpp b/Code/Sandbox/Plugins/EditorCommon/BatchFileDialog.cpp deleted file mode 100644 index 0dc7a8e7dc..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/BatchFileDialog.cpp +++ /dev/null @@ -1,357 +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 "EditorCommon_precompiled.h" -#include "BatchFileDialog.h" -#include "QPropertyTree/QPropertyDialog.h" -#include "Serialization/StringList.h" -#include "Serialization/STL.h" -#include "Serialization/IArchive.h" -#include "Serialization/STLImpl.h" -#include "IEditor.h" -#include "Pak/CryPakUtils.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -struct SBatchFileItem -{ - bool selected; - string path; - bool checkable = false; - - bool operator<(const SBatchFileItem& rhs) const { return path < rhs.path; } - - void Serialize(Serialization::IArchive& ar) - { - // ------------------------------------------------------------------- - // Note: The property tree label modifiers used below indicate... - // ! - Readonly, you can't modify the path - // ^ - Raise location to the parent (the index indicator) - // < - Take up the rest of the space - // ------------------------------------------------------------------- - if (!checkable) - { - ar(selected, "selected", "^"); - } - - auto gamePath = PathUtil::MakeGamePath(path); - ar(gamePath, "path", "!^<"); - } -}; -typedef std::vector SBatchFileItems; - -struct CBatchFileDialog::SContent -{ - SBatchFileItems items; - string listLabel; - - SContent(const char* itemsLabelText, bool readonlyList) - { - // Respect the readonly settings - if (readonlyList) - { - listLabel += "!"; - } - - // Label Size (5px per character) - auto labelSize = static_cast(strlen(itemsLabelText)) * 5; - { - // Format is: >#>+ where the >#> indicates the label size, and the + indicates end of all row formatting - char buffer[16]; - sprintf_s(buffer, sizeof(buffer), ">%i>+", labelSize); - listLabel += buffer; - } - - // Add the actual label text (the text that is seen) - listLabel += itemsLabelText; - } - - void Serialize(Serialization::IArchive& ar) - { - ar(items, "items", listLabel.c_str()); - } -}; - -static bool ReadFile(std::vector* buffer, const char* path) -{ - FILE* f = nullptr; - azfopen(&f, path, "rb"); - if (!f) - { - return false; - } - fseek(f, 0, SEEK_END); - size_t len = (size_t)ftell(f); - fseek(f, 0, SEEK_SET); - - buffer->resize(len); - bool result = true; - if (len) - { - result = fread(&(*buffer)[0], 1, len, f) == len; - } - fclose(f); - return result; -} - -static void SplitLines(std::vector* lines, const char* start, const char* end) -{ - const char* p = start; - const char* lineStart = start; - while (true) - { - if (p == end || *p == '\r' || *p == '\n') - { - if (p != lineStart) - { - string line(lineStart, p); - bool hasPrintableChars = false; - for (size_t i = 0; i < line.size(); ++i) - { - if (!isspace(line[i])) - { - hasPrintableChars = true; - } - } - if (hasPrintableChars) - { - lines->push_back(line); - } - } - lineStart = p + 1; - if (p == end) - { - break; - } - } - ++p; - } -} - -static string NormalizePath(const char* path) -{ - string result = path; - result.replace('\\', '/'); - result.MakeLower(); - - // strip .phys extensions in case list of .cdf is provided - string::size_type dotPos = result.rfind('.'); - if (dotPos != string::npos) - { - if (_stricmp(result.c_str() + dotPos, ".phys")) - { - result.erase(dotPos, 5); - } - } - return result; -} - -static bool IsEquivalentPath(const char* pathA, const char* pathB) -{ - string normalizedA = NormalizePath(pathA); - string normalizedB = NormalizePath(pathB); - return normalizedA == normalizedB; -} - -void CBatchFileDialog::OnLoadList() -{ - QString existingFile = QFileDialog::getOpenFileName(m_dialog, "Load file list...", QString(), QString("Text Files (*.txt)")); - if (existingFile.isEmpty()) - { - return; - } - - string path = existingFile.toLocal8Bit().data(); - std::vector content; - ReadFile(&content, path.c_str()); - - std::vector lines; - SplitLines(&lines, &content[0], &content[0] + content.size()); - - for (size_t i = 0; i < m_content->items.size(); ++i) - { - m_content->items[i].selected = false; - } - - for (size_t i = 0; i < lines.size(); ++i) - { - const char* line = lines[i].c_str(); - for (size_t j = 0; j < m_content->items.size(); ++j) - { - const char* itemPath = m_content->items[j].path.c_str(); - if (IsEquivalentPath(line, itemPath)) - { - m_content->items[j].selected = true; - break; - } - } - } - - m_dialog->revert(); -} - -void CBatchFileDialog::OnSelectAll() -{ - for (size_t i = 0; i < m_content->items.size(); ++i) - { - m_content->items[i].selected = true; - } - - m_dialog->revert(); -} - -void CBatchFileDialog::OnSelectNone() -{ - for (size_t i = 0; i < m_content->items.size(); ++i) - { - m_content->items[i].selected = false; - } - - m_dialog->revert(); -} - -bool EDITOR_COMMON_API ShowBatchFileDialog(Serialization::StringList* result, const SBatchFileSettings& settings, QWidget* parent) -{ - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - - CBatchFileDialog::SContent content(settings.listLabel, settings.readonlyList); - if (settings.scanExtension[0] != '\0') - { - if (settings.useCryPak) - { - AZStd::vector files; - - string mask = "*."; - mask += settings.scanExtension; - SDirectoryEnumeratorHelper helper; - helper.ScanDirectoryRecursive(gEnv->pCryPak, Path::GetEditingGameDataFolder().c_str(), "", mask.c_str(), files); - - for (int k = 0; k < files.size(); ++k) - { - SBatchFileItem item; - item.checkable = settings.filesAreCheckable; - item.selected = true; - item.path = { files[k].data(), files[k].size() }; - content.items.push_back(item); - } - } - else - { - string gameFolder = Path::GetEditingGameDataFolder().c_str(); - string gamePrefix = GetIEditor()->GetPrimaryCDFolder().toUtf8().data(); - if (!gamePrefix.empty() && gamePrefix[gamePrefix.size() - 1] != '\\') - { - gamePrefix += "\\"; - } - gamePrefix += gameFolder; - if (!gamePrefix.empty() && gamePrefix[gamePrefix.size() - 1] != '\\') - { - gamePrefix += "\\"; - } - gamePrefix.replace('/', '\\'); - - QString mask = "*." + QString(settings.scanExtension); - QDirIterator dirIterator(QString(gamePrefix), QStringList() << mask, QDir::Files, QDirIterator::Subdirectories); - while (dirIterator.hasNext()) - { - SBatchFileItem item; - item.selected = true; - QByteArray array = dirIterator.next().toUtf8(); - item.path = string(array); - item.path.replace('/', '\\'); - content.items.push_back(item); - } - - } - } - - content.items.reserve(content.items.size() + settings.explicitFileList.size()); - for (size_t i = 0; i < settings.explicitFileList.size(); ++i) - { - SBatchFileItem item; - item.path = settings.explicitFileList[i].c_str(); - item.selected = true; - content.items.push_back(item); - } - - - std::sort(content.items.begin(), content.items.end()); - QApplication::restoreOverrideCursor(); - - QPropertyDialog dialog(parent); - dialog.setSerializer(Serialization::SStruct(content)); - dialog.setWindowTitle(settings.title); - dialog.setWindowStateFilename(settings.stateFilename); - dialog.setSizeHint(QSize(settings.defaultWidth, settings.defaultHeight)); - dialog.setMinimumSize(QSize(540, 250)); - - CBatchFileDialog handler; - handler.m_dialog = &dialog; - handler.m_content = &content; - - QBoxLayout* topRow = new QBoxLayout(QBoxLayout::LeftToRight); - QLabel* label = new QLabel(settings.descriptionText); - QFont font; - font.setBold(true); - label->setFont(font); - topRow->addWidget(label, 1); - { - if (settings.allowListLoading && !settings.readonlyList) - { - QPushButton* loadListButton = new QPushButton("Load List..."); - QObject::connect(loadListButton, SIGNAL(pressed()), &handler, SLOT(OnLoadList())); - topRow->addWidget(loadListButton); - } - QPushButton* selectAllButton = new QPushButton("Select All"); - QObject::connect(selectAllButton, SIGNAL(pressed()), &handler, SLOT(OnSelectAll())); - topRow->addWidget(selectAllButton); - QPushButton* selectNoneButton = new QPushButton("Select None"); - QObject::connect(selectNoneButton, SIGNAL(pressed()), &handler, SLOT(OnSelectNone())); - topRow->addWidget(selectNoneButton); - } - dialog.layout()->insertLayout(0, topRow); - - if (parent) - { - QPoint center = parent->rect().center(); - dialog.window()->move(max(0, center.x() - dialog.width() / 2), - max(0, center.y() - dialog.height() / 2)); - } - - std::vector failedFiles; - if (dialog.exec() == QDialog::Accepted) - { - result->clear(); - for (size_t i = 0; i < content.items.size(); ++i) - { - if (content.items[i].selected) - { - const char* path = content.items[i].path.c_str(); - result->push_back(path); - } - } - return true; - } - return false; -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/BatchFileDialog.h b/Code/Sandbox/Plugins/EditorCommon/BatchFileDialog.h deleted file mode 100644 index 3c1b071bca..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/BatchFileDialog.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. - -#ifndef CRYINCLUDE_EDITORCOMMON_BATCHFILEDIALOG_H -#define CRYINCLUDE_EDITORCOMMON_BATCHFILEDIALOG_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "EditorCommonAPI.h" -#include -#include -#endif - -// Private class, should not be used directly -class QWidget; -class QPropertyDialog; -class CBatchFileDialog - : public QObject -{ - Q_OBJECT - -public slots: - void OnSelectAll(); - void OnSelectNone(); - void OnLoadList(); - -public: - QPropertyDialog* m_dialog; - struct SContent; - SContent* m_content; -}; -// ^^^ - -struct SBatchFileSettings -{ - const char* scanExtension; - const char* scanFolder; - const char* title; - const char* descriptionText; - const char* listLabel; - const char* stateFilename; - bool useCryPak; - bool allowListLoading; - bool readonlyList; - bool filesAreCheckable; - Serialization::StringList explicitFileList; - int defaultWidth; - int defaultHeight; - - SBatchFileSettings() - : useCryPak(true) - , readonlyList(true) - , filesAreCheckable(false) - , allowListLoading(true) - , descriptionText("Batch Selected Files") - , listLabel("Files") - , stateFilename("batchFileDialog.state") - , title("Batch Files") - , scanFolder("") - , scanExtension("*") - { - } -}; - -bool EDITOR_COMMON_API ShowBatchFileDialog(Serialization::StringList* filenames, const SBatchFileSettings& settings, QWidget* parent); - -#endif // CRYINCLUDE_EDITORCOMMON_BATCHFILEDIALOG_H diff --git a/Code/Sandbox/Plugins/EditorCommon/CMakeLists.txt b/Code/Sandbox/Plugins/EditorCommon/CMakeLists.txt index b0450d6b3d..001f0c65d5 100644 --- a/Code/Sandbox/Plugins/EditorCommon/CMakeLists.txt +++ b/Code/Sandbox/Plugins/EditorCommon/CMakeLists.txt @@ -13,8 +13,6 @@ if(NOT PAL_TRAIT_BUILD_HOST_TOOLS) return() endif() -ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) - # Header only target to prevent linkage against editor libraries when it is not needed. Eventually the targets that depend # on editor headers should cleanup dependencies and interact with the editor through buses or other mechanisms ly_add_target( @@ -34,7 +32,6 @@ ly_add_target( AUTORCC FILES_CMAKE editorcommon_files.cmake - ${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake INCLUDE_DIRECTORIES PUBLIC . diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditor.cpp b/Code/Sandbox/Plugins/EditorCommon/CurveEditor.cpp deleted file mode 100644 index e5426b78e4..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditor.cpp +++ /dev/null @@ -1,2459 +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 "EditorCommon_precompiled.h" -#include "CurveEditor.h" -#include "CurveEditorControl.h" -#include "DrawingPrimitives/TimeSlider.h" -#include "DrawingPrimitives/Ruler.h" - -AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") // class '...' needs to have dll-interface to be used by clients of class '...' -#include -#include -#include -#include -#include -#include -#include -#include -#include -AZ_POP_DISABLE_WARNING - -// C6201: buffer overrun for , which is possibly stack allocated: index is out of valid index range to -#if defined(__clang__) -#define INDEX_NOT_OUT_OF_RANGE _Pragma("clang diagnostic ignored \"-Warray-bounds\"") -#else -#define INDEX_NOT_OUT_OF_RANGE PREFAST_SUPPRESS_WARNING(6201) -#endif - -#define NO_BUFFER_OVERRUN PREFAST_SUPPRESS_WARNING(6385 6386) -#include -#include "Cry_LegacyPhysUtils.h" - -namespace CurveEditorHelpers -{ - const uint numColors = 4; - ColorB colors[numColors] = - { - ColorB(243, 126, 121), - ColorB(121, 152, 243), - ColorB(187, 243, 121), - ColorB(243, 121, 223), - }; - - ColorB GetCurveColor(const uint n) - { - return colors[n % numColors]; - } - - QColor LerpColor(const QColor& a, const QColor& b, float k) - { - float mk = 1.0f - k; - return QColor(aznumeric_cast(a.red() * mk + b.red() * k), - aznumeric_cast(a.green() * mk + b.green() * k), - aznumeric_cast(a.blue() * mk + b.blue() * k), - aznumeric_cast(a.alpha() * mk + b.alpha() * k)); - } -} - -namespace -{ - const int kRulerHeight = 16; - const int kRulerShadowHeight = 6; - const int kRulerMarkHeight = 8; - const int kTextXOffset = -1; - const int kTextYOffset = 16; - const int kTangentLength = 24; - - const float kHitDistance = 15.0f; - const float kMinZoom = 0.001f; - const float kMaxZoom = 1000.0f; - const float kFitMargin = 16.0f; - - const QPointF kPointRectExtent = QPointF(2.5f, 2.5f); - - Vec2 TransformPointToScreen(const Vec2 zoom, const Vec2 translation, QRect curveArea, Vec2 point) - { - Vec2 transformedPoint = Vec2(point.x * zoom.x, point.y * -zoom.y) + translation; - transformedPoint.x *= curveArea.width(); - transformedPoint.y *= curveArea.height(); - return Vec2(transformedPoint.x + curveArea.left(), transformedPoint.y + curveArea.top()); - } - - Vec2 TransformPointFromScreen(const Vec2 zoom, const Vec2 translation, QRect curveArea, Vec2 point) - { - Vec2 transformedPoint = Vec2((point.x - curveArea.left()) / curveArea.width(), (point.y - curveArea.top()) / curveArea.height()) - translation; - transformedPoint.x /= zoom.x; - transformedPoint.y /= -zoom.y; - return Vec2(transformedPoint.x, transformedPoint.y); - } - - float EvaluateBezier(float t, float p0, float p1, float p2, float p3) - { - const float a = 1 - t; - const float aSq = a * a; - const float tSq = t * t; - return (aSq * a * p0) + (3.0f * aSq * t * p1) + (3.0f * a * tSq * p2) + (tSq * t * p3); - } - - void SplitBezier(SCurveEditorKey& newKey, SCurveEditorKey& leftKey, SCurveEditorKey& rightKey) - { - // use De Casteljau's algorithm to find the - float normalizedTime = (newKey.m_time - leftKey.m_time) / (rightKey.m_time - leftKey.m_time); - - Vec2 p0 = Vec2(leftKey.m_time, leftKey.m_value); - Vec2 p3 = Vec2(rightKey.m_time, rightKey.m_value); - Vec2 p1 = p0 + leftKey.m_outTangent; - Vec2 p2 = p3 + rightKey.m_inTangent; - - Vec2 q0 = p0 + (p1 - p0) * normalizedTime; - Vec2 q1 = p1 + (p2 - p1) * normalizedTime; - Vec2 q2 = p2 + (p3 - p2) * normalizedTime; - - Vec2 r0 = q0 + (q1 - q0) * normalizedTime; - Vec2 r1 = q1 + (q2 - q1) * normalizedTime; - - Vec2 s0 = r0 + (r1 - r0) * normalizedTime; - - newKey.m_inTangent = r0 - s0; - newKey.m_outTangent = r1 - s0; - - leftKey.m_outTangent = q0 - p0; - rightKey.m_inTangent = q2 - p3; - } - - QPointF Vec2ToPoint(Vec2 point) - { - return QPointF(point.x, point.y); - } - - Vec2 PointToVec2(QPointF point) - { - return Vec2(aznumeric_cast(point.x()), aznumeric_cast(point.y())); - } - - // This function returns a new key with position and weights affected by eTangentType_Smooth, eTangentType_Linear and eTangentType_Step for the outgoing tangent - SCurveEditorKey ApplyOutTangentFlags(const SCurveEditorKey& key, [[maybe_unused]] const SCurveEditorKey* pLeftKey, const SCurveEditorKey& rightKey) - { - SCurveEditorKey newKey = key; - - if (rightKey.m_inTangentType == SCurveEditorKey::eTangentType_Step - && key.m_outTangentType != SCurveEditorKey::eTangentType_Step) - { - newKey.m_outTangent.y = 0.0f; - return newKey; - } - - switch (key.m_outTangentType) - { - case SCurveEditorKey::eTangentType_Linear: - newKey.m_outTangent.y = (rightKey.m_value - key.m_value) / 3.0f; - break; - case SCurveEditorKey::eTangentType_Step: - newKey.m_outTangent.x = 0.0f; - newKey.m_outTangent.y = 0.0f; - newKey.m_value = rightKey.m_value; - break; - default: - const float oneThirdDeltaTime = (rightKey.m_time - newKey.m_time) / 3.0f; - float ratio = oneThirdDeltaTime / newKey.m_outTangent.x; - newKey.m_outTangent *= ratio; - break; - } - - return newKey; - } - - // This function returns a new key with position and weights affected by eTangentType_Smooth, eTangentType_Linear and eTangentType_Step for the incoming tangent - SCurveEditorKey ApplyInTangentFlags(const SCurveEditorKey& key, const SCurveEditorKey& leftKey, [[maybe_unused]] const SCurveEditorKey* pRightKey) - { - SCurveEditorKey newKey = key; - - if (leftKey.m_outTangentType == SCurveEditorKey::eTangentType_Step) - { - newKey.m_inTangent.y = 0.0f; - return newKey; - } - - switch (key.m_inTangentType) - { - case SCurveEditorKey::eTangentType_Linear: - newKey.m_inTangent.y = (leftKey.m_value - key.m_value) / 3.0f; - break; - case SCurveEditorKey::eTangentType_Step: - newKey.m_inTangent.x = 0.0f; - newKey.m_inTangent.y = 0.0f; - newKey.m_value = leftKey.m_value; - break; - default: - const float oneThirdDeltaTime = (newKey.m_time - leftKey.m_time) / 3.0f; - float ratio = oneThirdDeltaTime / -newKey.m_inTangent.x; - newKey.m_inTangent *= ratio; - break; - } - - return newKey; - } - - QPainterPath CreatePathFromCurve(const SCurveEditorCurve& curve, - ECurveEditorCurveType curveType, AZStd::function transformFunc) - { - QPainterPath path; - - const Vec2 startPoint(curve.m_keys[0].m_time, curve.m_keys[0].m_value); - const Vec2 startTransformed = transformFunc(startPoint); - path.moveTo(startTransformed.x, startTransformed.y); - - const auto endIter = curve.m_keys.end() - 1; - - if (curve.m_customInterpolator && curve.m_keys.size() > 1) - { - const float range_start = curve.m_customInterpolator->GetKeyTime(0); - const float range_end = curve.m_customInterpolator->GetKeyTime(curve.m_customInterpolator->GetKeyCount() - 1); - const float range_delta = range_end - range_start; - - if (range_delta > 0) - { - const int drawResolution = (int)ceil_tpl(transformFunc(Vec2(range_end, 0.0f)).x - - transformFunc(Vec2(range_start, 0.0f)).x); - - const float increment = range_delta / drawResolution; - std::vector drawList; - drawList.reserve(512); - float value; - for (float time = range_start; time < range_end; time += increment) - { - curve.m_customInterpolator->InterpolateFloat(time, value); - drawList.push_back(Vec2(time, value)); - } - - path.moveTo(Vec2ToPoint(transformFunc(drawList.front()))); - for (int i = 1; i < drawList.size(); i++) - { - path.lineTo(Vec2ToPoint(transformFunc(drawList[i]))); - } - } - } - else if (curveType == eCECT_Bezier) - { - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - const SCurveEditorKey* pKeyLeftOfSegment = (iter != curve.m_keys.begin()) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pKeyRightOfSegment = (iter != (curve.m_keys.end() - 2)) ? &*(iter + 2) : nullptr; - - const SCurveEditorKey segmentStartKey = ApplyOutTangentFlags(*iter, pKeyLeftOfSegment, *(iter + 1)); - const SCurveEditorKey segmentEndKey = ApplyInTangentFlags(*(iter + 1), *iter, pKeyRightOfSegment); - - const Vec2 p0 = Vec2(segmentStartKey.m_time, segmentStartKey.m_value); - const Vec2 p3 = Vec2(segmentEndKey.m_time, segmentEndKey.m_value); - - // Need to compute tangents for x so that the cubic 2D Bezier does a linear interpolation in - // that dimension, because we actually want to draw a cubic 1D Bezier curve - //const float outTangentX = (2.0f * p0.x + p3.x) / 3.0f; // p1 = (2 * p0 + p3) / 3 - //const float inTangentX = (p0.x + 2.0f * p3.x) / 3.0f; // p2 = (p0 + 2 * p3) / 3 - - const Vec2 p1 = p0 + segmentStartKey.m_outTangent; // Vec2(inTangentX, p0.y + segmentStartKey.m_outTangent.y); - const Vec2 p2 = p3 + segmentEndKey.m_inTangent; // Vec2(inTangentX, p3.y + segmentEndKey.m_inTangent.y); - - const QPointF p0Transformed = Vec2ToPoint(transformFunc(p0)); - const QPointF p1Transformed = Vec2ToPoint(transformFunc(p1)); - const QPointF p2Transformed = Vec2ToPoint(transformFunc(p2)); - const QPointF p3Transformed = Vec2ToPoint(transformFunc(p3)); - path.moveTo(p0Transformed); - path.cubicTo(p1Transformed, p2Transformed, p3Transformed); - } - } - else if (curveType == eCECT_2DBezier) - { - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - const SCurveEditorKey& segmentStartKey = *iter; - const SCurveEditorKey& segmentEndKey = *(iter + 1); - - const Vec2 p0 = Vec2(segmentStartKey.m_time, segmentStartKey.m_value); - const Vec2 p3 = Vec2(segmentEndKey.m_time, segmentEndKey.m_value); - const Vec2 p1 = p0 + segmentStartKey.m_outTangent; - const Vec2 p2 = p3 + segmentEndKey.m_inTangent; - - const QPointF p1Transformed = Vec2ToPoint(transformFunc(p1)); - const QPointF p2Transformed = Vec2ToPoint(transformFunc(p2)); - const QPointF p3Transformed = Vec2ToPoint(transformFunc(p3)); - path.cubicTo(p1Transformed, p2Transformed, p3Transformed); - } - } - - return path; - } - - // Renders path outside of the current range of the curve - QPainterPath CreateExtrapolatedPathFromCurve(const SCurveEditorCurve& curve, AZStd::function transformFunc, float windowWidth) - { - QPainterPath path; - - if (curve.m_keys.size() > 0) - { - const Vec2 startPoint = Vec2(curve.m_keys[0].m_time, curve.m_keys[0].m_value); - const Vec2 startTransformed = transformFunc(startPoint); - if (startTransformed.x > 0.0f) - { - path.moveTo(std::min(startTransformed.x, windowWidth), startTransformed.y); - path.lineTo(0.0f, startTransformed.y); - } - - const Vec2 endPoint(curve.m_keys.back().m_time, curve.m_keys.back().m_value); - const Vec2 endTransformed = transformFunc(endPoint); - if (endTransformed.x < windowWidth) - { - path.moveTo(std::max(endTransformed.x, 0.0f), endTransformed.y); - path.lineTo(windowWidth, endTransformed.y); - } - } - else - { - const Vec2 pointOnCurve = Vec2(0.0f, curve.m_defaultValue); - const Vec2 pointOnTransformed = transformFunc(pointOnCurve); - path.moveTo(0.0, pointOnTransformed.y); - path.lineTo(windowWidth, pointOnTransformed.y); - } - - QVector dashPattern; - dashPattern << 16 << 8; - - QPainterPathStroker stroker; - stroker.setCapStyle(Qt::RoundCap); - stroker.setDashPattern(dashPattern); - stroker.setWidth(0.5); - - return stroker.createStroke(path); - } - - // Renders line between discontinuous path when step mode is used for a control point - QPainterPath CreateDiscontinuinityPathFromCurve(const SCurveEditorCurve& curve, ECurveEditorCurveType curveType, AZStd::function transformFunc) - { - QPainterPath path; - - if (curve.m_keys.size() > 0) - { - const auto endIter = curve.m_keys.end() - 1; - - if (curveType == eCECT_Bezier && !curve.m_customInterpolator) - { - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - const SCurveEditorKey* pKeyLeftOfSegment = (iter != curve.m_keys.begin()) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pKeyRightOfSegment = (iter != (curve.m_keys.end() - 2)) ? &*(iter + 2) : nullptr; - - const SCurveEditorKey segmentStartKey = ApplyOutTangentFlags(*iter, pKeyLeftOfSegment, *(iter + 1)); - const SCurveEditorKey segmentEndKey = ApplyInTangentFlags(*(iter + 1), *iter, pKeyRightOfSegment); - - if (segmentStartKey.m_value != iter->m_value) - { - const Vec2 start = Vec2(segmentStartKey.m_time, segmentStartKey.m_value); - const Vec2 end = Vec2(iter->m_time, iter->m_value); - - const QPointF startTransformed = Vec2ToPoint(transformFunc(start)); - const QPointF endTransformed = Vec2ToPoint(transformFunc(end)); - - path.moveTo(startTransformed); - path.lineTo(endTransformed); - } - - if (segmentEndKey.m_value != (iter + 1)->m_value) - { - const Vec2 start = Vec2(segmentEndKey.m_time, segmentEndKey.m_value); - const Vec2 end = Vec2((iter + 1)->m_time, (iter + 1)->m_value); - - const QPointF startTransformed = Vec2ToPoint(transformFunc(start)); - const QPointF endTransformed = Vec2ToPoint(transformFunc(end)); - - path.moveTo(startTransformed); - path.lineTo(endTransformed); - } - } - } - } - - QVector dashPattern; - dashPattern << 2 << 10; - - QPainterPathStroker stroker; - stroker.setCapStyle(Qt::RoundCap); - stroker.setDashPattern(dashPattern); - stroker.setWidth(0.5); - - return stroker.createStroke(path); - } - - void DrawPointRect(QPainter& painter, QPointF point, const QColor& color) - { - painter.setBrush(QBrush(color)); - painter.setPen(QColor(0, 0, 0)); - painter.drawRect(QRectF(point - kPointRectExtent, point + kPointRectExtent)); - } - - void ForEachKey(SCurveEditorContent& content, AZStd::function fun) - { - for (auto iter = content.m_curves.begin(); iter != content.m_curves.end(); ++iter) - { - SCurveEditorCurve& curve = *iter; - for (size_t i = 0; i < curve.m_keys.size(); ++i) - { - fun(curve, curve.m_keys[i]); - } - } - } - - Vec2 ClosestPointOnBezierSegment(const Vec2 point, const float t0, const float t1, const float p0, const float p1, const float p2, const float p3) - { - using namespace LegacyCryPhysicsUtils; - - // If values are too close the distance function is too flat to be useful. We just assume the curve is flat then - if ((p0 * p0 + p1 * p1 + p2 * p2 + p3 * p3) < 1e-10f) - { - return Vec2(point.x, p0); - } - - const float deltaTime = (t1 - t0); - const float deltaTimeSq = deltaTime * deltaTime; - - // Those are just the normal cubic Bezier formulas B(t) and B'(t) in collected polynomial form - const P3f cubicBezierPoly = P3f(-p0 + 3.0f * p1 - 3.0f * p2 + p3) + P2f(3.0f * p0 - 6.0f * p1 + 3.0f * p2) + P1f(3.0f * p1 - 3.0f * p0) + p0; - const P2f cubicBezierDerivativePoly = P2f(-3.0f * p0 + 9.0f * p1 - 6.0f * p2 + 3.0f * (p3 - p2)) + P1f(6.0f * p0 - 12.0f * p1 + 6.0f * p2) - 3.0f * p0 + 3.0f * p1; - - // lerp(t, t0, t1) in polynomial form - const P1f timePoly = P1f(deltaTime) + t0; - - // Derivative of the distance function (cubicBezierPoly - point.y) ^ 2 + (timePoly - point.x) ^ 2 - const auto distanceDerivativePoly = (cubicBezierDerivativePoly * (cubicBezierPoly - point.y) + (timePoly - point.x) * deltaTime) * 2.0f; - - // The point of minimum distance must be at one of the roots of the distance derivative or at the start/end of the segment - float checkPoints[7]; - const uint numRoots = distanceDerivativePoly.findroots(0.0f, 1.0f, checkPoints + 2); - // Start and end of segment - checkPoints[0] = 0.0f; - checkPoints[1] = 1.0f; - - // Find the closest point under all the candidates - Vec2 closestPoint; - float minDistanceSq = std::numeric_limits::max(); - for (uint i = 0; i < numRoots + 2; ++i) - { - const Vec2 rootPoint(Lerp(t0, t1, checkPoints[i]), EvaluateBezier(checkPoints[i], p0, p1, p2, p3)); - const float deltaX = rootPoint.x - point.x; - const float deltaY = rootPoint.y - point.y; - const float distSq = deltaX * deltaX + deltaY * deltaY; - if (distSq < minDistanceSq) - { - closestPoint = rootPoint; - minDistanceSq = distSq; - } - } - - return closestPoint; - } - - Range GetBezierSegmentValueRange(const SCurveEditorKey& startKey, const SCurveEditorKey& endKey) - { - using namespace LegacyCryPhysicsUtils; - - const float p0 = startKey.m_value; - const float p1 = p0 + startKey.m_outTangent.y; - const float p3 = endKey.m_value; - const float p2 = p3 + endKey.m_inTangent.y; - - Range valueRange(std::min(p0, p3), std::max(p0, p3)); - const P2f cubicBezierDerivativePoly = P2f(-3.0f * p0 + 9.0f * p1 - 6.0f * p2 + 3.0f * (p3 - p2)) + P1f(6.0f * p0 - 12.0f * p1 + 6.0f * p2) - 3.0f * p0 + 3.0f * p1; - - float roots[2]; - const uint numRoots = cubicBezierDerivativePoly.findroots(0.0f, 1.0f, roots); - for (uint i = 0; i < numRoots; ++i) - { - const float rootValue = EvaluateBezier(roots[i], p0, p1, p2, p3); - valueRange.start = std::min(valueRange.start, rootValue); - valueRange.end = std::max(valueRange.end, rootValue); - } - return valueRange; - } - - float DistanceTo2DBezierSegment([[maybe_unused]] const Vec2 point, [[maybe_unused]] const SCurveEditorKey& startKey, [[maybe_unused]] const SCurveEditorKey& endKey) - { - return std::numeric_limits::max(); - } - - - void SmoothTangents(const SCurveEditorKey& key, Vec2& inTangent, Vec2& outTangent, SCurveEditorKey* pLeftKey, SCurveEditorKey* pRightKey, bool applyInverseSegmentLengthFactor) - { - inTangent.Normalize(); - outTangent.Normalize(); - - if (!pLeftKey && !pRightKey) - { - return; - } - else if (!pLeftKey) - { - inTangent = -outTangent; - } - else if (!pRightKey) - { - outTangent = -inTangent; - } - else - { - const float deltaTime = pRightKey->m_time - pLeftKey->m_time; - const float ratio = (key.m_time - pLeftKey->m_time) / deltaTime; - - Vec2 smoothedTangent = Vec2::CreateLerp(-inTangent, outTangent, applyInverseSegmentLengthFactor ? ratio : 0.5f); - inTangent = -smoothedTangent; - outTangent = smoothedTangent; - } - - if (pLeftKey) - { - float leftSegmentTime = key.m_time - pLeftKey->m_time; - float inFactor = (leftSegmentTime / -inTangent.x) / 3.0f; - inTangent *= inFactor; - } - if (pRightKey) - { - float rightSegmentTime = pRightKey->m_time - key.m_time; - float outFactor = (rightSegmentTime / outTangent.x) / 3.0f; - outTangent *= outFactor; - } - } - - Vec2 GetSmoothInTangent(SCurveEditorKey& key, Vec2 inTangent, Vec2 outTangent, SCurveEditorKey* pLeftKey, SCurveEditorKey* pRightKey, bool applyInverseSegmentLengthFactor) - { - SmoothTangents(key, inTangent, outTangent, pLeftKey, pRightKey, applyInverseSegmentLengthFactor); - return inTangent; - } - - Vec2 GetSmoothOutTangent(SCurveEditorKey& key, Vec2 inTangent, Vec2 outTangent, SCurveEditorKey* pLeftKey, SCurveEditorKey* pRightKey, bool applyInverseSegmentLengthFactor) - { - SmoothTangents(key, inTangent, outTangent, pLeftKey, pRightKey, applyInverseSegmentLengthFactor); - return outTangent; - } -} - -void showTooltip(const SCurveEditorKey& key, const QPoint& pos, QWidget* parent, QString tipOverride = QString()) -{ - if (!tipOverride.isEmpty()) - { - return QToolTip::showText(pos, tipOverride, parent); - } - - QString tip = QString().asprintf("%s <- [%5.2f, %5.2f] -> %s", - CCurveEditor::TangentTypeToString(key.m_inTangentType).toUtf8().data(), - key.m_time, key.m_time, - CCurveEditor::TangentTypeToString(key.m_outTangentType).toUtf8().data()); - - QToolTip::showText(pos, tip, parent); -} - -struct CCurveEditor::SSelectionHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - QPoint m_startPoint; - QRect m_rect; - bool m_bAdd; - - SSelectionHandler(CCurveEditor* pCurveEditor, bool bAdd) - : m_pCurveEditor(pCurveEditor) - , m_bAdd(bAdd) {} - - void mousePressEvent(QMouseEvent* pEvent) override - { - m_startPoint = pEvent->pos(); - m_rect = QRect(m_startPoint, m_startPoint + QPoint(1, 1)); - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - m_rect = QRect(m_startPoint, pEvent->pos() + QPoint(1, 1)); - } - - void mouseReleaseEvent([[maybe_unused]] QMouseEvent* pEvent) override - { - m_pCurveEditor->SelectInRect(m_rect); - } - - void paintOver(QPainter& painter) override - { - painter.save(); - QColor highlightColor = m_pCurveEditor->palette().color(QPalette::Highlight); - QColor highlightColorA = QColor(highlightColor.red(), highlightColor.green(), highlightColor.blue(), 128); - painter.setPen(QPen(highlightColor)); - painter.setBrush(QBrush(highlightColorA)); - painter.drawRect(QRectF(m_rect)); - painter.restore(); - } -}; - -struct CCurveEditor::SPanHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - QPoint m_startPoint; - Vec2 m_startTranslation; - - SPanHandler(CCurveEditor* pCurveEditor) - : m_pCurveEditor(pCurveEditor) - { - } - - void mousePressEvent(QMouseEvent* pEvent) override - { - if (m_pCurveEditor->m_optOutFlags & EOptOutZoomingAndPanning) - { - return; - } - m_startPoint = QPoint(int(pEvent->x()), int(pEvent->y())); - m_startTranslation = m_pCurveEditor->m_translation; - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - if (m_pCurveEditor->m_optOutFlags & EOptOutZoomingAndPanning) - { - return; - } - const Vec2 windowSize((float)m_pCurveEditor->size().width(), (float)m_pCurveEditor->size().height()); - - const int pixelDeltaX = pEvent->x() - m_startPoint.x(); - const int pixelDeltaY = pEvent->y() - m_startPoint.y(); - - float deltaX = float(pixelDeltaX) / (windowSize.x); - float deltaY = float(pixelDeltaY) / (windowSize.y); - - if (m_pCurveEditor->IsTimeRangeEnforced()) - { - deltaX = 0; - } - - const Vec2 delta(deltaX, deltaY); - m_pCurveEditor->m_translation = m_startTranslation + delta; - m_pCurveEditor->update(); - } -}; - -struct CCurveEditor::SZoomHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - QPoint m_lastPoint; - - SZoomHandler(CCurveEditor* pCurveEditor) - : m_pCurveEditor(pCurveEditor) - { - } - - void mousePressEvent(QMouseEvent* pEvent) override - { - if (m_pCurveEditor->m_optOutFlags & EOptOutZoomingAndPanning) - { - return; - } - m_lastPoint = QPoint(int(pEvent->x()), int(pEvent->y())); - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - if (m_pCurveEditor->m_optOutFlags & EOptOutZoomingAndPanning) - { - return; - } - const Vec2 windowSize((float)m_pCurveEditor->size().width(), (float)m_pCurveEditor->size().height()); - - const int pixelDeltaX = pEvent->x() - m_lastPoint.x(); - const int pixelDeltaY = pEvent->y() - m_lastPoint.y(); - - m_lastPoint = QPoint(int(pEvent->x()), int(pEvent->y())); - - m_pCurveEditor->m_zoom.x *= pow(1.2f, (float)pixelDeltaX * 0.03f); - m_pCurveEditor->m_zoom.y *= pow(1.2f, (float)pixelDeltaY * 0.03f); - - m_pCurveEditor->m_zoom.x = clamp_tpl(m_pCurveEditor->m_zoom.x, kMinZoom, kMaxZoom); - m_pCurveEditor->m_zoom.y = clamp_tpl(m_pCurveEditor->m_zoom.y, kMinZoom, kMaxZoom); - - m_pCurveEditor->update(); - } -}; - -struct CCurveEditor::SScrubHandler - : SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - float m_startThumbPosition; - QPoint m_startPoint; - - SScrubHandler(CCurveEditor* pCurveEditor) - : m_pCurveEditor(pCurveEditor) - { - } - - void mousePressEvent(QMouseEvent* ev) override - { - QPoint point = QPoint(ev->pos().x(), ev->pos().y()); - - const Vec2 pointInCurveSpace = TransformPointFromScreen(m_pCurveEditor->m_zoom, m_pCurveEditor->m_translation, m_pCurveEditor->GetCurveArea(), PointToVec2(point)); - - m_pCurveEditor->m_time = pointInCurveSpace.x; - m_startThumbPosition = m_pCurveEditor->m_time; - m_startPoint = point; - - m_pCurveEditor->SignalScrub(); - } - - void Apply(QMouseEvent* ev, [[maybe_unused]] bool continuous) - { - QPoint point = QPoint(ev->pos().x(), ev->pos().y()); - - bool shift = ev->modifiers().testFlag(Qt::ShiftModifier); - bool control = ev->modifiers().testFlag(Qt::ControlModifier); - - const float deltaX = (float)(point.x() - m_startPoint.x()); - const float width = (float)m_pCurveEditor->size().width(); - float delta = float(deltaX) / (width * m_pCurveEditor->m_zoom.x); - - if (shift) - { - delta *= 0.01f; - } - - if (control) - { - delta *= 0.1f; - } - - m_pCurveEditor->m_time = m_startThumbPosition + delta; - m_pCurveEditor->SignalScrub(); - } - - void mouseMoveEvent(QMouseEvent* ev) override - { - Apply(ev, true); - } - - void mouseReleaseEvent(QMouseEvent* ev) override - { - Apply(ev, false); - } -}; - -struct CCurveEditor::SMoveKeyHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - bool m_bCycleSelection; - Vec2 m_startPoint; - std::vector m_keyPositions; - bool m_clamp; - QRectF m_range; - - SMoveKeyHandler(CCurveEditor* pCurveEditor, bool bCycleSelection, QRectF* clampRange = nullptr) - : m_pCurveEditor(pCurveEditor) - , m_bCycleSelection(bCycleSelection) - , m_startPoint(0.0f, 0.0f) - , m_clamp(clampRange ? true : false) - , m_range(clampRange ? *clampRange : QRectF()) - {} - - void mousePressEvent(QMouseEvent* pEvent) override - { - const QPoint currentPos = pEvent->pos(); - m_startPoint = TransformPointFromScreen(m_pCurveEditor->m_zoom, - m_pCurveEditor->m_translation, m_pCurveEditor->GetCurveArea(), PointToVec2(currentPos)); - StoreKeyPositions(); - m_pCurveEditor->SignalKeyMoveStarted(); - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - RestoreKeyPositions(); - const QPoint currentPos = pEvent->pos(); - Vec2 transformedPos = TransformPointFromScreen(m_pCurveEditor->m_zoom, - m_pCurveEditor->m_translation, m_pCurveEditor->GetCurveArea(), PointToVec2(currentPos)); - - const Vec2 offset = transformedPos - m_startPoint; - - SCurveEditorContent* pContent = m_pCurveEditor->m_pContent; - for (auto curveIter = pContent->m_curves.begin(); curveIter != pContent->m_curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - - for (auto iter = curve.m_keys.begin(); iter != curve.m_keys.end(); ++iter) - { - if (iter->m_bSelected) - { - iter->m_time += offset.x; - iter->m_value += offset.y; - if (m_clamp) - { - iter->m_time = clamp_tpl(iter->m_time, (float)m_range.left(), (float)m_range.right()); - iter->m_value = clamp_tpl(iter->m_value, (float)m_range.bottom(), (float)m_range.top()); - } - iter->m_bModified = true; - } - } - - m_pCurveEditor->SortKeys(curve); - } - - m_pCurveEditor->SignalKeyMoved(); - } - - void focusOutEvent([[maybe_unused]] QFocusEvent* pEvent) override - { - RestoreKeyPositions(); - } - - void mouseReleaseEvent([[maybe_unused]] QMouseEvent* pEvent) override - { - m_pCurveEditor->ContentChanged(); - } - - void StoreKeyPositions() - { - SCurveEditorContent* pContent = m_pCurveEditor->m_pContent; - for (auto curveIter = pContent->m_curves.begin(); curveIter != pContent->m_curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - for (auto iter = curve.m_keys.begin(); iter != curve.m_keys.end(); ++iter) - { - if (iter->m_bSelected) - { - m_keyPositions.push_back(Vec2(iter->m_time, iter->m_value)); - } - } - } - } - - void RestoreKeyPositions() - { - SCurveEditorContent* pContent = m_pCurveEditor->m_pContent; - auto posIter = m_keyPositions.begin(); - for (auto curveIter = pContent->m_curves.begin(); curveIter != pContent->m_curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - for (auto iter = curve.m_keys.begin(); iter != curve.m_keys.end(); ++iter) - { - if (iter->m_bSelected) - { - iter->m_time = posIter->x; - iter->m_value = (posIter++)->y; - } - } - } - } -}; - -struct CCurveEditor::SRotateTangentHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - CCurveEditorTangentControl* m_pSelectedTangent; - Vec2 m_StartPoint; - Vec2 m_InitialInTangent; - SCurveEditorKey::ETangentType m_InitialInTangentType; - Vec2 m_InitialOutTangent; - SCurveEditorKey::ETangentType m_InitialOutTangentType; - - SRotateTangentHandler(CCurveEditor* pCurveEditor, CCurveEditorTangentControl* pTangentControl) - : m_pCurveEditor(pCurveEditor) - , m_pSelectedTangent(pTangentControl) - , m_StartPoint(0.0f, 0.0f) - {} - - void mousePressEvent(QMouseEvent* pEvent) override - { - const QPoint currentPos = pEvent->pos(); - m_StartPoint = m_pCurveEditor->TransformFromScreenCoordinates(PointToVec2(currentPos)); - - StoreTangents(); - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - const QPoint currentPos = pEvent->pos(); - const Vec2 transformedPos = m_pCurveEditor->TransformFromScreenCoordinates(PointToVec2(currentPos)); - const Vec2 offset = transformedPos - m_StartPoint; - - SCurveEditorKey& key = m_pSelectedTangent->GetControl().GetKey(); - Vec2 keyPos(key.m_time, key.m_value); - - bool isInTangent = m_pSelectedTangent->GetTangentDirection() == ETangent_In; - bool shouldTangentsBePaired = key.m_inTangentType == key.m_outTangentType - && (key.m_inTangentType == SCurveEditorKey::eTangentType_Standard - || key.m_inTangentType == SCurveEditorKey::eTangentType_Smooth - || key.m_inTangentType == SCurveEditorKey::eTangentType_Flat); - - float tangentEpsilon = 1e-6f; - - // strictly left or right of key - have a fairly large epsilon to avoid weird floating point innaccuracies in editor - bool leftOfKey = (transformedPos.x - keyPos.x) < -tangentEpsilon; - bool rightOfKey = (transformedPos.x - keyPos.x) > tangentEpsilon; - bool tangentVertical = !(leftOfKey || rightOfKey); - - if ((isInTangent && leftOfKey) || (shouldTangentsBePaired && !tangentVertical)) - { - Vec2 newInTangent = transformedPos - keyPos; - if (rightOfKey) - { - // mirror tangent - newInTangent *= -1; - } - float scale = key.m_inTangent.x / newInTangent.x; - newInTangent *= scale; - key.m_inTangent = newInTangent; - - key.m_inTangentType = shouldTangentsBePaired ? SCurveEditorKey::eTangentType_Standard : key.m_inTangentType; - } - - if ((!isInTangent && rightOfKey) || (shouldTangentsBePaired && !tangentVertical)) - { - Vec2 newOutTangent = transformedPos - keyPos; - if (leftOfKey) - { - // mirror tangent - newOutTangent *= -1; - } - float scale = key.m_outTangent.x / newOutTangent.x; - newOutTangent *= scale; - key.m_outTangent = newOutTangent; - - key.m_outTangentType = shouldTangentsBePaired ? SCurveEditorKey::eTangentType_Standard : key.m_outTangentType; - } - } - - void focusOutEvent([[maybe_unused]] QFocusEvent* pEvent) override - { - RestoreTangents(); - } - - void mouseReleaseEvent([[maybe_unused]] QMouseEvent* pEvent) override - { - m_pCurveEditor->ContentChanged(); - } - - void StoreTangents() - { - SCurveEditorKey& key = m_pSelectedTangent->GetControl().GetKey(); - - m_InitialInTangent = key.m_inTangent; - m_InitialInTangentType = key.m_inTangentType; - - m_InitialOutTangent = key.m_outTangent; - m_InitialOutTangentType = key.m_outTangentType; - } - - void RestoreTangents() - { - SCurveEditorKey& key = m_pSelectedTangent->GetControl().GetKey(); - - key.m_inTangent = m_InitialInTangent; - key.m_inTangentType = m_InitialInTangentType; - - key.m_outTangent = m_InitialOutTangent; - key.m_outTangentType = m_InitialOutTangentType; - } -}; - -CCurveEditor::CCurveEditor(QWidget* parent) - : QWidget(parent) - , m_pContent(nullptr) - , m_pMouseHandler(nullptr) - , m_curveType(eCECT_Bezier) - , m_bWeighted(false) - , m_bHandlesVisible(true) - , m_bRulerVisible(true) - , m_bTimeSliderVisible(true) - , m_time(0.0f) - , m_zoom(0.5f, 0.5f) - , m_translation(0.5f, 0.5f) - , m_timeRange(0, 1) - , m_timeRangeEnforced(false) - , m_valueRange(0, 1) - , m_optOutFlags(0) -{ - setMouseTracking(true); - //EnforceTimeRange(0.0f, 1.0f); - SetTimeRange(0, 1); - SetValueRange(0, 1); - ZoomToTimeRange(-0.1f, 1.1f); - ZoomToValueRange(-0.1f, 1.1f); - SetRulerVisible(true); - QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - setSizePolicy(sizePolicy); -} - -CCurveEditor::~CCurveEditor() -{ -} - -void CCurveEditor::SetContent(SCurveEditorContent* pContent) -{ - m_pContent = pContent; - - ContentChanged(); - - update(); -} - -void CCurveEditor::SetTime(const float time) -{ - m_time = time; - update(); -} - -void CCurveEditor::SetTimeRange(const float start, const float end) -{ - SetTimeRange(start, end, false); -} - -void CCurveEditor::EnforceTimeRange(const float start, const float end) -{ - SetTimeRange(start, end, true); - ZoomToTimeRange(start, end); -} - -bool CCurveEditor::IsTimeRangeEnforced() const -{ - return m_timeRangeEnforced; -} - -void CCurveEditor::SetTimeRange(const float start, const float end, bool enforce) -{ - if (start <= end) - { - m_timeRangeEnforced = enforce; - m_timeRange = Range(start, end); - update(); - } -} - -void CCurveEditor::SetValueRange(const float min, const float max) -{ - if (min <= max) - { - m_valueRange = Range(min, max); - update(); - } -} - -void CCurveEditor::ZoomToTimeRange(const float start, const float end) -{ - if (start < end) - { - m_zoom.x = 1.0f / (end - start); - m_translation.x = start / (start - end); - } -} - -void CCurveEditor::ZoomToValueRange(const float min, const float max) -{ - if (min < max) - { - m_zoom.y = 1.0f / (max - min); - m_translation.y = max / (max - min); - } -} - -void CCurveEditor::paintEvent([[maybe_unused]] QPaintEvent* pEvent) -{ - QPainter painter(this); - painter.setRenderHint(QPainter::Antialiasing); - painter.translate(0.5f, 0.5f); - - const QPalette& palette = this->palette(); - - auto transformFunc = [&](Vec2 point) - { - return TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), point); - }; - - auto invTransformFunc = [&](Vec2 screenPoint) - { - return TransformPointFromScreen(m_zoom, m_translation, GetCurveArea(), screenPoint); - }; - - const QColor rangeHighlightColor = CurveEditorHelpers::LerpColor(palette.color(QPalette::WindowText), palette.color(QPalette::Window), 0.95f); - const QRectF rangesRect(Vec2ToPoint(transformFunc(Vec2(m_timeRange.start, m_valueRange.start))), Vec2ToPoint(transformFunc(Vec2(m_timeRange.end, m_valueRange.end)))); - painter.setPen(QPen(Qt::NoPen)); - if ((m_optOutFlags & EOptOutBackground)) - { - painter.setBrush(Qt::transparent); - } - else - { - painter.setBrush(rangeHighlightColor); - } - - if ((m_optOutFlags & EOptOutRuler)) - { - painter.drawRect(rangesRect); - } - else - { - painter.drawRect(rect()); - } - - if (m_pContent) - { - const QPen extrapolatedCurvePen = QPen(palette.color(QPalette::Highlight)); - - TCurveEditorCurves& curves = m_pContent->m_curves; - for (auto curveIter = curves.begin(); curveIter != curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - QColor penColor = QColor(curve.m_color.r, curve.m_color.g, curve.m_color.b, curve.m_color.a); - - if (!(m_optOutFlags & EOptOutCustomPenColor) && m_penColor.isValid()) - { - penColor = m_penColor; - } - - painter.setBrush(QBrush(Qt::NoBrush)); - const QPen curvePen = QPen(penColor, 2); - const QPen narrowCurvePen = QPen(penColor); - if (!(m_optOutFlags & eOptOutDashedPath)) - { - const QPainterPath extrapolatedPath = CreateExtrapolatedPathFromCurve(curve, transformFunc, aznumeric_cast(width())); - painter.setPen(narrowCurvePen); - painter.drawPath(extrapolatedPath); - } - - const QPainterPath discontinuinityPath = CreateDiscontinuinityPathFromCurve(curve, m_curveType, transformFunc); - painter.setPen(narrowCurvePen); - painter.drawPath(discontinuinityPath); - - if (curve.m_keys.size() > 0) - { - UpdateTangents(); - const QPainterPath path = CreatePathFromCurve(curve, m_curveType, transformFunc); - painter.setPen(curvePen); - painter.drawPath(path); - } - } - } - - if (!(m_optOutFlags & EOptOutSelectionKey)) - { - if ((m_optOutFlags & EOptOutKeyIcon)) - { - for (CCurveEditorControl* pControlKey : m_pControlKeys) - { - pControlKey->Paint(painter, palette, !(m_optOutFlags & EOptOutSelectionInOutTangent)); - } - } - else - { - for (CCurveEditorControl* pControlKey : m_pControlKeys) - { - pControlKey->PaintIcon(painter, palette, !(m_optOutFlags & EOptOutSelectionInOutTangent)); - } - } - } - - if (m_pMouseHandler) - { - m_pMouseHandler->paintOver(painter); - } - if (!(m_optOutFlags & EOptOutRuler)) - { - DrawingPrimitives::SRulerOptions rulerOptions; - rulerOptions.m_rect = QRect(0, -1, size().width(), kRulerHeight + 2); - rulerOptions.m_visibleRange = Range(-m_translation.x / m_zoom.x, (1.0f - m_translation.x) / m_zoom.x); - rulerOptions.m_rulerRange = rulerOptions.m_visibleRange; - rulerOptions.m_markHeight = kRulerMarkHeight; - rulerOptions.m_shadowSize = kRulerShadowHeight; - rulerOptions.m_textXOffset = kTextXOffset; - rulerOptions.m_textYOffset = kTextYOffset; - - int rulerPrecision; - DrawingPrimitives::DrawRuler(painter, palette, rulerOptions, &rulerPrecision); - - if (m_pContent && isEnabled() && !(m_optOutFlags & EOptOutTimeSlider)) - { - DrawingPrimitives::STimeSliderOptions timeSliderOptions; - timeSliderOptions.m_rect = rect(); - timeSliderOptions.m_precision = rulerPrecision; - timeSliderOptions.m_position = aznumeric_cast(transformFunc(Vec2(m_time, 0.0f)).x); - timeSliderOptions.m_time = m_time; - timeSliderOptions.m_bHasFocus = hasFocus(); - DrawingPrimitives::DrawTimeSlider(painter, palette, timeSliderOptions); - } - } -} - -void CCurveEditor::mousePressEvent(QMouseEvent* pEvent) -{ - if (m_optOutFlags & EOptOutControls) - { - return QWidget::mousePressEvent(pEvent); - } - setFocus(); - - if (pEvent->button() == Qt::LeftButton) - { - LeftButtonMousePressEvent(pEvent); - } - else if (pEvent->button() == Qt::MiddleButton) - { - MiddleButtonMousePressEvent(pEvent); - } - else if (pEvent->button() == Qt::RightButton) - { - RightButtonMousePressEvent(pEvent); - } -} - -void CCurveEditor::mouseDoubleClickEvent(QMouseEvent* pEvent) -{ - if (m_optOutFlags & EOptOutControls) - { - return QWidget::mouseDoubleClickEvent(pEvent); - } - if (pEvent->button() == Qt::LeftButton) - { - auto curveHitPair = HitDetectCurve(pEvent->pos()); - if (curveHitPair.first) - { - if (AddPointToCurve(curveHitPair.second, curveHitPair.first)) - { - setCursor(QCursor(Qt::SizeAllCursor)); - } - } - } -} - -void CCurveEditor::LeftButtonMousePressEvent(QMouseEvent* pEvent) -{ - const bool bCtrlPressed = (pEvent->modifiers() & Qt::CTRL) != 0; - const bool bAltPressed = (pEvent->modifiers() & Qt::ALT) != 0; - - if (pEvent->y() < kRulerHeight && !(m_optOutFlags & EOptOutRuler)) - { - m_pMouseHandler.reset(new SScrubHandler(this)); - m_pMouseHandler->mousePressEvent(pEvent); - } - else - { - if (bCtrlPressed) - { - auto curveHitPair = HitDetectCurve(pEvent->pos()); - if (curveHitPair.first) - { - if (AddPointToCurve(curveHitPair.second, curveHitPair.first)) - { - setCursor(QCursor(Qt::SizeAllCursor)); - } - } - } - else if (bAltPressed) - { - auto pCurveKey = HitDetectKey(pEvent->pos()); - if (pCurveKey) - { - pCurveKey->MarkKeyForRemoval(); - ContentChanged(); - } - } - else - { - auto pTangentKey = HitDetectTangent(pEvent->pos()); - if (pTangentKey) - { - SelectTangent(pTangentKey); - - m_pMouseHandler.reset(new SRotateTangentHandler(this, pTangentKey)); - } - else - { - auto pCurveKey = HitDetectKey(pEvent->pos()); - if (pCurveKey) - { - SelectKey(pCurveKey, false); - - QRectF range; - range.setLeft(m_timeRange.start); - range.setRight(m_timeRange.end); - range.setBottom(m_valueRange.start); - range.setTop(m_valueRange.end); - - m_pMouseHandler.reset(new SMoveKeyHandler(this, false, - m_timeRangeEnforced ? &range : nullptr)); - } - else - { - m_pMouseHandler.reset(new SSelectionHandler(this, false)); - } - } - - m_pMouseHandler->mousePressEvent(pEvent); - } - } - - update(); -} - -void CCurveEditor::MiddleButtonMousePressEvent(QMouseEvent* pEvent) -{ - const bool bShiftPressed = (pEvent->modifiers() & Qt::SHIFT) != 0; - - if (!bShiftPressed) - { - m_pMouseHandler.reset(new SPanHandler(this)); - } - else - { - m_pMouseHandler.reset(new SZoomHandler(this)); - } - - m_pMouseHandler->mousePressEvent(pEvent); - update(); -} - -void CCurveEditor::RightButtonMousePressEvent(QMouseEvent* pEvent) -{ - CCurveEditorControl* pCurveKey = HitDetectKey(pEvent->pos()); - if (pCurveKey) - { - SelectKey(pCurveKey, false); - update(); //Repaint so that we see that the key is selected - - QMenu* pMenu = new QMenu(this); - PopulateControlContextMenu(pMenu); - pMenu->popup(pEvent->globalPos()); - } - else - { - return QWidget::mousePressEvent(pEvent); - } -} - -void CCurveEditor::mouseMoveEvent(QMouseEvent* pEvent) -{ - if (m_optOutFlags & EOptOutControls) - { - return QWidget::mouseMoveEvent(pEvent); - } - const CCurveEditorControl* control = HitDetectKey(pEvent->pos()); - if (control) - { - if (!(m_optOutFlags & EOptOutDefaultTooltip)) - { - showTooltip(control->GetKey(), pEvent->globalPos(), this, control->GetToolTip()); - } - setCursor(QCursor(Qt::SizeAllCursor)); - } - else - { - if (!(m_optOutFlags & EOptOutDefaultTooltip)) - { - QToolTip::hideText(); - } - setCursor(QCursor()); - } - - if (m_pMouseHandler) - { - m_pMouseHandler->mouseMoveEvent(pEvent); - } - - update(); -} - -void CCurveEditor::mouseReleaseEvent(QMouseEvent* pEvent) -{ - if (m_optOutFlags & EOptOutControls) - { - return QWidget::mouseReleaseEvent(pEvent); - } - if (m_pMouseHandler) - { - m_pMouseHandler->mouseReleaseEvent(pEvent); - m_pMouseHandler.reset(); - update(); - } -} - -void CCurveEditor::focusOutEvent(QFocusEvent* pEvent) -{ - if (m_optOutFlags & EOptOutControls) - { - return focusOutEvent(pEvent); - } - if (m_pMouseHandler) - { - m_pMouseHandler->focusOutEvent(pEvent); - m_pMouseHandler.reset(); - update(); - } -} - -void CCurveEditor::wheelEvent(QWheelEvent* pEvent) -{ - if (m_optOutFlags & EOptOutControls || m_optOutFlags & EOptOutZoomingAndPanning) - { - return QWidget::wheelEvent(pEvent); - } - Vec2 windowSize((float)size().width(), (float)size().height()); - windowSize.y = (windowSize.y > 0.0f) ? windowSize.y : 1.0f; - - const QRect curveArea = GetCurveArea(); - const float mouseXNormalized = (float)(pEvent->position().x() - curveArea.left()) / (float)curveArea.width(); - const float mouseYNormalized = (float)(pEvent->position().y() - curveArea.top()) / (float)curveArea.height(); - - const float pivotX = (mouseXNormalized - m_translation.x) / m_zoom.x; - const float pivotY = (mouseYNormalized - m_translation.y) / m_zoom.y; - - float zoomFactor = pow(1.2f, (float)pEvent->angleDelta().y() * 0.01f); - - if (!m_timeRangeEnforced) - { - m_zoom.x *= zoomFactor; - } - m_zoom.y *= zoomFactor; - - m_zoom.x = clamp_tpl(m_zoom.x, kMinZoom, kMaxZoom); - m_zoom.y = clamp_tpl(m_zoom.y, kMinZoom, kMaxZoom); - - // Adjust translation so pivot point stays at same x and y position on screen - m_translation.x += ((mouseXNormalized - m_translation.x) / m_zoom.x - pivotX) * m_zoom.x; - m_translation.y += ((mouseYNormalized - m_translation.y) / m_zoom.y - pivotY) * m_zoom.y; - - update(); -} - -void CCurveEditor::keyPressEvent(QKeyEvent* pEvent) -{ - if (m_optOutFlags & EOptOutControls) - { - return QWidget::keyPressEvent(pEvent); - } - if (!m_pContent) - { - return; - } - - QKeySequence key(pEvent->key()); - - if (key == QKeySequence(Qt::Key_Delete)) - { - OnDeleteSelectedKeys(); - } - - update(); -} - -void CCurveEditor::SetCurveType(ECurveEditorCurveType curveType) -{ - m_curveType = curveType; -} - -void CCurveEditor::SetHandlesVisible(bool bVisible) -{ - m_bHandlesVisible = bVisible; - update(); -} - -void CCurveEditor::SetRulerVisible(bool bVisible) -{ - m_bRulerVisible = bVisible; - update(); -} - -void CCurveEditor::SetTimeSliderVisible(bool bVisible) -{ - m_bTimeSliderVisible = bVisible; - update(); -} - -std::pair CCurveEditor::HitDetectCurve(const QPoint point) -{ - if (!m_pContent) - { - return std::make_pair(nullptr, Vec2(ZERO)); - } - - SCurveEditorCurve* pNearestCurve = nullptr; - Vec2 closestPoint = Vec2(ZERO); - - float nearestDistance = std::numeric_limits::max(); - for (auto iter = m_pContent->m_curves.rbegin(); iter != m_pContent->m_curves.rend(); ++iter) - { - SCurveEditorCurve& curve = *iter; - const Vec2 closestPointOnCurve = ClosestPointOnCurve(PointToVec2(point), curve, m_curveType); - - const float distance = (PointToVec2(point) - closestPointOnCurve).GetLength(); - if (distance < nearestDistance) - { - nearestDistance = distance; - pNearestCurve = &curve; - closestPoint = closestPointOnCurve; - } - } - - if (nearestDistance <= kHitDistance) - { - return std::make_pair(pNearestCurve, TransformPointFromScreen(m_zoom, m_translation, GetCurveArea(), closestPoint)); - } - - return std::make_pair(nullptr, Vec2(ZERO)); -} - -CCurveEditorControl* CCurveEditor::GetSelectedCurveKey() -{ - for (CCurveEditorControl* pControlKey : m_pControlKeys) - { - if (pControlKey->IsSelected()) - { - return pControlKey; - } - } - return nullptr; -} - - -CCurveEditorControl* CCurveEditor::HitDetectKey(const QPoint point) -{ - for (CCurveEditorControl* pControlKey : m_pControlKeys) - { - if (pControlKey->IsMouseWithinControl(point)) - { - return pControlKey; - } - } - - return NULL; -} - -CCurveEditorTangentControl* CCurveEditor::HitDetectTangent(const QPoint point) -{ - if (m_optOutFlags & EOptOutSelectionInOutTangent) - { - return NULL; - } - - for (CCurveEditorControl* pControlKey : m_pControlKeys) - { - if (pControlKey->GetInTangent().IsMouseWithinControl(point)) - { - return &pControlKey->GetInTangent(); - } - else if (pControlKey->GetOutTangent().IsMouseWithinControl(point)) - { - return &pControlKey->GetOutTangent(); - } - } - - return NULL; -} - -void CCurveEditor::SelectKey(CCurveEditorControl* pControlToSelect, bool addToExistingSelection) -{ - bool wasSelected = pControlToSelect->IsSelected(); - - if (!wasSelected) - { - if (!addToExistingSelection) - { - for (CCurveEditorControl* pControlKey : m_pControlKeys) - { - pControlKey->SetSelected(false); - } - } - pControlToSelect->SetSelected(true); - //update key selection style - updateCurveKeyShapeColor(); - emit SignalKeySelected(pControlToSelect); - } -} - -void CCurveEditor::SelectTangent(CCurveEditorTangentControl* pTangentToSelect) -{ - bool wasSelected = pTangentToSelect->IsSelected(); - if (!wasSelected) - { - for (CCurveEditorControl* pControlKey : m_pControlKeys) - { - pControlKey->SetSelected(false); - pControlKey->GetInTangent().SetSelected(false); - pControlKey->GetOutTangent().SetSelected(false); - } - pTangentToSelect->GetControl().SetSelected(true); - pTangentToSelect->SetSelected(true); - } -} - -void CCurveEditor::SelectInRect(const QRect& rect) -{ - if (!m_pContent || (m_optOutFlags & EOptOutSelectionKey)) - { - return; - } - - ForEachKey(*m_pContent, [&]([[maybe_unused]] SCurveEditorCurve& curve, SCurveEditorKey& key) - { - const Vec2 screenPoint = TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), Vec2(key.m_time, key.m_value)); - key.m_bSelected = rect.contains((int)screenPoint.x, (int)screenPoint.y); - }); - - update(); -} - -// Input and output are in screen space -Vec2 CCurveEditor::ClosestPointOnCurve(const Vec2 point, const SCurveEditorCurve& curve, const ECurveEditorCurveType curveType) -{ - auto transformFunc = [&](Vec2 point) - { - return TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), point); - }; - - if (curve.m_keys.size() == 0) - { - const Vec2 pointOnCurve = transformFunc(Vec2(0.0f, curve.m_defaultValue)); - return Vec2(point.x, pointOnCurve.y); - } - - Vec2 closestPoint; - float minDistance = std::numeric_limits::max(); - - const Vec2 startKeyTransformed = transformFunc(Vec2(curve.m_keys.front().m_time, curve.m_keys.front().m_value)); - if (point.x < startKeyTransformed.x) - { - const float distanceToCurve = std::abs(point.y - startKeyTransformed.y); - if (distanceToCurve < minDistance) - { - closestPoint = Vec2(point.x, startKeyTransformed.y); - minDistance = distanceToCurve; - } - } - - const Vec2 endKeyTransformed = transformFunc(Vec2(curve.m_keys.back().m_time, curve.m_keys.back().m_value)); - if (point.x > endKeyTransformed.x) - { - const float distanceToCurve = std::abs(point.y - endKeyTransformed.y); - if (distanceToCurve < minDistance) - { - closestPoint = Vec2(point.x, endKeyTransformed.y); - minDistance = distanceToCurve; - } - } - - int numCustomKeys = curve.m_customInterpolator ? curve.m_customInterpolator->GetKeyCount() : 0; - if (numCustomKeys > 1 - && transformFunc(Vec2(curve.m_customInterpolator->GetKeyTime(0), 0)).x <= point.x - && transformFunc(Vec2(curve.m_customInterpolator->GetKeyTime(numCustomKeys - 1), 0)).x >= point.x) - { - const int sampleCount = 5; - for (int sample = 0; sample < sampleCount; sample++) - { - float value; - float offset = (float)sample - floorf((float)sampleCount / 2.0f); - float t = TransformPointFromScreen(m_zoom, m_translation, GetCurveArea(), Vec2(point.x + offset, point.y)).x; - curve.m_customInterpolator->InterpolateFloat(t, value); - value = transformFunc(Vec2(0, value)).y; - const Vec2 closestOnSegment = Vec2(point.x, value); - const float distanceToSegment = (closestOnSegment - point).GetLength(); - if (distanceToSegment < minDistance) - { - closestPoint = closestOnSegment; - minDistance = distanceToSegment; - } - } - } - else - { - const auto endIter = curve.m_keys.end() - 1; - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - if (curveType == eCECT_Bezier) - { - const SCurveEditorKey* pKeyLeftOfSegment = (iter != curve.m_keys.begin()) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pKeyRightOfSegment = (iter != (curve.m_keys.end() - 2)) ? &*(iter + 2) : nullptr; - - const SCurveEditorKey segmentStartKey = ApplyOutTangentFlags(*iter, pKeyLeftOfSegment, *(iter + 1)); - const SCurveEditorKey segmentEndKey = ApplyInTangentFlags(*(iter + 1), *iter, pKeyRightOfSegment); - - const Vec2 p0 = transformFunc(Vec2(segmentStartKey.m_time, segmentStartKey.m_value)); - const Vec2 p3 = transformFunc(Vec2(segmentEndKey.m_time, segmentEndKey.m_value)); - const Vec2 p1 = transformFunc(Vec2(0.0f, segmentStartKey.m_value + segmentStartKey.m_outTangent.y)); - const Vec2 p2 = transformFunc(Vec2(0.0f, segmentEndKey.m_value + segmentEndKey.m_inTangent.y)); - - const Vec2 closestOnSegment = ClosestPointOnBezierSegment(point, p0.x, p3.x, p0.y, p1.y, p2.y, p3.y); - const float distanceToSegment = (closestOnSegment - point).GetLength(); - if (distanceToSegment < minDistance) - { - closestPoint = closestOnSegment; - minDistance = distanceToSegment; - } - } - } - } - - return closestPoint; -} - -void CCurveEditor::ContentChanged() -{ - DeleteMarkedKeys(); - - while (!m_pControlKeys.isEmpty()) - { - delete m_pControlKeys.takeFirst(); - } - - for (auto iter = m_pContent->m_curves.begin(); iter != m_pContent->m_curves.end(); ++iter) - { - SCurveEditorCurve& curve = *iter; - for (size_t i = 0; i < curve.m_keys.size(); ++i) - { - SCurveEditorKey& key = curve.m_keys[i]; - key.m_bModified = false; - - CCurveEditorControl* pControlKey = new CCurveEditorControl(*this, curve, key); - pControlKey->SetSelected(key.m_bSelected); - - m_pControlKeys.append(pControlKey); - } - } - - UpdateTangents(); - - update(); - - SignalContentChanged(); -} - -void CCurveEditor::DeleteMarkedKeys() -{ - if (m_pContent) - { - bool changed = false; - // just delete the underlying key from the data model - the UI controls will be automatically updated to match the new model - for (auto iter = m_pContent->m_curves.begin(); iter != m_pContent->m_curves.end(); ++iter) - { - SCurveEditorCurve& curve = *iter; - for (auto keyIter = curve.m_keys.begin(); keyIter != curve.m_keys.end(); ) - { - if (keyIter->m_bDeleted) - { - keyIter = curve.m_keys.erase(keyIter); - changed = true; - } - else - { - ++keyIter; - } - } - } - } -} - -bool CCurveEditor::AddPointToCurve(const Vec2 point, SCurveEditorCurve* pCurve) -{ - assert(pCurve); - - // Makes sure that a new point can be only added at a safe distance - if (pCurve->m_customInterpolator) - { - const float w = aznumeric_cast(kPointRectExtent.x() * 2); - const float h = aznumeric_cast(kPointRectExtent.y() * 2); - const float minDist = w * w + h * h; - auto keys = pCurve->m_keys; - for (int i = 0; i < keys.size(); i++) - { - const SCurveEditorKey& k = keys[i]; - const Vec2 scrP0 = TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), Vec2(k.m_time, k.m_value)); - const Vec2 scrP1 = TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), point); - const float sqrDist = (scrP1 - scrP0).GetLength2(); - if (sqrDist <= minDist) - { - return false; - } - } - } - - SCurveEditorKey key; - key.m_bAdded = true; - key.m_time = point.x; - float yValue; - pCurve->m_customInterpolator->InterpolateFloat(point.x, yValue); - key.m_value = pCurve->m_customInterpolator ? yValue : point.y; - - // Set in/out tangents based on neighboring keys - const SCurveEditorKey* closestFromLeft = nullptr; - float closestTimeFromLeft = -std::numeric_limits::max(); - const SCurveEditorKey* closestFromRight = nullptr; - float closestTimeFromRight = std::numeric_limits::max(); - for (const SCurveEditorKey& k : pCurve->m_keys) - { - // Check left - if (k.m_time > closestTimeFromLeft && k.m_time < key.m_time) - { - closestTimeFromLeft = k.m_time; - closestFromLeft = &k; - } - - // Check right - if (k.m_time < closestTimeFromRight && k.m_time > key.m_time) - { - closestTimeFromRight = k.m_time; - closestFromRight = &k; - } - } - - if (closestFromLeft) - { - key.m_inTangentType = SCurveEditorKey::eTangentType_Bezier; - float value; - pCurve->m_customInterpolator->EvalInTangentFloat(key.m_time, value); - key.m_inTangent = Vec2(1.0f, value); - - } - - if (closestFromRight) - { - key.m_outTangentType = SCurveEditorKey::eTangentType_Bezier; - float value; - pCurve->m_customInterpolator->EvalOutTangentFloat(key.m_time, value); - key.m_outTangent = Vec2(1.0f, value); - } - - pCurve->m_keys.push_back(key); - - SortKeys(*pCurve); - - ContentChanged(); - return true; -} - -void CCurveEditor::SortKeys(SCurveEditorCurve& curve) -{ - std::stable_sort(curve.m_keys.begin(), curve.m_keys.end(), [](const SCurveEditorKey& a, const SCurveEditorKey& b) - { - return a.m_time < b.m_time; - }); -} - -QString CCurveEditor::TangentTypeToString(SCurveEditorKey::ETangentType type) -{ - switch (type) - { - case SCurveEditorKey::eTangentType_Standard: // Tangent freely rotates but will stay in sync with its pair if its pair is also standard - return tr("Standard"); - case SCurveEditorKey::eTangentType_Free: // Tangent is completely free moving (does not sync with its pair) - return tr("Free"); - case SCurveEditorKey::eTangentType_Step: // Step immediately to value of next control point in tangent direction - return tr("Step"); - case SCurveEditorKey::eTangentType_Linear: // Tangent always points to next control point - return tr("Linear"); - case SCurveEditorKey::eTangentType_Smooth: // Tangent is smoothed automatically based on direction/distance to neighboring controls - return tr("Smooth"); - case SCurveEditorKey::eTangentType_Flat: // Tangent is flattened (y = 0) - will still sync with its pair if both are flat - return tr("Flat"); - case SCurveEditorKey::eTangentType_Bezier: // Tangent is free moving and can be justified by user. Curve defined by Bz - return tr("Bezier"); - default: - break; - } - - return tr("Undefined tangent!"); -} - -void CCurveEditor::OnDeleteSelectedKeys() -{ - ForEachKey(*m_pContent, []([[maybe_unused]] SCurveEditorCurve& curve, SCurveEditorKey& key) - { - key.m_bDeleted = key.m_bDeleted || key.m_bSelected; - }); - - ContentChanged(); -} - -void CCurveEditor::OnSetSelectedKeysTangentStandard() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Standard); - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Standard); - - SmoothSelectedKeys(); -} - -void CCurveEditor::OnSetSelectedKeysTangentSmooth() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Smooth); - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Smooth); -} - -void CCurveEditor::OnSetSelectedKeysTangentFree() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Free); - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Free); -} - -void CCurveEditor::OnSetSelectedKeysTangentBezier() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Bezier); - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Bezier); -} - -void CCurveEditor::OnSetSelectedKeysTangentFlat() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Flat); - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Flat); -} - -void CCurveEditor::OnSetSelectedKeysTangentLinear() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Linear); - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Linear); -} - -void CCurveEditor::OnSetSelectedKeysInTangentFree() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Free); -} - -void CCurveEditor::OnSetSelectedKeysInTangentFlat() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Flat); -} - -void CCurveEditor::OnSetSelectedKeysInTangentLinear() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Linear); -} - -void CCurveEditor::OnSetSelectedKeysInTangentStep() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Step); -} - -void CCurveEditor::OnSetSelectedKeysInTangentBezier() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Bezier); -} - -void CCurveEditor::OnSetSelectedKeysOutTangentFree() -{ - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Free); -} - -void CCurveEditor::OnSetSelectedKeysOutTangentFlat() -{ - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Flat); -} - -void CCurveEditor::OnSetSelectedKeysOutTangentStep() -{ - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Step); -} - -void CCurveEditor::OnSetSelectedKeysOutTangentLinear() -{ - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Linear); -} - -void CCurveEditor::OnSetSelectedKeysOutTangentBezier() -{ - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Bezier); -} - -void CCurveEditor::OnFitCurvesHorizontally() -{ - if (m_timeRangeEnforced) - { - return; - } - if (m_pContent) - { - bool bAnyKeyFound = false; - float timeMin = std::numeric_limits::max(); - float timeMax = -std::numeric_limits::max(); - - TCurveEditorCurves& curves = m_pContent->m_curves; - for (auto curveIter = curves.begin(); curveIter != curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - if (curve.m_keys.size() > 0) - { - bAnyKeyFound = true; - timeMin = std::min(curve.m_keys.front().m_time, timeMin); - timeMax = std::max(curve.m_keys.back().m_time, timeMax); - } - } - - if (bAnyKeyFound) - { - ZoomToTimeRange(timeMin, timeMax); - - // Adjust zoom and translation depending on kFitMargin - const float pivot = (0.5f - m_translation.x) / m_zoom.x; - m_zoom.x /= 1.0f + 2.0f * (kFitMargin / GetCurveArea().width()); - m_translation.x += ((0.5f - m_translation.x) / m_zoom.x - pivot) * m_zoom.x; - - update(); - } - } -} - -void CCurveEditor::OnFitCurvesVertically() -{ - if (m_pContent) - { - bool bAnyKeyFound = false; - float valueMin = std::numeric_limits::max(); - float valueMax = -std::numeric_limits::max(); - - TCurveEditorCurves& curves = m_pContent->m_curves; - for (auto curveIter = curves.begin(); curveIter != curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - - if (m_curveType == eCECT_Bezier && curve.m_keys.size() > 0 && !curve.m_customInterpolator) - { - const auto endIter = curve.m_keys.end() - 1; - - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - bAnyKeyFound = true; - - const SCurveEditorKey* pKeyLeftOfSegment = (iter != curve.m_keys.begin()) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pKeyRightOfSegment = (iter != (curve.m_keys.end() - 2)) ? &*(iter + 2) : nullptr; - - const SCurveEditorKey segmentStartKey = ApplyOutTangentFlags(*iter, pKeyLeftOfSegment, *(iter + 1)); - const SCurveEditorKey segmentEndKey = ApplyInTangentFlags(*(iter + 1), *iter, pKeyRightOfSegment); - - const Range valueRange = GetBezierSegmentValueRange(segmentStartKey, segmentEndKey); - valueMin = std::min(valueMin, valueRange.start); - valueMax = std::max(valueMax, valueRange.end); - } - } - } - - if (bAnyKeyFound) - { - ZoomToValueRange(valueMin, valueMax); - - // Adjust zoom and translation depending on kFitMargin - const float pivot = (0.5f - m_translation.y) / m_zoom.y; - m_zoom.y /= 1.0f + 2.0f * (kFitMargin / GetCurveArea().height()); - m_translation.y += ((0.5f - m_translation.y) / m_zoom.y - pivot) * m_zoom.y; - - update(); - } - } -} - -void CCurveEditor::SetSelectedKeysTangentType(const ETangent tangent, const SCurveEditorKey::ETangentType type) -{ - if (m_pContent) - { - ForEachKey(*m_pContent, [&]([[maybe_unused]] SCurveEditorCurve& curve, SCurveEditorKey& key) - { - if (key.m_bSelected) - { - if (tangent == ETangent_In) - { - key.m_inTangentType = type; - } - else - { - key.m_outTangentType = type; - } - } - }); - - UpdateTangents(); - - update(); - - SignalContentChanged(); - } -} - -void CCurveEditor::SmoothSelectedKeys() -{ - if (m_pContent) - { - for (SCurveEditorCurve& curve : m_pContent->m_curves) - { - for (int keyIx = 0; keyIx < curve.m_keys.size(); ++keyIx) - { - SCurveEditorKey& key = curve.m_keys[keyIx]; - if (key.m_bSelected) - { - SCurveEditorKey* pLeftKey = (keyIx > 0) ? &curve.m_keys[keyIx - 1] : nullptr; - SCurveEditorKey* pRightKey = (keyIx + 1 < curve.m_keys.size()) ? &curve.m_keys[keyIx + 1] : nullptr; - SmoothTangents(key, key.m_inTangent, key.m_outTangent, pLeftKey, pRightKey, false); - } - } - } - - UpdateTangents(); - - update(); - } -} - -void CCurveEditor::UpdateTangents() -{ - for (SCurveEditorCurve& curve : m_pContent->m_curves) - { - for (int keyIx = 0; keyIx < curve.m_keys.size(); ++keyIx) - { - SCurveEditorKey& key = curve.m_keys[keyIx]; - - if (key.m_bAdded) - { - if (curve.m_keys.size() == 1) - { - return; - } - if (keyIx == 0) - { - SCurveEditorKey& nextKey = curve.m_keys[keyIx + 1]; - key.m_outTangent = Vec2(nextKey.m_time - key.m_time, nextKey.m_value - key.m_value) / 3.0f; - key.m_inTangent = -key.m_outTangent; - } - else if (keyIx + 1 == curve.m_keys.size()) - { - SCurveEditorKey& prevKey = curve.m_keys[keyIx - 1]; - key.m_inTangent = Vec2(prevKey.m_time - key.m_time, prevKey.m_value - key.m_value) / 3.0f; - key.m_outTangent = -key.m_outTangent; - } - key.m_bAdded = false; - } - if (keyIx > 0) - { - SCurveEditorKey& prevKey = curve.m_keys[keyIx - 1]; - - switch (key.m_inTangentType) - { - case SCurveEditorKey::eTangentType_Smooth: - { - if (keyIx + 1 >= curve.m_keys.size()) - { - key.m_inTangent = Vec2(prevKey.m_time - key.m_time, prevKey.m_value - key.m_value) / 3.0f; - break; - } - SCurveEditorKey& nextKey = curve.m_keys[keyIx + 1]; - const float deltaTime = nextKey.m_time - prevKey.m_time; - if (deltaTime > 0.0f) - { - Vec2 normalizedIn = Vec2(prevKey.m_time - key.m_time, prevKey.m_value - key.m_value); - Vec2 normalizedOut = Vec2(nextKey.m_time - key.m_time, nextKey.m_value - key.m_value); - - key.m_inTangent = GetSmoothInTangent(key, normalizedIn, normalizedOut, &prevKey, &nextKey, true); - } - break; - } - case SCurveEditorKey::eTangentType_Flat: - { - key.m_inTangent = Vec2(prevKey.m_time - key.m_time, 0.0f) / 3.0f; - break; - } - case SCurveEditorKey::eTangentType_Step: - { - //key.m_inTangent = Vec2(0.0f, 0.0f); - break; - } - case SCurveEditorKey::eTangentType_Linear: - { - key.m_inTangent = Vec2(prevKey.m_time - key.m_time, prevKey.m_value - key.m_value) / 3.0f; - break; - } - default: - { - const float oneThirdDeltaTime = (key.m_time - prevKey.m_time) / 3.0f; - float ratio = oneThirdDeltaTime / -key.m_inTangent.x; - key.m_inTangent *= ratio; - break; - } - } - } - if (keyIx + 1 < curve.m_keys.size()) - { - SCurveEditorKey& nextKey = curve.m_keys[keyIx + 1]; - - switch (key.m_outTangentType) - { - case SCurveEditorKey::eTangentType_Smooth: - { - if (keyIx <= 0) - { - key.m_outTangent = Vec2(nextKey.m_time - key.m_time, nextKey.m_value - key.m_value) / 3.0f; - } - if (keyIx > 0) - { - SCurveEditorKey& prevKey = curve.m_keys[keyIx - 1]; - const float deltaTime = nextKey.m_time - prevKey.m_time; - if (deltaTime > 0.0f) - { - Vec2 normalizedIn = Vec2(prevKey.m_time - key.m_time, prevKey.m_value - key.m_value); - Vec2 normalizedOut = Vec2(nextKey.m_time - key.m_time, nextKey.m_value - key.m_value); - - key.m_outTangent = GetSmoothOutTangent(key, normalizedIn, normalizedOut, &prevKey, &nextKey, true); - } - } - break; - } - case SCurveEditorKey::eTangentType_Flat: - { - key.m_outTangent = Vec2(nextKey.m_time - key.m_time, 0.0f) / 3.0f; - break; - } - case SCurveEditorKey::eTangentType_Step: - { - //key.m_outTangent = Vec2(0.0f, 0.0f); - break; - } - case SCurveEditorKey::eTangentType_Linear: - { - key.m_outTangent = Vec2(nextKey.m_time - key.m_time, nextKey.m_value - key.m_value) / 3.0f; - break; - } - default: - { - const float oneThirdDeltaTime = (nextKey.m_time - key.m_time) / 3.0f; - float ratio = oneThirdDeltaTime / key.m_outTangent.x; - key.m_outTangent *= ratio; - break; - } - } - } - } - } -} - -QRect CCurveEditor::GetCurveArea() -{ - const uint rulerAreaHeight = m_bRulerVisible ? kRulerHeight : 0; - return QRect(0, rulerAreaHeight, width(), height() - rulerAreaHeight); -} - -Vec2 CCurveEditor::TransformToScreenCoordinates(Vec2 graphPoint) -{ - return TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), graphPoint); -} - -Vec2 CCurveEditor::TransformFromScreenCoordinates(Vec2 screenPoint) -{ - return TransformPointFromScreen(m_zoom, m_translation, GetCurveArea(), screenPoint); -} - -void CCurveEditor::SetOptOutFlags(int flags) -{ - m_optOutFlags = flags; - if (m_optOutFlags & EOptOutRuler) - { - m_bRulerVisible = false; - } -} - -void CCurveEditor::PopulateControlContextMenu(QMenu* pMenu) -{ - #define OPTOUT(BITS) ((m_optOutFlags & (BITS))) - - bool needsSeperator = false; - - pMenu->addAction("Delete selected keys", this, SLOT(OnDeleteSelectedKeys())); - pMenu->addSeparator(); - - // standard and smooth should only be available for both - flat, free, step, and linear should be available for all - const int flagsFreeStep = EOptOutFree | EOptOutStep; - if (OPTOUT(flagsFreeStep) != flagsFreeStep) - { - pMenu->addAction("Standard", this, SLOT(OnSetSelectedKeysTangentStandard())); - pMenu->addAction("Auto Smooth", this, SLOT(OnSetSelectedKeysTangentSmooth())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutFree)) - { - pMenu->addAction("Free", this, SLOT(OnSetSelectedKeysTangentFree())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutBezier)) - { - pMenu->addAction("Bezier", this, SLOT(OnSetSelectedKeysTangentBezier())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutFlat)) - { - pMenu->addAction("Flat", this, SLOT(OnSetSelectedKeysTangentFlat())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutLinear)) - { - pMenu->addAction("Linear", this, SLOT(OnSetSelectedKeysTangentLinear())); - needsSeperator = true; - } - - if (needsSeperator) - { - pMenu->addSeparator(); - } - needsSeperator = false; - - if (!OPTOUT(EOptOutBezier)) - { - pMenu->addAction("IN Tangent - Bezier", this, SLOT(OnSetSelectedKeysInTangentBezier())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutFree)) - { - pMenu->addAction("IN Tangent - Free", this, SLOT(OnSetSelectedKeysInTangentFree())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutFlat)) - { - pMenu->addAction("IN Tangent - Flat", this, SLOT(OnSetSelectedKeysInTangentFlat())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutLinear)) - { - pMenu->addAction("IN Tangent - Linear", this, SLOT(OnSetSelectedKeysInTangentLinear())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutStep)) - { - pMenu->addAction("IN Tangent - Step", this, SLOT(OnSetSelectedKeysInTangentStep())); - needsSeperator = true; - } - - if (needsSeperator) - { - pMenu->addSeparator(); - } - needsSeperator = false; - - if (!OPTOUT(EOptOutBezier)) - { - pMenu->addAction("OUT Tangent - Bezier", this, SLOT(OnSetSelectedKeysOutTangentBezier())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutFree)) - { - pMenu->addAction("OUT Tangent - Free", this, SLOT(OnSetSelectedKeysOutTangentFree())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutFlat)) - { - pMenu->addAction("OUT Tangent - Flat", this, SLOT(OnSetSelectedKeysOutTangentFlat())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutLinear)) - { - pMenu->addAction("OUT Tangent - Linear", this, SLOT(OnSetSelectedKeysOutTangentLinear())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutStep)) - { - pMenu->addAction("OUT Tangent - Step", this, SLOT(OnSetSelectedKeysOutTangentStep())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutFitCurvesContextMenuOptions)) - { - if (needsSeperator) - { - pMenu->addSeparator(); - } - needsSeperator = false; - pMenu->addAction("Fit curves horizontally", this, SLOT(OnFitCurvesHorizontally())); - pMenu->addAction("Fit curves vertically", this, SLOT(OnFitCurvesVertically())); - } -} - -void CCurveEditor::setPenColor(QColor color) -{ - if (color.isValid()) - { - m_penColor = color; - } - else if (!m_penColor.isValid()) - { - m_penColor = palette().highlight().color(); - } -} - -void CCurveEditor::updateCurveKeyShapeColor() -{ - for (CCurveEditorControl* key : m_pControlKeys) - { - QColor color = key->IsSelected() ? QColor(Qt::yellow) : QColor(Qt::white); - key->SetIconShapeColor(color); - } -} - -void CCurveEditor::SetIconShapeColor(unsigned int key, QColor color) -{ - m_pControlKeys[key]->SetIconShapeColor(color); -} - -void CCurveEditor::SetIconFillColor(unsigned int key, QColor color) -{ - m_pControlKeys[key]->SetIconFillColor(color); -} - -void CCurveEditor::SetIconImage(QString str) -{ - for (auto* key : m_pControlKeys) - { - key->SetIconImage(str); - } -} - -void CCurveEditor::SetIconShapeMask(QColor color) -{ - for (auto* key : m_pControlKeys) - { - key->SetIconShapeMask(color); - } -} - -void CCurveEditor::SetIconFillMask(QColor color) -{ - for (auto* key : m_pControlKeys) - { - key->SetIconFillMask(color); - } -} - -void CCurveEditor::SetIconToolTip(unsigned int key, QString str) -{ - m_pControlKeys[key]->SetIconToolTip(str); -} - -void CCurveEditor::SetIconSize(unsigned int key, unsigned int size) -{ - m_pControlKeys[key]->SetIconSize(size); - m_pControlKeys[key]->SetVisualSize(size); - m_pControlKeys[key]->SetClickableSize(size); -} - - diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditor.h b/Code/Sandbox/Plugins/EditorCommon/CurveEditor.h deleted file mode 100644 index 60d5608005..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditor.h +++ /dev/null @@ -1,233 +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 - -#include "CurveEditorContent.h" -#include -#include - -class QMenu; -class CCurveEditorControl; -class CCurveEditorTangentControl; -struct ISplineInterpolator; - -enum ETangent -{ - ETangent_In, - ETangent_Out -}; - -enum ECurveEditorCurveType -{ - eCECT_Bezier, - // 2D Bezier curves are used for better curve control, the editor - // will enforce that the resulting curve is always 1D. - eCECT_2DBezier, -}; - -namespace CurveEditorHelpers -{ - // Picks a nice color value for a curve. Wraps around after 4. - EDITOR_COMMON_API ColorB GetCurveColor(const uint n); - EDITOR_COMMON_API QColor LerpColor(const QColor& a, const QColor& b, float k); -} - -class EDITOR_COMMON_API CCurveEditor - : public QWidget -{ - Q_OBJECT -public: - enum EOptOutFlags - { - EOptOutFree = 1 << 0, - EOptOutFlat = 1 << 1, - EOptOutLinear = 1 << 2, - EOptOutStep = 1 << 3, - EOptOutBezier = 1 << 4, - EOptOutSelectionKey = 1 << 5, - EOptOutSelectionInOutTangent = 1 << 6, - //steven@conffx added some optout options to allow easier graphical customization - EOptOutKeyIcon = 1 << 7, - EOptOutRuler = 1 << 8, - EOptOutTimeSlider = 1 << 9, - EOptOutBackground = 1 << 10, - EOptOutCustomPenColor = 1 << 11, - EOptOutControls = 1 << 12, - eOptOutDashedPath = 1 << 13, - EOptOutDefaultTooltip = 1 << 14, - EOptOutFitCurvesContextMenuOptions = 1 << 15, - EOptOutZoomingAndPanning = 1 << 16 - }; - - CCurveEditor(QWidget* parent); - ~CCurveEditor(); - - void SetContent(SCurveEditorContent* pContent); - SCurveEditorContent* Content() const { return m_pContent; } - - void SetTime(const float time); - - // The background in the time and value range will be drawn a bit brighter to indicate where keys - // should be placed. The curve editor does not enforce that the curves actually stay in those ranges. - void SetTimeRange(const float start, const float end); - void SetValueRange(const float min, const float max); - - // Points cannot be added outside of the time range and the view will not move horizontally...zooming will only be done on the vertical axis - void EnforceTimeRange(const float start, const float end); - bool IsTimeRangeEnforced() const; - - void ZoomToTimeRange(const float start, const float end); - void ZoomToValueRange(const float min, const float max); - - void SetCurveType(ECurveEditorCurveType curveType); - void SetWeighted(bool bWeighted); - void SetHandlesVisible(bool bVisible); - void SetRulerVisible(bool bVisible); - void SetTimeSliderVisible(bool bVisible); - - Vec2 TransformToScreenCoordinates(Vec2 graphPoint); - Vec2 TransformFromScreenCoordinates(Vec2 screenPoint); - - // Removes parts of the popup-menu, use CCurveEditor::EMenuOptOutFlags - void SetOptOutFlags(int flags); - - // Tools added to tool bar depend on options above - void PopulateControlContextMenu(QMenu* pToolBar); - - virtual void paintEvent(QPaintEvent* pEvent) override; - void mousePressEvent(QMouseEvent* pEvent) override; - void mouseDoubleClickEvent(QMouseEvent* pEvent) override; - void mouseMoveEvent(QMouseEvent* pEvent) override; - void mouseReleaseEvent(QMouseEvent* pEvent) override; - void focusOutEvent(QFocusEvent* pEvent) override; - void wheelEvent(QWheelEvent* pEvent) override; - void keyPressEvent(QKeyEvent* pEvent) override; - - QString static TangentTypeToString(SCurveEditorKey::ETangentType type); - - void updateCurveKeyShapeColor(); // loop through curve keys and set shape color for them - void SetIconShapeColor(unsigned int key, QColor color); - void SetIconFillColor(unsigned int key, QColor color); - void SetIconImage(QString str); - void SetIconShapeMask(QColor color); - void SetIconFillMask(QColor color); - void SetIconToolTip(unsigned int key, QString str); - void SetIconSize(unsigned int key, unsigned int size); - - void setPenColor(QColor color); - void ContentChanged(); - void SortKeys(SCurveEditorCurve& curve); - - std::pair HitDetectCurve(const QPoint point); - CCurveEditorControl* HitDetectKey(const QPoint point); - CCurveEditorTangentControl* HitDetectTangent(const QPoint point); - - CCurveEditorControl* GetSelectedCurveKey(); - QRectF GetBackgroundRect(); - - void SelectKey(CCurveEditorControl* pKeyToSelect, bool addToExistingSelection); - void SelectTangent(CCurveEditorTangentControl* pTangentToSelect); - void SelectInRect(const QRect& rect); - -signals: - void SignalContentChanged(); - void SignalScrub(); - void SignalKeyMoved(); - void SignalKeyMoveStarted(); - void SignalKeySelected(CCurveEditorControl* selectedKey); - -public slots: - void OnDeleteSelectedKeys(); - void OnSetSelectedKeysTangentStandard(); - void OnSetSelectedKeysTangentSmooth(); - void OnSetSelectedKeysTangentFree(); - void OnSetSelectedKeysTangentBezier(); - void OnSetSelectedKeysTangentFlat(); - void OnSetSelectedKeysTangentLinear(); - - void OnSetSelectedKeysInTangentFree(); - void OnSetSelectedKeysInTangentFlat(); - void OnSetSelectedKeysInTangentLinear(); - void OnSetSelectedKeysInTangentStep(); - void OnSetSelectedKeysInTangentBezier(); - - void OnSetSelectedKeysOutTangentFree(); - void OnSetSelectedKeysOutTangentFlat(); - void OnSetSelectedKeysOutTangentLinear(); - void OnSetSelectedKeysOutTangentStep(); - void OnSetSelectedKeysOutTangentBezier(); - - void OnFitCurvesHorizontally(); - void OnFitCurvesVertically(); - -protected: - struct SMouseHandler - { - virtual ~SMouseHandler() = default; - virtual void mousePressEvent([[maybe_unused]] QMouseEvent* pEvent) {} - virtual void mouseDoubleClickEvent([[maybe_unused]] QMouseEvent* pEvent) {} - virtual void mouseMoveEvent([[maybe_unused]] QMouseEvent* pEvent) {} - virtual void mouseReleaseEvent([[maybe_unused]] QMouseEvent* pEvent) {} - virtual void focusOutEvent([[maybe_unused]] QFocusEvent* pEvent) {} - virtual void paintOver([[maybe_unused]] QPainter& painter) {} - }; - struct SSelectionHandler; - struct SPanHandler; - struct SZoomHandler; - struct SMoveKeyHandler; - struct SRotateTangentHandler; - struct SScrubHandler; - QColor m_penColor; - - void LeftButtonMousePressEvent(QMouseEvent* pEvent); - void MiddleButtonMousePressEvent(QMouseEvent* pEvent); - void RightButtonMousePressEvent(QMouseEvent* pEvent); - - void DeleteMarkedKeys(); - - void SetTimeRange(const float start, const float end, bool enforce); - - Vec2 ClosestPointOnCurve(const Vec2 point, const SCurveEditorCurve& curve, const ECurveEditorCurveType curveType); - - bool AddPointToCurve(Vec2 point, SCurveEditorCurve* pCurve); - - QRect GetCurveArea(); - - void SetSelectedKeysTangentType(const ETangent tangent, const SCurveEditorKey::ETangentType type); - void SmoothSelectedKeys(); - - void UpdateTangents(); - SCurveEditorContent* m_pContent; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - std::unique_ptr m_pMouseHandler; - - ECurveEditorCurveType m_curveType; - bool m_bWeighted; - bool m_bHandlesVisible; - bool m_bRulerVisible; - bool m_bTimeSliderVisible; - - float m_time; - Vec2 m_zoom; - Vec2 m_translation; - Range m_timeRange; - bool m_timeRangeEnforced; - Range m_valueRange; - - int m_optOutFlags; -public: - QList m_pControlKeys; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent.h b/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent.h deleted file mode 100644 index 49acc62f67..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent.h +++ /dev/null @@ -1,155 +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 - -#include -#include - -#include "Serialization/Strings.h" -#include "Serialization/SmartPtr.h" -#include "Serialization/Color.h" -#include "Serialization.h" - -struct ISplineInterpolator; - -struct SCurveEditorKey -{ - SCurveEditorKey() - : m_bSelected(false) - , m_bModified(false) - , m_bAdded(false) - , m_bDeleted(false) - , m_time(0.0f) - , m_value(0.0f) - , m_inTangentType(eTangentType_Standard) - , m_outTangentType(eTangentType_Standard) - , m_inTangent(ZERO) - , m_outTangent(ZERO) - { - } - - enum ETangentType - { - eTangentType_Standard, // Tangent freely rotates but will stay in sync with its pair if its pair is also standard - eTangentType_Free, // Tangent is completely free moving (does not sync with its pair) - eTangentType_Step, // Step immediately to value of next control point in tangent direction - eTangentType_Linear, // Tangent always points to next control point - eTangentType_Bezier, // Tangent is free moving and can be justified by user - eTangentType_Smooth, // Tangent is smoothed automatically based on direction/distance to neighboring controls - eTangentType_Flat, // Tangent is flattened (y = 0) - will still sync with its pair if both are flat - }; - - void Serialize(IArchive& ar) - { - ar(m_inTangentType, "inTangentType"); - ar(m_outTangentType, "outTangentType"); - ar(m_time, "time"); - ar(m_value, "value"); - ar(m_inTangent, "inTangent"); - ar(m_outTangent, "outTangent"); - } - - bool m_bSelected : 1; - bool m_bModified : 1; - bool m_bAdded : 1; - bool m_bDeleted : 1; - - ETangentType m_inTangentType : 4; - ETangentType m_outTangentType : 4; - - float m_time; - float m_value; - - // For 1D Bezier only the Y component is used - Vec2 m_inTangent; - Vec2 m_outTangent; - - - bool operator==(const SCurveEditorKey& rhs) const - { - return (m_inTangentType == rhs.m_inTangentType - && m_outTangentType == rhs.m_outTangentType - && m_time == rhs.m_time - && m_value == rhs.m_value - && m_inTangent == rhs.m_inTangent - && m_outTangent == rhs.m_outTangent); - } - - bool operator!=(const SCurveEditorKey& rhs) const - { - return !(*this == rhs); - } -}; - -struct SCurveEditorCurve -{ - SCurveEditorCurve() - : m_bModified(false) - , m_defaultValue(0.0f) - , m_color(255, 255, 255) - , m_customInterpolator(nullptr) - {} - - void Serialize(IArchive& ar) - { - ar(m_keys, "keys"); - ar(m_defaultValue, "defaultValue"); - ar(m_color, "color"); - } - - bool m_bModified : 1; - float m_defaultValue; - ColorB m_color; - - // Setting m_customInterpolator will override spline-draw code. - // When used, its up to developer to fill and update all necessary keys. - ISplineInterpolator* m_customInterpolator; - - std::vector m_keys; - - bool operator==(const SCurveEditorCurve& rhs) const - { - if (m_defaultValue != rhs.m_defaultValue - || m_color != rhs.m_color - || m_keys.size() != rhs.m_keys.size()) - { - return false; - } - - for (int i = 0; i < m_keys.size(); i++) - { - if (m_keys[i] != rhs.m_keys[i]) - return false; - } - - return true; - } - - bool operator!=(const SCurveEditorCurve& rhs) const - { - return !(*this == rhs); - } -}; - -typedef std::vector TCurveEditorCurves; - -struct SCurveEditorContent -{ - void Serialize(IArchive& ar) - { - ar(m_curves, "curves"); - } - - TCurveEditorCurves m_curves; -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent_38.h b/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent_38.h deleted file mode 100644 index f11a135c80..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent_38.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. -* -*/ -#pragma once - -#include -#include -#include -#include - -#include "Serialization/Strings.h" -#include "Serialization/SmartPtr.h" -#include "Serialization/Color.h" -#include "Serialization.h" - -struct SCurveEditorKey -{ - SCurveEditorKey() - : m_time(0) - , m_bSelected(false) - , m_bModified(false) - , m_bAdded(false) - , m_bDeleted(false) - { - } - - void Serialize(IArchive& ar) - { - ar(m_time); - ar(m_controlPoint); - } - - SAnimTime m_time; - SBezierControlPoint m_controlPoint; - - bool m_bSelected : 1; - bool m_bModified : 1; - bool m_bAdded : 1; - bool m_bDeleted : 1; -}; - -struct SCurveEditorCurve -{ - SCurveEditorCurve() - : m_bModified(false) - , m_defaultValue(0.0f) - , m_color(255, 255, 255) - {} - - void Serialize(IArchive& ar) - { - ar(m_keys, "keys"); - ar(m_defaultValue, "defaultValue"); - ar(m_color, "color"); - } - - bool m_bModified : 1; - float m_defaultValue; - ColorB m_color; - - DynArray userSideLoad; - - std::vector m_keys; -}; - -typedef std::vector TCurveEditorCurves; - -struct SCurveEditorContent -{ - void Serialize(IArchive& ar) - { - ar(m_curves, "curves"); - } - - TCurveEditorCurves m_curves; -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent_impl.h b/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent_impl.h deleted file mode 100644 index 9d2bdd796a..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent_impl.h +++ /dev/null @@ -1,20 +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 "CurveEditorContent.h" - -SERIALIZATION_ENUM_BEGIN_NESTED(SCurveEditorKey, ETangentType, "TangentType") -SERIALIZATION_ENUM_VALUE_NESTED(SCurveEditorKey, eTangentType_Custom, "Custom") -SERIALIZATION_ENUM_VALUE_NESTED(SCurveEditorKey, eTangentType_Auto, "Smooth") -SERIALIZATION_ENUM_VALUE_NESTED(SCurveEditorKey, eTangentType_Zero, "Zero") -SERIALIZATION_ENUM_VALUE_NESTED(SCurveEditorKey, eTangentType_Step, "Step") -SERIALIZATION_ENUM_VALUE_NESTED(SCurveEditorKey, eTangentType_Linear, "Linear") -SERIALIZATION_ENUM_END() diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditorControl.cpp b/Code/Sandbox/Plugins/EditorCommon/CurveEditorControl.cpp deleted file mode 100644 index 0b0359a0ad..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditorControl.cpp +++ /dev/null @@ -1,352 +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 "EditorCommon_precompiled.h" -#include "CurveEditorControl.h" - -#include -#include -#include - -#include - -#include "CurveEditor.h" - -namespace -{ - const int kDefaultControlVisualSize = 8; - const int kDefaultControlClickableSize = 10; - const int kDefaultTangentControlVisualSize = 6; - const int kDefaultTangentControlClickableSize = 8; - const int kDefaultTangentControlDistanceFromControl = 30; - - void DrawPointRect(QPainter& painter, QPointF point, const QColor& color, int size) - { - painter.setBrush(QBrush(color)); - painter.setPen(QColor(0, 0, 0)); - float halfSize = size / 2.0f; - QPointF extents = QPointF(halfSize, halfSize); - painter.drawRect(QRectF(point - extents, point + extents)); - } -} - -CCurveEditorControl::CCurveEditorControl(CCurveEditor& curveEditor, SCurveEditorCurve& curve, SCurveEditorKey& key) - : m_CurveEditor(curveEditor) - , m_Curve(curve) - , m_Key(key) - , m_VisualSize(kDefaultControlVisualSize) - , m_ClickableSize(kDefaultControlClickableSize) - , m_pInTangent(new CCurveEditorTangentControl(*this, ETangent_In)) - , m_pOutTangent(new CCurveEditorTangentControl(*this, ETangent_Out)) - , m_filledPxr(kDefaultControlVisualSize, kDefaultControlVisualSize) - , m_shapePxr(kDefaultControlVisualSize, kDefaultControlVisualSize) - , m_icon(kDefaultControlVisualSize, kDefaultControlVisualSize) - , m_originalPxr(kDefaultControlVisualSize, kDefaultControlVisualSize) - , m_tip("") - , m_iconsize(16) -{ -} - -CCurveEditorControl::~CCurveEditorControl() -{ - delete m_pInTangent; - delete m_pOutTangent; -} - -CCurveEditor& CCurveEditorControl::GetCurveEditor() const -{ - return m_CurveEditor; -} - -SCurveEditorCurve& CCurveEditorControl::GetCurve() const -{ - return m_Curve; -} - -SCurveEditorKey& CCurveEditorControl::GetKey() const -{ - return m_Key; -} - -CCurveEditorTangentControl& CCurveEditorControl::GetInTangent() -{ - return *m_pInTangent; -} - -CCurveEditorTangentControl& CCurveEditorControl::GetOutTangent() -{ - return *m_pOutTangent; -} - -bool CCurveEditorControl::IsSelected() const -{ - return m_Key.m_bSelected; -} - -void CCurveEditorControl::SetSelected(bool selected) -{ - m_Key.m_bSelected = selected; - m_pInTangent->SetVisible(selected); - m_pOutTangent->SetVisible(selected); -} - -bool CCurveEditorControl::IsKeyMarkedForRemoval() const -{ - return m_Key.m_bDeleted; -} - -void CCurveEditorControl::MarkKeyForRemoval() -{ - m_Key.m_bDeleted = true; -} - -void CCurveEditorControl::Paint(QPainter& painter, const QPalette& palette, const bool& paintInOutTangents) -{ - const QColor pointColor = m_Key.m_bSelected ? palette.color(QPalette::Highlight) : QColor(255, 255, 255, 255); - - if (paintInOutTangents) - { - m_pInTangent->Paint(painter, palette); - m_pOutTangent->Paint(painter, palette); - } - - DrawPointRect(painter, GetScreenPosition(), pointColor, m_VisualSize); -} -void CCurveEditorControl::PaintIcon(QPainter& painter, const QPalette& palette, const bool& paintInOutTangents) -{ - if (paintInOutTangents) - { - m_pInTangent->Paint(painter, palette); - m_pOutTangent->Paint(painter, palette); - } - - QPointF pos = GetScreenPosition(); - float halfSize = m_iconsize / 2.0f; - QPointF extents = QPointF(halfSize, halfSize); - painter.drawPixmap(QRectF(GetScreenPosition() - extents, GetScreenPosition() + extents), m_icon, QRectF(0, 0, m_iconsize, m_iconsize)); -} - -bool CCurveEditorControl::IsMouseWithinControl(QPointF screenPos) const -{ - QPointF keyPosition = GetScreenPosition(); - QPointF deltaPos = screenPos - keyPosition; - - float halfClickSize = m_ClickableSize / 2.0f; - - return abs(deltaPos.x()) <= halfClickSize && abs(deltaPos.y()) <= halfClickSize; -} - -QPointF CCurveEditorControl::GetScreenPosition() const -{ - Vec2 screenPosition = m_CurveEditor.TransformToScreenCoordinates(Vec2(m_Key.m_time, m_Key.m_value)); - return QPointF(screenPosition.x, screenPosition.y); -} - -void CCurveEditorControl::BuildIcon() -{ - m_filledPxr = QPixmap(m_originalPxr.size()); - m_shapePxr = QPixmap(m_originalPxr.size()); - m_shapePxr.fill(m_shapeColor); - m_filledPxr.fill(m_fillColor); - m_shapePxr.setMask(m_originalPxr.createMaskFromColor(m_shapeMask).createMaskFromColor(m_fillMask)); - m_filledPxr.setMask(m_originalPxr.createMaskFromColor(m_fillMask, Qt::MaskOutColor)); - QPainter painter(&m_shapePxr); - painter.drawPixmap(0, 0, m_filledPxr); - m_icon = m_shapePxr.scaled(m_iconsize, m_iconsize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); -} - -void CCurveEditorControl::SetIconFillMask(QColor color) -{ - m_fillMask = color; - BuildIcon(); -} - -void CCurveEditorControl::SetIconShapeMask(QColor color) -{ - m_shapeMask = color; - BuildIcon(); -} - -void CCurveEditorControl::SetIconImage(QString str) -{ - m_originalPxr.load(str); - BuildIcon(); -} - -void CCurveEditorControl::SetIconFillColor(QColor color) -{ - m_fillColor = color; - BuildIcon(); -} - -void CCurveEditorControl::SetIconShapeColor(QColor color) -{ - m_shapeColor = color; - BuildIcon(); -} - - -CCurveEditorTangentControl::CCurveEditorTangentControl(CCurveEditorControl& control, ETangent tangentDirection) - : m_Control(control) - , m_TangentDirection(tangentDirection) - , m_Visible(false) - , m_Selected(false) - , m_VisualSize(kDefaultTangentControlVisualSize) - , m_ClickableSize(kDefaultTangentControlClickableSize) - , m_DistanceFromControl(kDefaultTangentControlDistanceFromControl) -{ -} - -CCurveEditorTangentControl::~CCurveEditorTangentControl() -{ -} - -CCurveEditorControl& CCurveEditorTangentControl::GetControl() -{ - return m_Control; -} - -ETangent CCurveEditorTangentControl::GetTangentDirection() const -{ - return m_TangentDirection; -} - -bool CCurveEditorTangentControl::IsVisible() const -{ - if (!m_Visible) - { - return false; - } - SCurveEditorKey::ETangentType tangentType; - - if (m_TangentDirection == ETangent_In) - { - tangentType = m_Control.GetKey().m_inTangentType; - } - else - { - tangentType = m_Control.GetKey().m_outTangentType; - } - - if (tangentType == SCurveEditorKey::eTangentType_Step) - { - return false; - } - - // first in - if ((*m_Control.GetCurve().m_keys.begin()).m_time == m_Control.GetKey().m_time && m_TangentDirection == ETangent_In) - { - return false; - } - - // last out - if ((*(m_Control.GetCurve().m_keys.end() - 1)).m_time == m_Control.GetKey().m_time && m_TangentDirection == ETangent_Out) - { - return false; - } - - return true; -} - -void CCurveEditorTangentControl::SetVisible(bool visible) -{ - m_Visible = visible; -} - -bool CCurveEditorTangentControl::IsSelected() const -{ - return m_Selected; -} - -void CCurveEditorTangentControl::SetSelected(bool selected) -{ - m_Selected = selected; -} - -void CCurveEditorTangentControl::SetVisualSize(int visualSize) -{ - m_VisualSize = visualSize; -} - -void CCurveEditorTangentControl::SetClickableSize(int clickableSize) -{ - m_ClickableSize = clickableSize; -} - -void CCurveEditorTangentControl::SetDistanceFromControl(int distanceFromControl) -{ - m_DistanceFromControl = distanceFromControl; -} - -void CCurveEditorTangentControl::Paint(QPainter& painter, const QPalette& palette) -{ - if (!IsVisible()) - { - return; - } - - QPointF controlPosition = m_Control.GetScreenPosition(); - QPointF tangentPosition = GetScreenPosition(); - - float highlightPercent; - if (m_Selected) - { - highlightPercent = 0.0f; - } - else - { - highlightPercent = 0.5f; - } - const QColor tangentColor = CurveEditorHelpers::LerpColor(palette.color(QPalette::Highlight), palette.color(QPalette::Window), highlightPercent); - const QPen tangentPen = QPen(tangentColor); - - painter.setPen(tangentPen); - painter.drawLine(controlPosition, tangentPosition); - - const QColor tangentControlColor = m_Selected ? palette.color(QPalette::Highlight) : palette.color(QPalette::Dark); - DrawPointRect(painter, tangentPosition, tangentControlColor, m_VisualSize); -} - -bool CCurveEditorTangentControl::IsMouseWithinControl(QPointF screenPos) const -{ - if (!IsVisible()) - { - return false; - } - - QPointF keyPosition = GetScreenPosition(); - QPointF deltaPos = screenPos - keyPosition; - - float halfClickSize = m_ClickableSize / 2.0f; - - return abs(deltaPos.x()) <= halfClickSize && abs(deltaPos.y()) <= halfClickSize; -} - -QPointF CCurveEditorTangentControl::GetScreenPosition() const -{ - QPointF controlPosition = m_Control.GetScreenPosition(); - - Vec2 tangent; - if (m_TangentDirection == ETangent_In) - { - tangent = m_Control.GetKey().m_inTangent; - } - else - { - tangent = m_Control.GetKey().m_outTangent; - } - - Vec2 tangentScreenPosition = m_Control.GetCurveEditor().TransformToScreenCoordinates(Vec2(m_Control.GetKey().m_time + tangent.x, m_Control.GetKey().m_value + tangent.y)); - Vec2 transformedTangentDelta = (tangentScreenPosition - Vec2(aznumeric_cast(controlPosition.x()), aznumeric_cast(controlPosition.y()))).Normalize() * aznumeric_cast(m_DistanceFromControl); - - return controlPosition + QPointF(transformedTangentDelta.x, transformedTangentDelta.y); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditorControl.h b/Code/Sandbox/Plugins/EditorCommon/CurveEditorControl.h deleted file mode 100644 index 5cc12cbfcf..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditorControl.h +++ /dev/null @@ -1,150 +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 "CurveEditor.h" - -#include - -class CCurveEditor; -class CCurveEditorTangentControl; -class QMouseEvent; - -class QPainter; - -class EDITOR_COMMON_API CCurveEditorControl -{ -public: - CCurveEditorControl(CCurveEditor& curveEditor, SCurveEditorCurve& curve, SCurveEditorKey& key); - ~CCurveEditorControl(); - - CCurveEditor& GetCurveEditor() const; - SCurveEditorCurve& GetCurve() const; - SCurveEditorKey& GetKey() const; - - CCurveEditorTangentControl& GetInTangent(); - CCurveEditorTangentControl& GetOutTangent(); - - void SetVisualSize(int visualSize) - { - m_VisualSize = visualSize; - } - void SetClickableSize(int clickableSize) - { - m_ClickableSize = clickableSize; - } - - bool IsSelected() const; - void SetSelected(bool selected); - - bool IsKeyMarkedForRemoval() const; - void MarkKeyForRemoval(); - - void Paint(QPainter& painter, const QPalette& palette, const bool& paintInOutTangents); - void PaintIcon(QPainter& painter, const QPalette& palette, const bool& paintInOutTangents); - - bool IsMouseWithinControl(QPointF screenPos) const; - - QPointF GetScreenPosition() const; - - QRect GetRect() const - { - return QRect(aznumeric_cast(GetScreenPosition().x() - (m_VisualSize / 2)), aznumeric_cast(GetScreenPosition().y() - (m_VisualSize / 2)), m_VisualSize, m_VisualSize); - } - - void SetIconShapeColor(QColor color); - - void SetIconFillColor(QColor color); - - void SetIconImage(QString str); - - void SetIconShapeMask(QColor color); - - void SetIconFillMask(QColor color); - - void SetIconToolTip(QString str) - { - m_tip = str; - } - - void SetIconSize(int size) - { - m_iconsize = size; - BuildIcon(); - } - - QString GetToolTip() const { return m_tip; } - -protected: - void BuildIcon(); - -private: - QPixmap m_icon; - QPixmap m_filledPxr; - QPixmap m_shapePxr; - QPixmap m_originalPxr; - QColor m_fillColor; - QColor m_shapeColor; - QColor m_fillMask; - QColor m_shapeMask; - QString m_tip; - int m_iconsize; - - CCurveEditor& m_CurveEditor; - SCurveEditorCurve& m_Curve; - SCurveEditorKey& m_Key; - - int m_VisualSize; - int m_ClickableSize; - - CCurveEditorTangentControl* m_pInTangent; - CCurveEditorTangentControl* m_pOutTangent; -}; - -class EDITOR_COMMON_API CCurveEditorTangentControl -{ -public: - CCurveEditorTangentControl(CCurveEditorControl& curveControl, ETangent tangentDirection); - ~CCurveEditorTangentControl(); - - CCurveEditorControl& GetControl(); - ETangent GetTangentDirection() const; - - bool IsVisible() const; - void SetVisible(bool visible); - - bool IsSelected() const; - void SetSelected(bool selected); - - void SetVisualSize(int visualSize); - void SetClickableSize(int clickableSize); - void SetDistanceFromControl(int distanceFromControl); - - void Paint(QPainter& painter, const QPalette& palette); - - bool IsMouseWithinControl(QPointF screenPos) const; - -private: - - QPointF GetScreenPosition() const; - - CCurveEditorControl& m_Control; - ETangent m_TangentDirection; - - bool m_Selected; - - int m_VisualSize; - int m_ClickableSize; - int m_DistanceFromControl; - - bool m_Visible; -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditor_38.cpp b/Code/Sandbox/Plugins/EditorCommon/CurveEditor_38.cpp deleted file mode 100644 index 60a61b930f..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditor_38.cpp +++ /dev/null @@ -1,1825 +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 "EditorCommon_precompiled.h" -#include "CurveEditor.h" -#include "DrawingPrimitives/TimeSlider.h" -#include "DrawingPrimitives/Ruler.h" - -#include -#include -#include -#include -#include - -#pragma warning (push) -#pragma warning (disable : 4554) - -#define INDEX_NOT_OUT_OF_RANGE PREFAST_SUPPRESS_WARNING(6201) -#define NO_BUFFER_OVERRUN PREFAST_SUPPRESS_WARNING(6385 6386) -#include "Cry_LegacyPhysUtils.h" - -#pragma warning (pop) - -namespace CurveEditorHelpers -{ - const uint numColors = 4; - ColorB colors[numColors] = - { - ColorB(243, 126, 121), - ColorB(121, 152, 243), - ColorB(187, 243, 121), - ColorB(243, 121, 223), - }; - - ColorB GetCurveColor(const uint n) - { - return colors[n % numColors]; - } - - QColor Interpolate(const QColor& a, const QColor& b, float k) - { - float mk = 1.0f - k; - return QColor(a.red() * mk + b.red() * k, - a.green() * mk + b.green() * k, - a.blue() * mk + b.blue() * k, - a.alpha() * mk + b.alpha() * k); - } -} - -namespace -{ - using namespace LegacyCryPhysicsUtils; - - const int kRulerHeight = 16; - const int kRulerShadowHeight = 6; - const int kRulerMarkHeight = 8; - const float kHitDistance = 5.0f; - const float kMinZoom = 0.00001f; - const float kMaxZoom = 1000.0f; - const float kFitMargin = 30.0f; - - const QPointF kPointRectExtent = QPointF(2.5f, 2.5f); - - Vec2 TransformPointToScreen(const Vec2 zoom, const Vec2 translation, QRect curveArea, Vec2 point) - { - Vec2 transformedPoint = Vec2(point.x * zoom.x, point.y * -zoom.y) + translation; - transformedPoint.x *= curveArea.width(); - transformedPoint.y *= curveArea.height(); - return Vec2(transformedPoint.x + curveArea.left(), transformedPoint.y + curveArea.top()); - } - - Vec2 TransformPointFromScreen(const Vec2 zoom, const Vec2 translation, QRect curveArea, Vec2 point) - { - Vec2 transformedPoint = Vec2((point.x - curveArea.left()) / curveArea.width(), (point.y - curveArea.top()) / curveArea.height()) - translation; - transformedPoint.x /= zoom.x; - transformedPoint.y /= -zoom.y; - return Vec2(transformedPoint.x, transformedPoint.y); - } - - QPointF Vec2ToPoint(Vec2 point) - { - return QPointF(point.x, point.y); - } - - Vec2 PointToVec2(QPointF point) - { - return Vec2(point.x(), point.y()); - } - - // This function returns a new key with position and weights affected by eTangentType_Smooth, eTangentType_Linear and eTangentType_Step for the incoming tangent - SCurveEditorKey ApplyInTangentFlags(const SCurveEditorKey& key, const SCurveEditorKey& leftKey, const SCurveEditorKey* pRightKey) - { - SCurveEditorKey newKey = key; - - if (leftKey.m_controlPoint.m_outTangentType == SBezierControlPoint::eTangentType_Step) - { - newKey.m_controlPoint.m_inTangent = Vec2(0.0f, 0.0f); - return newKey; - } - else if (key.m_controlPoint.m_inTangentType != SBezierControlPoint::eTangentType_Step) - { - const SAnimTime leftTime = leftKey.m_time; - const SAnimTime rightTime = pRightKey ? pRightKey->m_time : key.m_time; - - // Rebase to [0, rightTime - leftTime] to increase float precision - const float floatTime = (key.m_time - leftTime).ToFloat(); - const float floatLeftTime = 0.0f; - const float floatRightTime = (rightTime - leftTime).ToFloat(); - - newKey.m_controlPoint = Bezier::CalculateInTangent(floatTime, key.m_controlPoint, - floatLeftTime, &leftKey.m_controlPoint, - floatRightTime, pRightKey ? &pRightKey->m_controlPoint : nullptr); - } - else - { - newKey.m_controlPoint.m_inTangent = Vec2(0.0f, 0.0f); - newKey.m_controlPoint.m_value = leftKey.m_controlPoint.m_value; - } - - return newKey; - } - - // This function returns a new key with position and weights affected by eTangentType_Smooth, eTangentType_Linear and eTangentType_Step for the outgoing tangent - SCurveEditorKey ApplyOutTangentFlags(const SCurveEditorKey& key, const SCurveEditorKey* pLeftKey, const SCurveEditorKey& rightKey) - { - SCurveEditorKey newKey = key; - - if (rightKey.m_controlPoint.m_inTangentType == SBezierControlPoint::eTangentType_Step - && key.m_controlPoint.m_outTangentType != SBezierControlPoint::eTangentType_Step) - { - newKey.m_controlPoint.m_outTangent = Vec2(0.0f, 0.0f); - } - else if (key.m_controlPoint.m_outTangentType != SBezierControlPoint::eTangentType_Step) - { - const SAnimTime leftTime = pLeftKey ? pLeftKey->m_time : key.m_time; - const SAnimTime rightTime = rightKey.m_time; - - // Rebase to [0, rightTime - leftTime] to increase float precision - const float floatTime = (key.m_time - leftTime).ToFloat(); - const float floatLeftTime = 0.0f; - const float floatRightTime = (rightTime - leftTime).ToFloat(); - - newKey.m_controlPoint = Bezier::CalculateOutTangent(floatTime, key.m_controlPoint, - floatLeftTime, pLeftKey ? &pLeftKey->m_controlPoint : nullptr, - floatRightTime, &rightKey.m_controlPoint); - } - else - { - newKey.m_controlPoint.m_outTangent = Vec2(0.0f, 0.0f); - newKey.m_controlPoint.m_value = rightKey.m_controlPoint.m_value; - } - - return newKey; - } - - QPainterPath CreatePathFromCurve(const SCurveEditorCurve& curve, ECurveEditorCurveType curveType, AZStd::function transformFunc) - { - QPainterPath path; - - const Vec2 startPoint(curve.m_keys[0].m_time.ToFloat(), curve.m_keys[0].m_controlPoint.m_value); - const Vec2 startTransformed = transformFunc(startPoint); - path.moveTo(startTransformed.x, startTransformed.y); - - const auto endIter = curve.m_keys.end() - 1; - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - const SCurveEditorKey* pKeyLeftOfSegment = (iter != curve.m_keys.begin()) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pKeyRightOfSegment = (iter != (curve.m_keys.end() - 2)) ? &*(iter + 2) : nullptr; - - const SCurveEditorKey segmentStartKey = ApplyOutTangentFlags(*iter, pKeyLeftOfSegment, *(iter + 1)); - const SCurveEditorKey segmentEndKey = ApplyInTangentFlags(*(iter + 1), *iter, pKeyRightOfSegment); - - const Vec2 p0 = Vec2(segmentStartKey.m_time.ToFloat(), segmentStartKey.m_controlPoint.m_value); - const Vec2 p3 = Vec2(segmentEndKey.m_time.ToFloat(), segmentEndKey.m_controlPoint.m_value); - - Vec2 p1, p2; - if (curveType == eCECT_Bezier) - { - // Need to compute tangents for x so that the cubic 2D Bezier does a linear interpolation in - // that dimension, because we actually want to draw a cubic 1D Bezier curve - const float outTangentX = (2.0f * p0.x + p3.x) / 3.0f; // p1 = (2 * p0 + p3) / 3 - const float inTangentX = (p0.x + 2.0f * p3.x) / 3.0f; // p2 = (p0 + 2 * p3) / 3 - - p1 = Vec2(outTangentX, p0.y + segmentStartKey.m_controlPoint.m_outTangent.y); - p2 = Vec2(inTangentX, p3.y + segmentEndKey.m_controlPoint.m_inTangent.y); - } - else if (curveType == eCECT_2DBezier) - { - p1 = p0 + segmentStartKey.m_controlPoint.m_outTangent; - p2 = p3 + segmentEndKey.m_controlPoint.m_inTangent; - } - - const QPointF p0Transformed = Vec2ToPoint(transformFunc(p0)); - const QPointF p1Transformed = Vec2ToPoint(transformFunc(p1)); - const QPointF p2Transformed = Vec2ToPoint(transformFunc(p2)); - const QPointF p3Transformed = Vec2ToPoint(transformFunc(p3)); - path.moveTo(p0Transformed); - path.cubicTo(p1Transformed, p2Transformed, p3Transformed); - } - - return path; - } - - QPainterPath CreateExtrapolatedPathFromCurve(const SCurveEditorCurve& curve, AZStd::function transformFunc, float windowWidth) - { - QPainterPath path; - - if (curve.m_keys.size() > 0) - { - const Vec2 startPoint = Vec2(curve.m_keys[0].m_time.ToFloat(), curve.m_keys[0].m_controlPoint.m_value); - const Vec2 startTransformed = transformFunc(startPoint); - if (startTransformed.x > 0.0f) - { - path.moveTo(std::min(startTransformed.x, windowWidth), startTransformed.y); - path.lineTo(0.0f, startTransformed.y); - } - - const Vec2 endPoint(curve.m_keys.back().m_time.ToFloat(), curve.m_keys.back().m_controlPoint.m_value); - const Vec2 endTransformed = transformFunc(endPoint); - if (endTransformed.x < windowWidth) - { - path.moveTo(std::max(endTransformed.x, 0.0f), endTransformed.y); - path.lineTo(windowWidth, endTransformed.y); - } - } - else - { - const Vec2 pointOnCurve = Vec2(0.0f, curve.m_defaultValue); - const Vec2 pointOnTransformed = transformFunc(pointOnCurve); - path.moveTo(0.0, pointOnTransformed.y); - path.lineTo(windowWidth, pointOnTransformed.y); - } - - QVector dashPattern; - dashPattern << 16 << 8; - - QPainterPathStroker stroker; - stroker.setCapStyle(Qt::RoundCap); - stroker.setDashPattern(dashPattern); - stroker.setWidth(0.5); - - return stroker.createStroke(path); - } - - QPainterPath CreateDiscontinuityPathFromCurve(const SCurveEditorCurve& curve, ECurveEditorCurveType curveType, AZStd::function transformFunc) - { - QPainterPath path; - - if (curve.m_keys.size() > 0) - { - const auto endIter = curve.m_keys.end() - 1; - - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - const SCurveEditorKey* pKeyLeftOfSegment = (iter != curve.m_keys.begin()) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pKeyRightOfSegment = (iter != (curve.m_keys.end() - 2)) ? &*(iter + 2) : nullptr; - - const SCurveEditorKey segmentStartKey = ApplyOutTangentFlags(*iter, pKeyLeftOfSegment, *(iter + 1)); - const SCurveEditorKey segmentEndKey = ApplyInTangentFlags(*(iter + 1), *iter, pKeyRightOfSegment); - - if (segmentStartKey.m_controlPoint.m_value != iter->m_controlPoint.m_value) - { - const Vec2 start = Vec2(segmentStartKey.m_time.ToFloat(), segmentStartKey.m_controlPoint.m_value); - const Vec2 end = Vec2(iter->m_time.ToFloat(), iter->m_controlPoint.m_value); - - const QPointF startTransformed = Vec2ToPoint(transformFunc(start)); - const QPointF endTransformed = Vec2ToPoint(transformFunc(end)); - - path.moveTo(startTransformed); - path.lineTo(endTransformed); - } - - if (segmentEndKey.m_controlPoint.m_value != (iter + 1)->m_controlPoint.m_value) - { - const Vec2 start = Vec2(segmentEndKey.m_time.ToFloat(), segmentEndKey.m_controlPoint.m_value); - const Vec2 end = Vec2((iter + 1)->m_time.ToFloat(), (iter + 1)->m_controlPoint.m_value); - - const QPointF startTransformed = Vec2ToPoint(transformFunc(start)); - const QPointF endTransformed = Vec2ToPoint(transformFunc(end)); - - path.moveTo(startTransformed); - path.lineTo(endTransformed); - } - } - } - - QVector dashPattern; - dashPattern << 2 << 10; - - QPainterPathStroker stroker; - stroker.setCapStyle(Qt::RoundCap); - stroker.setDashPattern(dashPattern); - stroker.setWidth(0.5); - - return stroker.createStroke(path); - } - - void DrawPointRect(QPainter& painter, QPointF point, const QColor& color) - { - painter.setBrush(QBrush(color)); - painter.setPen(QColor(0, 0, 0)); - painter.drawRect(QRectF(point - kPointRectExtent, point + kPointRectExtent)); - } - - void DrawKeys(QPainter& painter, const QPalette& palette, const SCurveEditorCurve& curve, ECurveEditorCurveType curveType, AZStd::function transformFunc, const bool bDrawHandles) - { - const QColor tangentColor = CurveEditorHelpers::Interpolate(QColor(), QColor(curve.m_color.r, curve.m_color.g, curve.m_color.b, curve.m_color.a), 0.3f); - const QPen tangentPen = QPen(tangentColor, 2.5); - - for (auto iter = curve.m_keys.begin(); iter != curve.m_keys.end(); ++iter) - { - SCurveEditorKey key = *iter; - - const Vec2 keyPoint = Vec2(key.m_time.ToFloat(), key.m_controlPoint.m_value); - const QPointF transformedKeyPoint = Vec2ToPoint(transformFunc(keyPoint)); - - const bool bIsFirstKey = (iter == curve.m_keys.begin()); - const bool bIsLastKey = (iter == (curve.m_keys.end() - 1)); - const SCurveEditorKey* pLeftKey = (!bIsFirstKey) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pRightKey = (!bIsLastKey) ? &*(iter + 1) : nullptr; - key = pRightKey ? ApplyOutTangentFlags(key, pLeftKey, *pRightKey) : key; - key = pLeftKey ? ApplyInTangentFlags(key, *pLeftKey, pRightKey) : key; - - // For 1D Bezier, we need to ignore the X component - const Vec2 inTangent = (curveType == eCECT_Bezier) ? Vec2(0.0f, key.m_controlPoint.m_inTangent.y) : key.m_controlPoint.m_inTangent; - const Vec2 outTangent = (curveType == eCECT_Bezier) ? Vec2(0.0f, key.m_controlPoint.m_outTangent.y) : key.m_controlPoint.m_outTangent; - - if (key.m_bSelected && (key.m_controlPoint.m_inTangentType != SBezierControlPoint::eTangentType_Step) && !bIsFirstKey && bDrawHandles) - { - // Draw incoming tangent - const Vec2 tangentHandlePoint = keyPoint + inTangent; - const QPointF transformedTangentHandlePoint = Vec2ToPoint(transformFunc(tangentHandlePoint)); - painter.setPen(tangentPen); - painter.drawLine(transformedKeyPoint, transformedTangentHandlePoint); - DrawPointRect(painter, transformedTangentHandlePoint, palette.color(QPalette::Dark)); - } - - if (key.m_bSelected && (key.m_controlPoint.m_outTangentType != SBezierControlPoint::eTangentType_Step) && !bIsLastKey && bDrawHandles) - { - // Draw outgoing tangent - const Vec2 tangentHandlePoint = keyPoint + outTangent; - const QPointF transformedTangentHandlePoint = Vec2ToPoint(transformFunc(tangentHandlePoint)); - painter.setPen(tangentPen); - painter.drawLine(transformedKeyPoint, transformedTangentHandlePoint); - DrawPointRect(painter, transformedTangentHandlePoint, palette.color(QPalette::Dark)); - } - - const QColor pointColor = key.m_bSelected ? palette.color(QPalette::Highlight) : palette.color(QPalette::Dark); - DrawPointRect(painter, transformedKeyPoint, pointColor); - } - } - - void ForEachKey(SCurveEditorContent& content, AZStd::function fun) - { - for (auto iter = content.m_curves.begin(); iter != content.m_curves.end(); ++iter) - { - SCurveEditorCurve& curve = *iter; - for (size_t i = 0; i < curve.m_keys.size(); ++i) - { - fun(curve, curve.m_keys[i]); - } - } - } - -#pragma warning (push) -#pragma warning (disable : 4554) - - Vec2 ClosestPointOnBezierSegment(const Vec2 point, const float t0, const float t1, const float p0, const float p1, const float p2, const float p3) - { - // If values are too close the distance function is too flat to be useful. We just assume the curve is flat then - if ((p0 * p0 + p1 * p1 + p2 * p2 + p3 * p3) < 1e-10f) - { - return Vec2(point.x, p0); - } - - const float deltaTime = (t1 - t0); - const float deltaTimeSq = deltaTime * deltaTime; - - // Those are just the normal cubic Bezier formulas B(t) and B'(t) in collected polynomial form - const P3f cubicBezierPoly = P3f(-p0 + 3.0f * p1 - 3.0f * p2 + p3) + P2f(3.0f * p0 - 6.0f * p1 + 3.0f * p2) + P1f(3.0f * p1 - 3.0f * p0) + p0; - const P2f cubicBezierDerivativePoly = P2f(-3.0f * p0 + 9.0f * p1 - 6.0f * p2 + 3.0f * (p3 - p2)) + P1f(6.0f * p0 - 12.0f * p1 + 6.0f * p2) - 3.0f * p0 + 3.0f * p1; - - // lerp(t, t0, t1) in polynomial form - const P1f timePoly = P1f(deltaTime) + t0; - - // Derivative of the distance function (cubicBezierPoly - point.y) ^ 2 + (timePoly - point.x) ^ 2 - const auto distanceDerivativePoly = (cubicBezierDerivativePoly * (cubicBezierPoly - point.y) + (timePoly - point.x) * deltaTime) * 2.0f; - - // The point of minimum distance must be at one of the roots of the distance derivative or at the start/end of the segment - float checkPoints[7]; - const uint numRoots = distanceDerivativePoly.findroots(0.0f, 1.0f, checkPoints + 2); - - // Start and end of segment - checkPoints[0] = 0.0f; - checkPoints[1] = 1.0f; - - // Find the closest point among all the candidates - Vec2 closestPoint; - float minDistanceSq = std::numeric_limits::max(); - for (uint i = 0; i < numRoots + 2; ++i) - { - const Vec2 rootPoint(Lerp(t0, t1, checkPoints[i]), Bezier::Evaluate(checkPoints[i], p0, p1, p2, p3)); - const float deltaX = rootPoint.x - point.x; - const float deltaY = rootPoint.y - point.y; - const float distSq = deltaX * deltaX + deltaY * deltaY; - if (distSq < minDistanceSq) - { - closestPoint = rootPoint; - minDistanceSq = distSq; - } - } - - return closestPoint; - } - - Vec2 ClosestPointOn2DBezierSegment(const Vec2 point, const Vec2 p0, const Vec2 p1, const Vec2 p2, const Vec2 p3) - { - // If values are too close the distance function is too flat to be useful. We just assume the curve is flat then - if ((p0.y * p0.y + p1.y * p1.y + p2.y * p2.y + p3.y * p3.y) < 1e-10f) - { - return Vec2(point.x, p0.y); - } - - // Those are just the normal cubic Bezier formulas B(t) and B'(t) in collected polynomial form - const P3f xCubicBezierPoly = P3f(-p0.x + 3.0f * p1.x - 3.0f * p2.x + p3.x) + P2f(3.0f * p0.x - 6.0f * p1.x + 3.0f * p2.x) + P1f(3.0f * p1.x - 3.0f * p0.x) + p0.x; - const P2f xCubicBezierDerivativePoly = P2f(-3.0f * p0.x + 9.0f * p1.x - 6.0f * p2.x + 3.0f * (p3.x - p2.x)) + P1f(6.0f * p0.x - 12.0f * p1.x + 6.0f * p2.x) - 3.0f * p0.x + 3.0f * p1.x; - const P3f yCubicBezierPoly = P3f(-p0.y + 3.0f * p1.y - 3.0f * p2.y + p3.y) + P2f(3.0f * p0.y - 6.0f * p1.y + 3.0f * p2.y) + P1f(3.0f * p1.y - 3.0f * p0.y) + p0.y; - const P2f yCubicBezierDerivativePoly = P2f(-3.0f * p0.y + 9.0f * p1.y - 6.0f * p2.y + 3.0f * (p3.y - p2.y)) + P1f(6.0f * p0.y - 12.0f * p1.y + 6.0f * p2.y) - 3.0f * p0.y + 3.0f * p1.y; - - // Derivative of the distance function (yCubicBezierPoly - point.y) ^ 2 + (xCubicBezierPoly - point.x) ^ 2 - const auto distanceDerivativePoly = yCubicBezierDerivativePoly * (yCubicBezierPoly - point.y) + xCubicBezierDerivativePoly * (xCubicBezierPoly - point.x); - - // The point of minimum distance must be at one of the roots of the distance derivative or at the start/end of the segment - float checkPoints[7]; - const uint numRoots = distanceDerivativePoly.findroots(0.0f, 1.0f, checkPoints + 2); - - // Start and end of segment - checkPoints[0] = 0.0f; - checkPoints[1] = 1.0f; - - // Find the closest point among all the candidates - Vec2 closestPoint; - float minDistanceSq = std::numeric_limits::max(); - for (uint i = 0; i < numRoots + 2; ++i) - { - const Vec2 rootPoint(Bezier::Evaluate(checkPoints[i], p0.x, p1.x, p2.x, p3.x), Bezier::Evaluate(checkPoints[i], p0.y, p1.y, p2.y, p3.y)); - const float deltaX = rootPoint.x - point.x; - const float deltaY = rootPoint.y - point.y; - const float distSq = deltaX * deltaX + deltaY * deltaY; - if (distSq < minDistanceSq) - { - closestPoint = rootPoint; - minDistanceSq = distSq; - } - } - - return closestPoint; - } - - // This works for 1D and 2D bezier because the y range of values is not affected by the x bezier in the 2D case. - Range GetBezierSegmentValueRange(const SCurveEditorKey& startKey, const SCurveEditorKey& endKey) - { - const float p0 = startKey.m_controlPoint.m_value; - const float p1 = p0 + startKey.m_controlPoint.m_outTangent.y; - const float p3 = endKey.m_controlPoint.m_value; - const float p2 = p3 + endKey.m_controlPoint.m_inTangent.y; - - Range valueRange(std::min(p0, p3), std::max(p0, p3)); - - const P2f cubicBezierDerivativePoly = P2f(-3.0f * p0 + 9.0f * p1 - 6.0f * p2 + 3.0f * (p3 - p2)) + P1f(6.0f * p0 - 12.0f * p1 + 6.0f * p2) - 3.0f * p0 + 3.0f * p1; - - float roots[2]; - const uint numRoots = cubicBezierDerivativePoly.findroots(0.0f, 1.0f, roots); - for (uint i = 0; i < numRoots; ++i) - { - const float rootValue = Bezier::Evaluate(roots[i], p0, p1, p2, p3); - valueRange.start = std::min(valueRange.start, rootValue); - valueRange.end = std::max(valueRange.end, rootValue); - } - - return valueRange; - } -} - -#pragma warning (pop) - -struct CCurveEditor::SMouseHandler -{ - virtual ~SMouseHandler() = default; - virtual void mousePressEvent(QMouseEvent* pEvent) {} - virtual void mouseDoubleClickEvent(QMouseEvent* pEvent) {} - virtual void mouseMoveEvent(QMouseEvent* pEvent) {} - virtual void mouseReleaseEvent(QMouseEvent* pEvent) {} - virtual void focusOutEvent(QFocusEvent* pEvent) {} - virtual void paintOver(QPainter& painter) {} -}; - -struct CCurveEditor::SSelectionHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - QPoint m_startPoint; - QRect m_rect; - bool m_bAdd; - - SSelectionHandler(CCurveEditor* pCurveEditor, bool bAdd) - : m_pCurveEditor(pCurveEditor) - , m_bAdd(bAdd) {} - - void mousePressEvent(QMouseEvent* pEvent) override - { - m_startPoint = pEvent->pos(); - m_rect = QRect(m_startPoint, m_startPoint + QPoint(1, 1)); - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - m_rect = QRect(m_startPoint, pEvent->pos() + QPoint(1, 1)); - } - - void mouseReleaseEvent(QMouseEvent* pEvent) override - { - m_pCurveEditor->SelectInRect(m_rect); - } - - void paintOver(QPainter& painter) override - { - painter.save(); - QColor highlightColor = m_pCurveEditor->palette().color(QPalette::Highlight); - QColor highlightColorA = QColor(highlightColor.red(), highlightColor.green(), highlightColor.blue(), 128); - painter.setPen(QPen(highlightColor)); - painter.setBrush(QBrush(highlightColorA)); - painter.drawRect(QRectF(m_rect)); - painter.restore(); - } -}; - -struct CCurveEditor::SPanHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - QPoint m_startPoint; - Vec2 m_startTranslation; - - SPanHandler(CCurveEditor* pCurveEditor) - : m_pCurveEditor(pCurveEditor) - { - } - - void mousePressEvent(QMouseEvent* pEvent) override - { - m_startPoint = QPoint(int(pEvent->x()), int(pEvent->y())); - m_startTranslation = m_pCurveEditor->m_translation; - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - const Vec2 windowSize((float)m_pCurveEditor->size().width(), (float)m_pCurveEditor->size().height()); - - const int pixelDeltaX = pEvent->x() - m_startPoint.x(); - const int pixelDeltaY = pEvent->y() - m_startPoint.y(); - - const float deltaX = float(pixelDeltaX) / (windowSize.x); - const float deltaY = float(pixelDeltaY) / (windowSize.y); - - const Vec2 delta(deltaX, deltaY); - m_pCurveEditor->m_translation = m_startTranslation + delta; - m_pCurveEditor->update(); - } -}; - -struct CCurveEditor::SZoomHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - Vec2 m_pivot; - QPoint m_lastPoint; - - SZoomHandler(CCurveEditor* pCurveEditor) - : m_pCurveEditor(pCurveEditor) - { - } - - void mousePressEvent(QMouseEvent* pEvent) override - { - m_lastPoint = QPoint(int(pEvent->x()), int(pEvent->y())); - - const QRect curveArea = m_pCurveEditor->GetCurveArea(); - const float pivotXNormalized = (float)(m_lastPoint.x() - curveArea.left()) / (float)curveArea.width(); - const float pivotYNormalized = (float)(m_lastPoint.y() - curveArea.top()) / (float)curveArea.height(); - m_pivot = Vec2(pivotXNormalized, pivotYNormalized); - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - const Vec2 windowSize((float)m_pCurveEditor->size().width(), (float)m_pCurveEditor->size().height()); - - const int pixelDeltaX = pEvent->x() - m_lastPoint.x(); - const int pixelDeltaY = -(pEvent->y() - m_lastPoint.y()); - m_lastPoint = QPoint(int(pEvent->x()), int(pEvent->y())); - - Vec2& translation = m_pCurveEditor->m_translation; - Vec2& zoom = m_pCurveEditor->m_zoom; - - const float pivotX = (m_pivot.x - translation.x) / zoom.x; - const float pivotY = (m_pivot.y - translation.y) / zoom.y; - - zoom.x *= pow(1.2f, (float)pixelDeltaX * 0.03f); - zoom.y *= pow(1.2f, (float)pixelDeltaY * 0.03f); - - zoom.x = clamp_tpl(zoom.x, kMinZoom, kMaxZoom); - zoom.y = clamp_tpl(zoom.y, kMinZoom, kMaxZoom); - - // Adjust translation so pivot point stays at same x and y position on screen - translation.x += ((m_pivot.x - translation.x) / zoom.x - pivotX) * zoom.x; - translation.y += ((m_pivot.y - translation.y) / zoom.y - pivotY) * zoom.y; - - m_pCurveEditor->update(); - } -}; - -struct CCurveEditor::SScrubHandler - : SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - SAnimTime m_startThumbPosition; - QPoint m_startPoint; - - SScrubHandler(CCurveEditor* pCurveEditor) - : m_pCurveEditor(pCurveEditor) - { - } - - void mousePressEvent(QMouseEvent* ev) override - { - QPoint point = QPoint(ev->pos().x(), ev->pos().y()); - - const Vec2 pointInCurveSpace = TransformPointFromScreen(m_pCurveEditor->m_zoom, m_pCurveEditor->m_translation, m_pCurveEditor->GetCurveArea(), PointToVec2(point)); - - m_pCurveEditor->m_time = clamp_tpl(SAnimTime(pointInCurveSpace.x), m_pCurveEditor->m_timeRange.start, m_pCurveEditor->m_timeRange.end); - m_startThumbPosition = m_pCurveEditor->m_time; - m_startPoint = point; - - m_pCurveEditor->SignalScrub(); - } - - void Apply(QMouseEvent* ev, bool continuous) - { - QPoint point = QPoint(ev->pos().x(), ev->pos().y()); - - bool shift = ev->modifiers().testFlag(Qt::ShiftModifier); - bool control = ev->modifiers().testFlag(Qt::ControlModifier); - - const float deltaX = (float)(point.x() - m_startPoint.x()); - const float width = (float)m_pCurveEditor->size().width(); - float delta = float(deltaX) / (width * m_pCurveEditor->m_zoom.x); - - if (shift) - { - delta *= 0.01f; - } - - if (control) - { - delta *= 0.1f; - } - - m_pCurveEditor->m_time = clamp_tpl(m_startThumbPosition + SAnimTime(delta), m_pCurveEditor->m_timeRange.start, m_pCurveEditor->m_timeRange.end); - m_pCurveEditor->SignalScrub(); - } - - void mouseMoveEvent(QMouseEvent* ev) override - { - Apply(ev, true); - } - - void mouseReleaseEvent(QMouseEvent* ev) override - { - Apply(ev, false); - } -}; - -struct CCurveEditor::SMoveHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - bool m_bCycleSelection; - Vec2 m_startPoint; - SAnimTime m_minSelectedTime; - std::vector m_keyTimes; - std::vector m_keyValues; - - SMoveHandler(CCurveEditor* pCurveEditor, bool bCycleSelection) - : m_pCurveEditor(pCurveEditor) - , m_bCycleSelection(bCycleSelection) - , m_startPoint(0.0f, 0.0f) - {} - - void mousePressEvent(QMouseEvent* pEvent) override - { - const QPoint currentPos = pEvent->pos(); - m_startPoint = TransformPointFromScreen(m_pCurveEditor->m_zoom, m_pCurveEditor->m_translation, m_pCurveEditor->GetCurveArea(), PointToVec2(currentPos)); - StoreKeyPositions(); - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - RestoreKeyPositions(); - - const QPoint currentPos = pEvent->pos(); - const Vec2 transformedPos = TransformPointFromScreen(m_pCurveEditor->m_zoom, m_pCurveEditor->m_translation, m_pCurveEditor->GetCurveArea(), PointToVec2(currentPos)); - const Vec2 offset = transformedPos - m_startPoint; - - SAnimTime deltaTime = SAnimTime(offset.x); - if (m_pCurveEditor->m_bSnapKeys) - { - SAnimTime newMinKeyTime = m_minSelectedTime + deltaTime; - newMinKeyTime = newMinKeyTime.SnapToNearest(m_pCurveEditor->m_frameRate); - deltaTime = newMinKeyTime - m_minSelectedTime; - } - - SCurveEditorContent* pContent = m_pCurveEditor->m_pContent; - for (auto curveIter = pContent->m_curves.begin(); curveIter != pContent->m_curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - - for (auto iter = curve.m_keys.begin(); iter != curve.m_keys.end(); ++iter) - { - if (iter->m_bSelected) - { - iter->m_time += deltaTime; - iter->m_controlPoint.m_value += offset.y; - iter->m_bModified = true; - } - } - - m_pCurveEditor->SortKeys(curve); - } - } - - void focusOutEvent(QFocusEvent* pEvent) override - { - RestoreKeyPositions(); - } - - void mouseReleaseEvent(QMouseEvent* pEvent) override - { - m_pCurveEditor->ContentChanged(); - } - - void StoreKeyPositions() - { - m_minSelectedTime = SAnimTime::Max(); - - SCurveEditorContent* pContent = m_pCurveEditor->m_pContent; - for (auto curveIter = pContent->m_curves.begin(); curveIter != pContent->m_curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - for (auto iter = curve.m_keys.begin(); iter != curve.m_keys.end(); ++iter) - { - if (iter->m_bSelected) - { - m_keyTimes.push_back(iter->m_time); - m_keyValues.push_back(iter->m_controlPoint.m_value); - m_minSelectedTime = min(m_minSelectedTime, iter->m_time); - } - } - } - } - - void RestoreKeyPositions() - { - SCurveEditorContent* pContent = m_pCurveEditor->m_pContent; - - auto timeIter = m_keyTimes.begin(); - auto valueIter = m_keyValues.begin(); - - for (auto curveIter = pContent->m_curves.begin(); curveIter != pContent->m_curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - for (auto iter = curve.m_keys.begin(); iter != curve.m_keys.end(); ++iter) - { - if (iter->m_bSelected) - { - iter->m_time = *(timeIter++); - iter->m_controlPoint.m_value = *(valueIter++); - iter->m_bModified = false; - } - } - } - } -}; - -struct CCurveEditor::SHandleMoveHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - SCurveEditorKey m_appliedHandlesKey; - SCurveEditorKey* m_pKey; - CCurveEditor::ETangent m_tangent; - Vec2 m_startPoint; - Vec2 m_inTangentStartPosition; - Vec2 m_outTangentStartPosition; - SBezierControlPoint::ETangentType m_inTangentStartType; - SBezierControlPoint::ETangentType m_outTangentStartType; - float m_inTangentStartLength; - float m_outTangentStartLength; - - SHandleMoveHandler(CCurveEditor* pCurveEditor, SCurveEditorKey appliedHandlesKey, SCurveEditorKey* pKey, CCurveEditor::ETangent tangent) - : m_pCurveEditor(pCurveEditor) - , m_appliedHandlesKey(appliedHandlesKey) - , m_pKey(pKey) - , m_tangent(tangent) - , m_inTangentStartPosition(ZERO) - , m_inTangentStartType(SBezierControlPoint::eTangentType_Auto) - , m_inTangentStartLength(0.0f) - , m_outTangentStartPosition(ZERO) - , m_outTangentStartType(SBezierControlPoint::eTangentType_Auto) - , m_outTangentStartLength(0.0f) - { - } - - void mousePressEvent(QMouseEvent* pEvent) override - { - const QPoint currentPos = pEvent->pos(); - m_startPoint = TransformPointFromScreen(m_pCurveEditor->m_zoom, m_pCurveEditor->m_translation, m_pCurveEditor->GetCurveArea(), PointToVec2(currentPos)); - - m_inTangentStartPosition = m_appliedHandlesKey.m_controlPoint.m_inTangent; - m_inTangentStartType = m_appliedHandlesKey.m_controlPoint.m_inTangentType; - m_inTangentStartLength = m_inTangentStartPosition.GetLength(); - m_outTangentStartPosition = m_appliedHandlesKey.m_controlPoint.m_outTangent; - m_outTangentStartType = m_appliedHandlesKey.m_controlPoint.m_outTangentType; - m_outTangentStartLength = m_outTangentStartPosition.GetLength(); - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - const QPoint currentPos = pEvent->pos(); - const Vec2 transformedPos = TransformPointFromScreen(m_pCurveEditor->m_zoom, m_pCurveEditor->m_translation, m_pCurveEditor->GetCurveArea(), PointToVec2(currentPos)); - - if (m_tangent == CCurveEditor::ETangent_In) - { - const Vec2 newPos = m_inTangentStartPosition + (transformedPos - m_startPoint); - - m_pKey->m_controlPoint.m_inTangent = newPos; - m_pKey->m_controlPoint.m_inTangentType = SBezierControlPoint::eTangentType_Custom; - - if (!m_pKey->m_controlPoint.m_bBreakTangents) - { - m_pKey->m_controlPoint.m_outTangent = -newPos.GetNormalizedSafe() * m_outTangentStartLength; - m_pKey->m_controlPoint.m_outTangentType = SBezierControlPoint::eTangentType_Custom; - } - } - else - { - const Vec2 newPos = m_outTangentStartPosition + (transformedPos - m_startPoint); - - m_pKey->m_controlPoint.m_outTangent = newPos; - m_pKey->m_controlPoint.m_outTangentType = SBezierControlPoint::eTangentType_Custom; - - if (!m_pKey->m_controlPoint.m_bBreakTangents) - { - m_pKey->m_controlPoint.m_inTangent = -newPos.GetNormalizedSafe() * m_inTangentStartLength; - m_pKey->m_controlPoint.m_inTangentType = SBezierControlPoint::eTangentType_Custom; - } - } - - m_pKey->m_bModified = true; - } - - void focusOutEvent(QFocusEvent* pEvent) override - { - m_pKey->m_controlPoint.m_inTangent = m_inTangentStartPosition; - m_pKey->m_controlPoint.m_inTangentType = m_inTangentStartType; - m_pKey->m_controlPoint.m_outTangent = m_outTangentStartPosition; - m_pKey->m_controlPoint.m_outTangentType = m_outTangentStartType; - m_pKey->m_bModified = false; - } - - void mouseReleaseEvent(QMouseEvent* pEvent) override - { - m_pCurveEditor->ContentChanged(); - } -}; - -CCurveEditor::CCurveEditor(QWidget* parent) - : QWidget(parent) - , m_pContent(nullptr) - , m_pMouseHandler(nullptr) - , m_curveType(eCECT_Bezier) - , m_frameRate(SAnimTime::eFrameRate_30fps) - , m_bWeighted(false) - , m_bHandlesVisible(true) - , m_bRulerVisible(true) - , m_bTimeSliderVisible(true) - , m_bGridVisible(false) - , m_bSnapTime(false) - , m_bSnapKeys(false) - , m_time(SAnimTime(0)) - , m_zoom(0.5f, 0.5f) - , m_translation(0.5f, 0.5f) - , m_timeRange(SAnimTime::Min(), SAnimTime::Max()) - , m_valueRange(-1e10f, 1e10f) -{ - setMouseTracking(true); -} - -CCurveEditor::~CCurveEditor() -{ -} - -void CCurveEditor::SetContent(SCurveEditorContent* pContent) -{ - m_pContent = pContent; - update(); -} - -void CCurveEditor::SetTime(const SAnimTime time) -{ - m_time = clamp_tpl<>(time, m_timeRange.start, m_timeRange.end); - update(); -} - -void CCurveEditor::SetTimeRange(const SAnimTime start, const SAnimTime end) -{ - if (start <= end) - { - m_timeRange = TRange(start, end); - update(); - } -} - -void CCurveEditor::SetValueRange(const float min, const float max) -{ - if (min <= max) - { - m_valueRange = Range(min, max); - update(); - } -} - -void CCurveEditor::ZoomToTimeRange(const float start, const float end) -{ - const float delta = (end - start); - - if (delta > 1e-10f) - { - m_zoom.x = 1.0f / (end - start); - m_translation.x = start / (start - end); - } - else - { - // Just center around value with zoom = 1.0f - m_zoom.x = 1.0f; - m_translation.x = 0.5f - start; - } -} - -void CCurveEditor::ZoomToValueRange(const float min, const float max) -{ - const float delta = (max - min); - - if (delta > 1e-10f) - { - m_zoom.y = 1.0f / (max - min); - m_translation.y = max / (max - min); - } - else - { - // Just center around value with zoom = 1.0f - m_zoom.y = 1.0f; - m_translation.y = 0.5f + min; - } -} - -void CCurveEditor::paintEvent(QPaintEvent* pEvent) -{ - QPainter painter(this); - painter.setRenderHint(QPainter::Antialiasing); - painter.translate(0.5f, 0.5f); - - const QPalette& palette = this->palette(); - - auto transformFunc = [&](Vec2 point) - { - return TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), point); - }; - - const QColor rangeHighlightColor = CurveEditorHelpers::Interpolate(palette.color(QPalette::Foreground), palette.color(QPalette::Background), 0.95f); - const QRectF rangesRect(Vec2ToPoint(transformFunc(Vec2(m_timeRange.start.ToFloat(), m_valueRange.start))), Vec2ToPoint(transformFunc(Vec2(m_timeRange.end.ToFloat(), m_valueRange.end)))); - painter.setPen(QPen(Qt::NoPen)); - painter.setBrush(rangeHighlightColor); - painter.drawRect(rangesRect); - - if (m_bGridVisible) - { - DrawGrid(painter, palette); - } - - if (m_pContent) - { - const QPen extrapolatedCurvePen = QPen(palette.color(QPalette::Highlight)); - - TCurveEditorCurves& curves = m_pContent->m_curves; - for (auto curveIter = curves.begin(); curveIter != curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - - painter.setBrush(QBrush(Qt::NoBrush)); - const QPen curvePen = QPen(QColor(curve.m_color.r, curve.m_color.g, curve.m_color.b, curve.m_color.a), 2); - const QPen narrowCurvePen = QPen(QColor(curve.m_color.r, curve.m_color.g, curve.m_color.b, curve.m_color.a)); - - const QPainterPath extrapolatedPath = CreateExtrapolatedPathFromCurve(curve, transformFunc, width()); - painter.setPen(narrowCurvePen); - painter.drawPath(extrapolatedPath); - - const QPainterPath discontinuityPath = CreateDiscontinuityPathFromCurve(curve, m_curveType, transformFunc); - painter.setPen(narrowCurvePen); - painter.drawPath(discontinuityPath); - - if (curve.m_keys.size() > 0) - { - const QPainterPath path = CreatePathFromCurve(curve, m_curveType, transformFunc); - painter.setPen(curvePen); - painter.drawPath(path); - - DrawKeys(painter, palette, curve, m_curveType, transformFunc, m_bHandlesVisible); - } - } - } - - if (m_pMouseHandler) - { - m_pMouseHandler->paintOver(painter); - } - - DrawingPrimitives::SRulerOptions rulerOptions; - rulerOptions.m_rect = QRect(0, -1, size().width(), kRulerHeight + 2); - rulerOptions.m_visibleRange = Range(-m_translation.x / m_zoom.x, (1.0f - m_translation.x) / m_zoom.x); - rulerOptions.m_rulerRange = rulerOptions.m_visibleRange; - rulerOptions.m_markHeight = kRulerMarkHeight; - rulerOptions.m_shadowSize = kRulerShadowHeight; - - int rulerPrecision; - DrawingPrimitives::DrawRuler(painter, palette, rulerOptions, &rulerPrecision); - - if (m_pContent && isEnabled()) - { - DrawingPrimitives::STimeSliderOptions timeSliderOptions; - timeSliderOptions.m_rect = rect(); - timeSliderOptions.m_precision = rulerPrecision; - timeSliderOptions.m_position = transformFunc(Vec2(m_time.ToFloat(), 0.0f)).x; - timeSliderOptions.m_time = m_time.ToFloat(); - timeSliderOptions.m_bHasFocus = hasFocus(); - DrawingPrimitives::DrawTimeSlider(painter, palette, timeSliderOptions); - } -} - -void CCurveEditor::mousePressEvent(QMouseEvent* pEvent) -{ - setFocus(); - - if (pEvent->button() == Qt::LeftButton) - { - LeftButtonMousePressEvent(pEvent); - } - else if (pEvent->button() == Qt::MiddleButton) - { - MiddleButtonMousePressEvent(pEvent); - } - else if (pEvent->button() == Qt::RightButton) - { - RightButtonMousePressEvent(pEvent); - } -} - -void CCurveEditor::mouseDoubleClickEvent(QMouseEvent* pEvent) -{ - if (pEvent->button() == Qt::LeftButton) - { - auto curveHitPair = HitDetectCurve(pEvent->pos()); - if (curveHitPair.first) - { - AddPointToCurve(curveHitPair.second, curveHitPair.first); - setCursor(QCursor(Qt::SizeAllCursor)); - } - } -} - -void CCurveEditor::DrawGrid(QPainter& painter, const QPalette& palette) -{ - using namespace DrawingPrimitives; - - QColor gridColor = CurveEditorHelpers::Interpolate(palette.color(QPalette::Dark), palette.color(QPalette::Button), 0.5f); - gridColor.setAlpha(128); - const QColor textColor = palette.color(QPalette::BrightText); - - const Range horizontalVisibleRange = Range(-m_translation.x / m_zoom.x, (1.0f - m_translation.x) / m_zoom.x); - const Range verticalVisibleRange = Range((m_translation.y - 1.0f) / m_zoom.y, m_translation.y / m_zoom.y); - - const int height = size().height(); - const int width = size().width(); - - int verticalRulerPrecision; - - std::vector horizontalTicks = CalculateTicks(width, horizontalVisibleRange, horizontalVisibleRange, nullptr, nullptr); - std::vector verticalTicks = CalculateTicks(height, verticalVisibleRange, verticalVisibleRange, &verticalRulerPrecision, nullptr); - - char format[16] = ""; - sprintf_s(format, "%%.%df", verticalRulerPrecision); - - const QPen gridPen(gridColor, 1.0); - painter.setPen(gridPen); - - for (const STick& tick : horizontalTicks) - { - if (!tick.m_bTenth) - { - const int x = tick.m_position; - painter.drawLine(x, kRulerHeight, x, height); - } - } - - for (const STick& tick : verticalTicks) - { - if (!tick.m_bTenth) - { - const int y = height - tick.m_position; - painter.drawLine(0, y, width, y); - } - } - - const QPen textPen(textColor); - painter.setPen(textPen); - - QString str; - for (const STick& tick : verticalTicks) - { - if (!tick.m_bTenth) - { - const int y = height - tick.m_position; - str.sprintf(format, tick.m_value); - painter.drawText(5, y - 4, str); - } - } -} - -void CCurveEditor::LeftButtonMousePressEvent(QMouseEvent* pEvent) -{ - const bool bCtrlPressed = (pEvent->modifiers() & Qt::CTRL) != 0; - const bool bAltPressed = (pEvent->modifiers() & Qt::ALT) != 0; - - if (pEvent->y() < kRulerHeight) - { - m_pMouseHandler.reset(new SScrubHandler(this)); - m_pMouseHandler->mousePressEvent(pEvent); - } - else - { - if (bCtrlPressed) - { - auto curveHitPair = HitDetectCurve(pEvent->pos()); - if (curveHitPair.first) - { - AddPointToCurve(curveHitPair.second, curveHitPair.first); - setCursor(QCursor(Qt::SizeAllCursor)); - } - } - else if (bAltPressed) - { - auto curveKeyPair = HitDetectKey(pEvent->pos()); - if (curveKeyPair.first) - { - curveKeyPair.second->m_bDeleted = true; - ContentChanged(); - } - } - else - { - auto curveKeyPair = HitDetectKey(pEvent->pos()); - auto handleKeyTuple = HitDetectHandle(pEvent->pos()); - - if (std::get<0>(handleKeyTuple)) - { - m_pMouseHandler.reset(new SHandleMoveHandler(this, std::get<1>(handleKeyTuple), std::get<2>(handleKeyTuple), std::get<3>(handleKeyTuple))); - } - else if (curveKeyPair.first) - { - bool useExistingSelection = curveKeyPair.second->m_bSelected; - if (!useExistingSelection) - { - ForEachKey(*m_pContent, [](SCurveEditorCurve& curve, SCurveEditorKey& key) - { - key.m_bSelected = false; - }); - curveKeyPair.second->m_bSelected = true; - } - - m_pMouseHandler.reset(new SMoveHandler(this, false)); - } - else - { - m_pMouseHandler.reset(new SSelectionHandler(this, false)); - } - - m_pMouseHandler->mousePressEvent(pEvent); - } - } - - update(); -} - -void CCurveEditor::MiddleButtonMousePressEvent(QMouseEvent* pEvent) -{ - const bool bShiftPressed = (pEvent->modifiers() & Qt::SHIFT) != 0; - - if (!bShiftPressed) - { - m_pMouseHandler.reset(new SPanHandler(this)); - } - else - { - m_pMouseHandler.reset(new SZoomHandler(this)); - } - - m_pMouseHandler->mousePressEvent(pEvent); - update(); -} - -void CCurveEditor::RightButtonMousePressEvent(QMouseEvent* pEvent) -{ -} - -void CCurveEditor::mouseMoveEvent(QMouseEvent* pEvent) -{ - if (m_pMouseHandler) - { - m_pMouseHandler->mouseMoveEvent(pEvent); - } - else - { - if (HitDetectKey(pEvent->pos()).first || std::get<0>(HitDetectHandle(pEvent->pos()))) - { - setCursor(QCursor(Qt::SizeAllCursor)); - } - else - { - setCursor(QCursor()); - } - } - - update(); -} - -void CCurveEditor::mouseReleaseEvent(QMouseEvent* pEvent) -{ - if (m_pMouseHandler) - { - m_pMouseHandler->mouseReleaseEvent(pEvent); - m_pMouseHandler.reset(); - update(); - } -} - -void CCurveEditor::focusOutEvent(QFocusEvent* pEvent) -{ - if (m_pMouseHandler) - { - m_pMouseHandler->focusOutEvent(pEvent); - m_pMouseHandler.reset(); - update(); - } -} - -void CCurveEditor::wheelEvent(QWheelEvent* pEvent) -{ - Vec2 windowSize((float)size().width(), (float)size().height()); - windowSize.y = (windowSize.y > 0.0f) ? windowSize.y : 1.0f; - - const QRect curveArea = GetCurveArea(); - const float mouseXNormalized = (float)(pEvent->x() - curveArea.left()) / (float)curveArea.width(); - const float mouseYNormalized = (float)(pEvent->y() - curveArea.top()) / (float)curveArea.height(); - - const float pivotX = (mouseXNormalized - m_translation.x) / m_zoom.x; - const float pivotY = (mouseYNormalized - m_translation.y) / m_zoom.y; - - m_zoom *= pow(1.2f, (float)pEvent->delta() * 0.01f); - m_zoom.x = clamp_tpl(m_zoom.x, kMinZoom, kMaxZoom); - m_zoom.y = clamp_tpl(m_zoom.y, kMinZoom, kMaxZoom); - - // Adjust translation so pivot point stays at same x and y position on screen - m_translation.x += ((mouseXNormalized - m_translation.x) / m_zoom.x - pivotX) * m_zoom.x; - m_translation.y += ((mouseYNormalized - m_translation.y) / m_zoom.y - pivotY) * m_zoom.y; - - update(); -} - -void CCurveEditor::keyPressEvent(QKeyEvent* pEvent) -{ - if (!m_pContent) - { - return; - } - - QKeySequence key(pEvent->key()); - - if (key == QKeySequence(Qt::Key_Delete)) - { - OnDeleteSelectedKeys(); - } - - update(); -} - -void CCurveEditor::SetCurveType(ECurveEditorCurveType curveType) -{ - m_curveType = curveType; - update(); -} - -void CCurveEditor::SetHandlesVisible(bool bVisible) -{ - m_bHandlesVisible = bVisible; - update(); -} - -void CCurveEditor::SetRulerVisible(bool bVisible) -{ - m_bRulerVisible = bVisible; - update(); -} - -void CCurveEditor::SetTimeSliderVisible(bool bVisible) -{ - m_bTimeSliderVisible = bVisible; - update(); -} - -void CCurveEditor::SetGridVisible(bool bVisible) -{ - m_bGridVisible = bVisible; - update(); -} - -void CCurveEditor::SelectInRect(const QRect& rect) -{ - if (!m_pContent) - { - return; - } - - ForEachKey(*m_pContent, [&](SCurveEditorCurve& curve, SCurveEditorKey& key) - { - const Vec2 screenPoint = TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), Vec2(key.m_time.ToFloat(), key.m_controlPoint.m_value)); - key.m_bSelected = rect.contains((int)screenPoint.x, (int)screenPoint.y); - }); - - update(); - SignalContentChanged(); -} - -std::pair CCurveEditor::HitDetectCurve(const QPoint point) -{ - if (!m_pContent) - { - return std::make_pair(nullptr, Vec2(ZERO)); - } - - SCurveEditorCurve* pNearestCurve = nullptr; - Vec2 closestPoint = Vec2(ZERO); - - float nearestDistance = std::numeric_limits::max(); - for (auto iter = m_pContent->m_curves.rbegin(); iter != m_pContent->m_curves.rend(); ++iter) - { - SCurveEditorCurve& curve = *iter; - const Vec2 closestPointOnCurve = ClosestPointOnCurve(PointToVec2(point), curve, m_curveType); - - const float distance = (PointToVec2(point) - closestPointOnCurve).GetLength(); - if (distance < nearestDistance) - { - nearestDistance = distance; - pNearestCurve = &curve; - closestPoint = closestPointOnCurve; - } - } - - if (nearestDistance <= kHitDistance) - { - return std::make_pair(pNearestCurve, TransformPointFromScreen(m_zoom, m_translation, GetCurveArea(), closestPoint)); - } - - return std::make_pair(nullptr, Vec2(ZERO)); -} - -std::pair CCurveEditor::HitDetectKey(const QPoint point) -{ - if (!m_pContent) - { - return std::make_pair(nullptr, nullptr); - } - - for (auto curvesIter = m_pContent->m_curves.rbegin(); curvesIter != m_pContent->m_curves.rend(); ++curvesIter) - { - SCurveEditorCurve& curve = *curvesIter; - for (auto iter = curve.m_keys.rbegin(); iter != curve.m_keys.rend(); ++iter) - { - SCurveEditorKey& key = *iter; - const Vec2 keyPoint = Vec2(key.m_time.ToFloat(), key.m_controlPoint.m_value); - const Vec2 transformedPoint = TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), keyPoint); - if ((transformedPoint - PointToVec2(point)).GetLength() <= kHitDistance) - { - return std::make_pair(&curve, &key); - } - } - } - - return std::make_pair(nullptr, nullptr); -} - -std::tuple CCurveEditor::HitDetectHandle(const QPoint point) -{ - if (!m_pContent || !m_bHandlesVisible) - { - return std::make_tuple(nullptr, SCurveEditorKey(), nullptr, ETangent_In); - } - - for (auto curvesIter = m_pContent->m_curves.rbegin(); curvesIter != m_pContent->m_curves.rend(); ++curvesIter) - { - SCurveEditorCurve& curve = *curvesIter; - for (auto iter = curve.m_keys.begin(); iter != curve.m_keys.end(); ++iter) - { - SCurveEditorKey key = *iter; - - const bool bIsFirstKey = (iter == curve.m_keys.begin()); - const bool bIsLastKey = (iter == (curve.m_keys.end() - 1)); - const SCurveEditorKey* pLeftKey = (!bIsFirstKey) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pRightKey = (!bIsLastKey) ? &*(iter + 1) : nullptr; - key = pRightKey ? ApplyOutTangentFlags(key, pLeftKey, *pRightKey) : key; - key = pLeftKey ? ApplyInTangentFlags(key, *pLeftKey, pRightKey) : key; - - const Vec2 inTangent = (m_curveType == eCECT_Bezier) ? Vec2(0.0f, key.m_controlPoint.m_inTangent.y) : key.m_controlPoint.m_inTangent; - const Vec2 outTangent = (m_curveType == eCECT_Bezier) ? Vec2(0.0f, key.m_controlPoint.m_outTangent.y) : key.m_controlPoint.m_outTangent; - - const Vec2 keyPoint = Vec2(key.m_time.ToFloat(), key.m_controlPoint.m_value); - - if (!bIsFirstKey && (key.m_controlPoint.m_inTangentType != SBezierControlPoint::eTangentType_Step)) - { - const Vec2 tangentHandlePoint = keyPoint + inTangent; - const Vec2 transformedTangentHandlePoint = TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), tangentHandlePoint); - if ((transformedTangentHandlePoint - PointToVec2(point)).GetLength() <= kHitDistance) - { - return std::make_tuple(&curve, key, &(*iter), ETangent_In); - } - } - - if (!bIsLastKey && (key.m_controlPoint.m_outTangentType != SBezierControlPoint::eTangentType_Step)) - { - const Vec2 tangentHandlePoint = keyPoint + outTangent; - const Vec2 transformedTangentHandlePoint = TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), tangentHandlePoint); - if ((transformedTangentHandlePoint - PointToVec2(point)).GetLength() <= kHitDistance) - { - return std::make_tuple(&curve, key, &(*iter), ETangent_Out); - } - } - } - } - - return std::make_tuple(nullptr, SCurveEditorKey(), nullptr, ETangent_In); -} - -// Input and output are in screen space -Vec2 CCurveEditor::ClosestPointOnCurve(const Vec2 point, const SCurveEditorCurve& curve, const ECurveEditorCurveType curveType) -{ - auto transformFunc = [&](Vec2 point) - { - return TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), point); - }; - - if (curve.m_keys.size() == 0) - { - const Vec2 pointOnCurve = transformFunc(Vec2(0.0f, curve.m_defaultValue)); - return Vec2(point.x, pointOnCurve.y); - } - - Vec2 closestPoint; - float minDistance = std::numeric_limits::max(); - - const Vec2 startKeyTransformed = transformFunc(Vec2(curve.m_keys.front().m_time.ToFloat(), curve.m_keys.front().m_controlPoint.m_value)); - if (point.x < startKeyTransformed.x) - { - const float distanceToCurve = std::abs(point.y - startKeyTransformed.y); - if (distanceToCurve < minDistance) - { - closestPoint = Vec2(point.x, startKeyTransformed.y); - minDistance = distanceToCurve; - } - } - - const Vec2 endKeyTransformed = transformFunc(Vec2(curve.m_keys.back().m_time.ToFloat(), curve.m_keys.back().m_controlPoint.m_value)); - if (point.x > endKeyTransformed.x) - { - const float distanceToCurve = std::abs(point.y - endKeyTransformed.y); - if (distanceToCurve < minDistance) - { - closestPoint = Vec2(point.x, endKeyTransformed.y); - minDistance = distanceToCurve; - } - } - - const auto endIter = curve.m_keys.end() - 1; - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - const SCurveEditorKey* pKeyLeftOfSegment = (iter != curve.m_keys.begin()) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pKeyRightOfSegment = (iter != (curve.m_keys.end() - 2)) ? &*(iter + 2) : nullptr; - - const SCurveEditorKey segmentStartKey = ApplyOutTangentFlags(*iter, pKeyLeftOfSegment, *(iter + 1)); - const SCurveEditorKey segmentEndKey = ApplyInTangentFlags(*(iter + 1), *iter, pKeyRightOfSegment); - - const Vec2 p0 = transformFunc(Vec2(segmentStartKey.m_time.ToFloat(), segmentStartKey.m_controlPoint.m_value)); - const Vec2 p3 = transformFunc(Vec2(segmentEndKey.m_time.ToFloat(), segmentEndKey.m_controlPoint.m_value)); - const Vec2 p1 = transformFunc(Vec2(segmentStartKey.m_time.ToFloat() + segmentStartKey.m_controlPoint.m_outTangent.x, - segmentStartKey.m_controlPoint.m_value + segmentStartKey.m_controlPoint.m_outTangent.y)); - const Vec2 p2 = transformFunc(Vec2(segmentEndKey.m_time.ToFloat() + segmentEndKey.m_controlPoint.m_inTangent.x, - segmentEndKey.m_controlPoint.m_value + segmentEndKey.m_controlPoint.m_inTangent.y)); - - const Vec2 closestOnSegment = (curveType == eCECT_Bezier) ? ClosestPointOnBezierSegment(point, p0.x, p3.x, p0.y, p1.y, p2.y, p3.y) : ClosestPointOn2DBezierSegment(point, p0, p1, p2, p3); - const float distanceToSegment = (closestOnSegment - point).GetLength(); - if (distanceToSegment < minDistance) - { - closestPoint = closestOnSegment; - minDistance = distanceToSegment; - } - } - - return closestPoint; -} - -void CCurveEditor::ContentChanged() -{ - SignalContentChanged(); - - DeleteMarkedKeys(); - - ForEachKey(*m_pContent, [](SCurveEditorCurve& curve, SCurveEditorKey& key) - { - key.m_bModified = false; - }); - - update(); -} - -void CCurveEditor::DeleteMarkedKeys() -{ - if (m_pContent) - { - for (auto iter = m_pContent->m_curves.begin(); iter != m_pContent->m_curves.end(); ++iter) - { - SCurveEditorCurve& curve = *iter; - for (auto keyIter = curve.m_keys.begin(); keyIter != curve.m_keys.end(); ) - { - if (keyIter->m_bDeleted) - { - keyIter = curve.m_keys.erase(keyIter); - } - else - { - ++keyIter; - } - } - } - } -} - -void CCurveEditor::AddPointToCurve(const Vec2 point, SCurveEditorCurve* pCurve) -{ - SCurveEditorKey key; - key.m_time = SAnimTime(point.x); - if (m_bSnapKeys) - { - key.m_time.SnapToNearest(m_frameRate); - } - key.m_controlPoint.m_value = point.y; - key.m_bAdded = true; - pCurve->m_keys.push_back(key); - - SortKeys(*pCurve); - ContentChanged(); -} - -void CCurveEditor::SortKeys(SCurveEditorCurve& curve) -{ - std::stable_sort(curve.m_keys.begin(), curve.m_keys.end(), [](const SCurveEditorKey& a, const SCurveEditorKey& b) - { - return a.m_time < b.m_time; - }); -} - -void CCurveEditor::OnDeleteSelectedKeys() -{ - ForEachKey(*m_pContent, [](SCurveEditorCurve& curve, SCurveEditorKey& key) - { - key.m_bDeleted = key.m_bDeleted || key.m_bSelected; - }); - - ContentChanged(); -} - -void CCurveEditor::OnSetSelectedKeysTangentAuto() -{ - SetSelectedKeysTangentType(ETangent_In, SBezierControlPoint::eTangentType_Auto); - SetSelectedKeysTangentType(ETangent_Out, SBezierControlPoint::eTangentType_Auto); -} - -void CCurveEditor::OnSetSelectedKeysInTangentZero() -{ - SetSelectedKeysTangentType(ETangent_In, SBezierControlPoint::eTangentType_Zero); -} - -void CCurveEditor::OnSetSelectedKeysInTangentStep() -{ - SetSelectedKeysTangentType(ETangent_In, SBezierControlPoint::eTangentType_Step); -} - -void CCurveEditor::OnSetSelectedKeysInTangentLinear() -{ - SetSelectedKeysTangentType(ETangent_In, SBezierControlPoint::eTangentType_Linear); -} - -void CCurveEditor::OnSetSelectedKeysOutTangentZero() -{ - SetSelectedKeysTangentType(ETangent_Out, SBezierControlPoint::eTangentType_Zero); -} - -void CCurveEditor::OnSetSelectedKeysOutTangentStep() -{ - SetSelectedKeysTangentType(ETangent_Out, SBezierControlPoint::eTangentType_Step); -} - -void CCurveEditor::OnSetSelectedKeysOutTangentLinear() -{ - SetSelectedKeysTangentType(ETangent_Out, SBezierControlPoint::eTangentType_Linear); -} - -void CCurveEditor::OnFitCurvesHorizontally() -{ - if (m_pContent) - { - bool bAnyKeyFound = false; - SAnimTime timeMin = SAnimTime::Max(); - SAnimTime timeMax = SAnimTime::Min(); - - TCurveEditorCurves& curves = m_pContent->m_curves; - for (auto curveIter = curves.begin(); curveIter != curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - if (curve.m_keys.size() > 0) - { - bAnyKeyFound = true; - timeMin = std::min(curve.m_keys.front().m_time, timeMin); - timeMax = std::max(curve.m_keys.back().m_time, timeMax); - } - } - - if (!bAnyKeyFound) - { - timeMin = m_timeRange.start; - timeMax = m_timeRange.end; - } - - ZoomToTimeRange(timeMin.ToFloat(), timeMax.ToFloat()); - - // Adjust zoom and translation depending on kFitMargin - const float pivot = (0.5f - m_translation.x) / m_zoom.x; - m_zoom.x /= 1.0f + 2.0f * (kFitMargin / GetCurveArea().width()); - m_translation.x += ((0.5f - m_translation.x) / m_zoom.x - pivot) * m_zoom.x; - } - - update(); -} - -void CCurveEditor::OnFitCurvesVertically() -{ - if (m_pContent) - { - bool bAnyKeyFound = false; - float valueMin = std::numeric_limits::max(); - float valueMax = -std::numeric_limits::max(); - - TCurveEditorCurves& curves = m_pContent->m_curves; - for (auto curveIter = curves.begin(); curveIter != curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - - if (curve.m_keys.size() > 1) - { - const auto endIter = curve.m_keys.end() - 1; - - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - bAnyKeyFound = true; - - const SCurveEditorKey* pKeyLeftOfSegment = (iter != curve.m_keys.begin()) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pKeyRightOfSegment = (iter != (curve.m_keys.end() - 2)) ? &*(iter + 2) : nullptr; - - const SCurveEditorKey segmentStartKey = ApplyOutTangentFlags(*iter, pKeyLeftOfSegment, *(iter + 1)); - const SCurveEditorKey segmentEndKey = ApplyInTangentFlags(*(iter + 1), *iter, pKeyRightOfSegment); - - const Range valueRange = GetBezierSegmentValueRange(segmentStartKey, segmentEndKey); - valueMin = std::min(valueMin, valueRange.start); - valueMax = std::max(valueMax, valueRange.end); - } - } - else if (curve.m_keys.size() == 1) - { - bAnyKeyFound = true; - valueMin = valueMax = curve.m_keys[0].m_controlPoint.m_value; - } - } - - if (!bAnyKeyFound) - { - valueMin = -0.5f; - valueMax = 0.5f; - } - - ZoomToValueRange(valueMin, valueMax); - - // Adjust zoom and translation depending on kFitMargin - const float pivot = (0.5f - m_translation.y) / m_zoom.y; - m_zoom.y /= 1.0f + 2.0f * (kFitMargin / GetCurveArea().height()); - m_translation.y += ((0.5f - m_translation.y) / m_zoom.y - pivot) * m_zoom.y; - } - - update(); -} - -void CCurveEditor::OnBreakTangents() -{ - if (m_pContent) - { - ForEachKey(*m_pContent, [&](SCurveEditorCurve& curve, SCurveEditorKey& key) - { - if (key.m_bSelected) - { - key.m_controlPoint.m_bBreakTangents = true; - } - }); - } - - SignalContentChanged(); -} - -void CCurveEditor::OnUnifyTangents() -{ - if (m_pContent) - { - ForEachKey(*m_pContent, [&](SCurveEditorCurve& curve, SCurveEditorKey& key) - { - if (key.m_bSelected) - { - key.m_controlPoint.m_bBreakTangents = false; - } - }); - } - - SignalContentChanged(); -} - -void CCurveEditor::SetSelectedKeysTangentType(const ETangent tangent, const SBezierControlPoint::ETangentType type) -{ - if (m_pContent) - { - ForEachKey(*m_pContent, [&](SCurveEditorCurve& curve, SCurveEditorKey& key) - { - if (key.m_bSelected) - { - if (tangent == ETangent_In) - { - key.m_controlPoint.m_inTangentType = type; - } - else - { - key.m_controlPoint.m_outTangentType = type; - } - } - }); - - update(); - } - - SignalContentChanged(); -} - -QRect CCurveEditor::GetCurveArea() -{ - const uint rulerAreaHeight = m_bRulerVisible ? kRulerHeight : 0; - return QRect(0, rulerAreaHeight, width(), height() - rulerAreaHeight); -} - -void CCurveEditor::FillWithCurveToolsAndConnect(QToolBar* pToolBar) -{ - pToolBar->addAction(QIcon(":/Icons/CurveEditor/auto.png"), "Set in and out tangents to auto", this, SLOT(OnSetSelectedKeysTangentAuto())); - pToolBar->addSeparator(); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/zero_in.png"), "Set in tangent to zero", this, SLOT(OnSetSelectedKeysInTangentZero())); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/step_in.png"), "Set in tangent to step", this, SLOT(OnSetSelectedKeysInTangentStep())); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/linear_in.png"), "Set in tangent to linear", this, SLOT(OnSetSelectedKeysInTangentLinear())); - pToolBar->addSeparator(); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/zero_out.png"), "Set out tangent to zero", this, SLOT(OnSetSelectedKeysOutTangentZero())); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/step_out.png"), "Set out tangent to step", this, SLOT(OnSetSelectedKeysOutTangentStep())); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/linear_out.png"), "Set out tangent to linear", this, SLOT(OnSetSelectedKeysOutTangentLinear())); - pToolBar->addSeparator(); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/fit_horizontal.png"), "Fit curves horizontally", this, SLOT(OnFitCurvesHorizontally())); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/fit_vertical.png"), "Fit curves vertically", this, SLOT(OnFitCurvesVertically())); - pToolBar->addSeparator(); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/break.png"), "Break tangents", this, SLOT(OnBreakTangents())); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/unify.png"), "Unify tangents", this, SLOT(OnUnifyTangents())); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditor_38.h b/Code/Sandbox/Plugins/EditorCommon/CurveEditor_38.h deleted file mode 100644 index f0c5da608b..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditor_38.h +++ /dev/null @@ -1,154 +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 "CurveEditorContent.h" -#include -#include -#include - -class QToolBar; - -enum ECurveEditorCurveType -{ - eCECT_Bezier, - // 2D Bezier curves are used for better curve control, the editor - // will enforce that the resulting curve is always 1D. - eCECT_2DBezier, -}; - -namespace CurveEditorHelpers -{ - // Picks a nice color value for a curve. Wraps around after 4. - EDITOR_COMMON_API ColorB GetCurveColor(const uint n); -} - -class EDITOR_COMMON_API CCurveEditor - : public QWidget -{ - Q_OBJECT -public: - CCurveEditor(QWidget* parent); - ~CCurveEditor(); - - void SetContent(SCurveEditorContent* pContent); - SCurveEditorContent* Content() const { return m_pContent; } - - SAnimTime Time() const { return m_time; } - void SetTime(const SAnimTime time); - - // The background in the time and value range will be drawn a bit brighter to indicate where keys - // should be placed. The curve editor does not enforce that the curves actually stay in those ranges. - void SetTimeRange(const SAnimTime start, const SAnimTime end); - void SetValueRange(const float min, const float max); - - void ZoomToTimeRange(const float start, const float end); - void ZoomToValueRange(const float min, const float max); - - void SetCurveType(ECurveEditorCurveType curveType); - void SetWeighted(bool bWeighted); - void SetHandlesVisible(bool bVisible); - void SetRulerVisible(bool bVisible); - void SetTimeSliderVisible(bool bVisible); - void SetGridVisible(bool bVisible); - void SetFrameRate(SAnimTime::EFrameRate frameRate) { m_frameRate = frameRate; } - void SetTimeSnapping(bool snapTime) { m_bSnapTime = snapTime; } - void SetKeySnapping(bool snapKeys) { m_bSnapKeys = snapKeys; } - - // Tools added to tool bar depend on options above - void FillWithCurveToolsAndConnect(QToolBar* pToolBar); - - void paintEvent(QPaintEvent* pEvent) override; - void mousePressEvent(QMouseEvent* pEvent) override; - void mouseDoubleClickEvent(QMouseEvent* pEvent) override; - void mouseMoveEvent(QMouseEvent* pEvent) override; - void mouseReleaseEvent(QMouseEvent* pEvent) override; - void focusOutEvent(QFocusEvent* pEvent) override; - void wheelEvent(QWheelEvent* pEvent) override; - void keyPressEvent(QKeyEvent* pEvent) override; - -signals: - void SignalContentChanged(); - void SignalScrub(); - -public slots: - void OnDeleteSelectedKeys(); - void OnSetSelectedKeysTangentAuto(); - void OnSetSelectedKeysInTangentZero(); - void OnSetSelectedKeysInTangentStep(); - void OnSetSelectedKeysInTangentLinear(); - void OnSetSelectedKeysOutTangentZero(); - void OnSetSelectedKeysOutTangentStep(); - void OnSetSelectedKeysOutTangentLinear(); - void OnFitCurvesHorizontally(); - void OnFitCurvesVertically(); - void OnBreakTangents(); - void OnUnifyTangents(); - -private: - struct SMouseHandler; - struct SSelectionHandler; - struct SPanHandler; - struct SZoomHandler; - struct SMoveHandler; - struct SHandleMoveHandler; - struct SScrubHandler; - enum ETangent; - - void DrawGrid(QPainter& painter, const QPalette& palette); - - void LeftButtonMousePressEvent(QMouseEvent* pEvent); - void MiddleButtonMousePressEvent(QMouseEvent* pEvent); - void RightButtonMousePressEvent(QMouseEvent* pEvent); - - void SelectInRect(const QRect& rect); - - void ContentChanged(); - void DeleteMarkedKeys(); - - std::pair HitDetectCurve(const QPoint point); - std::pair HitDetectKey(const QPoint point); - std::tuple HitDetectHandle(const QPoint point); - Vec2 ClosestPointOnCurve(const Vec2 point, const SCurveEditorCurve& curve, const ECurveEditorCurveType curveType); - - void AddPointToCurve(Vec2 point, SCurveEditorCurve* pCurve); - void SortKeys(SCurveEditorCurve& curve); - - QRect GetCurveArea(); - - enum ETangent - { - ETangent_In, - ETangent_Out - }; - - void SetSelectedKeysTangentType(const ETangent tangent, const SBezierControlPoint::ETangentType type); - - SCurveEditorContent* m_pContent; - std::unique_ptr m_pMouseHandler; - - ECurveEditorCurveType m_curveType; - SAnimTime::EFrameRate m_frameRate; - bool m_bWeighted : 1; - bool m_bHandlesVisible : 1; - bool m_bRulerVisible : 1; - bool m_bTimeSliderVisible : 1; - bool m_bGridVisible : 1; - bool m_bSnapTime : 1; - bool m_bSnapKeys : 1; - - SAnimTime m_time; - Vec2 m_zoom; - Vec2 m_translation; - TRange m_timeRange; - Range m_valueRange; -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/DisplayViewportAdapter.cpp b/Code/Sandbox/Plugins/EditorCommon/DisplayViewportAdapter.cpp deleted file mode 100644 index 3d6a33fd6a..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/DisplayViewportAdapter.cpp +++ /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. -* -*/ - -#include "EditorCommon_precompiled.h" -//Cry -#include - -//Editor -#include -#include - -//Local -#include "QViewport.h" -#include "DisplayViewportAdapter.h" - -CDisplayViewportAdapter::CDisplayViewportAdapter(QViewport* viewport) - : m_viewport(viewport) -{ - m_screenMatrix.SetIdentity(); -} - -void CDisplayViewportAdapter::Update() -{ -} - -const Matrix34& CDisplayViewportAdapter::GetScreenTM() const -{ - return m_screenMatrix; -} - -float CDisplayViewportAdapter::GetScreenScaleFactor(const Vec3& position) const -{ - float dist = m_viewport->Camera()->GetPosition().GetDistance(position); - if (dist < m_viewport->Camera()->GetNearPlane()) - { - dist = m_viewport->Camera()->GetNearPlane(); - } - return dist; -} - -float CDisplayViewportAdapter::GetScreenScaleFactor([[maybe_unused]] const CCamera& camera, [[maybe_unused]] const Vec3& object_position) -{ - return 1; -} - -bool CDisplayViewportAdapter::HitTestLine(const Vec3& lineP1, const Vec3& lineP2, const QPoint& hitpoint, int pixelRadius, float* pToCameraDistance) const -{ - float dist = GetDistanceToLine(lineP1, lineP2, hitpoint); - if (dist <= pixelRadius) - { - if (pToCameraDistance) - { - Vec3 raySrc, rayDir; - ViewToWorldRay(hitpoint, raySrc, rayDir); - Vec3 rayTrg = raySrc + rayDir * 10000.0f; - - Vec3 pa, pb; - float mua, mub; - LineLineIntersect(lineP1, lineP2, raySrc, rayTrg, pa, pb, mua, mub); - *pToCameraDistance = mub; - } - - return true; - } - - return false; -} - -float CDisplayViewportAdapter::GetDistanceToLine(const Vec3& lineP1, const Vec3& lineP2, const QPoint& point) const -{ - QPoint p1 = WorldToView(lineP1); - QPoint p2 = WorldToView(lineP2); - - return PointToLineDistance2D( - Vec3(float(p1.x()), float(p1.y()), 0), - Vec3(float(p2.x()), float(p2.y()), 0), - Vec3(float(point.x()), float(point.y()), 0)); -} - -CBaseObjectsCache* CDisplayViewportAdapter::GetVisibleObjectsCache() -{ - return 0; -} - -bool CDisplayViewportAdapter::IsBoundsVisible([[maybe_unused]] const AABB& box) const -{ - return false; -} - -void CDisplayViewportAdapter::GetPerpendicularAxis(EAxis* axis, bool* is2D) const -{ - *axis = AXIS_NONE; - *is2D = false; -} - -const Matrix34& CDisplayViewportAdapter::GetViewTM() const -{ - m_viewMatrix = m_viewport->Camera()->GetViewMatrix(); - return m_viewMatrix; -} - -QPoint CDisplayViewportAdapter::WorldToView(const Vec3& worldPoint) const -{ - return m_viewport->ProjectToScreen(worldPoint); -} - -QPoint CDisplayViewportAdapter::WorldToViewParticleEditor(const Vec3& worldPoint, [[maybe_unused]] int width, [[maybe_unused]] int height) const -{ - return m_viewport->ProjectToScreen(worldPoint); -} - -Vec3 CDisplayViewportAdapter::WorldToView3D([[maybe_unused]] const Vec3& worldPoint, [[maybe_unused]] int flags) const -{ - return Vec3(0.0f, 0.0f, 0.0f); -} - -Vec3 CDisplayViewportAdapter::ViewToWorld([[maybe_unused]] const QPoint& vp, [[maybe_unused]] bool* collideWithTerrain, [[maybe_unused]] bool onlyTerrain, [[maybe_unused]] bool bSkipVegetation, [[maybe_unused]] bool bTestRenderMesh, [[maybe_unused]] bool* collideWithObject) const -{ - return Vec3(0.0f, 0.0f, 0.0f); -} - -void CDisplayViewportAdapter::ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& rayDir) const -{ - Ray ray; - // this can fail for number of reasons - if (!m_viewport->ScreenToWorldRay(&ray, vp.x(), vp.y())) - { - // return some "safe" default that will not cause FPE - raySrc = m_viewport->Camera()->GetPosition(); - rayDir = m_viewport->Camera()->GetViewdir(); - - // the interface should be changed to accommodate for error - return; - } - raySrc = ray.origin; - rayDir = ray.direction; -} - -float CDisplayViewportAdapter::GetGridStep() const -{ - return 1.0f; -} - -float CDisplayViewportAdapter::GetAspectRatio() const -{ - int w, h; - GetDimensions(&w, &h); - if (h != 0) - { - return float(w) / h; - } - else - { - return 1.0f; - } -} - -const Plane* CDisplayViewportAdapter::GetConstructionPlane() const -{ - return 0; -} - -void CDisplayViewportAdapter::ScreenToClient([[maybe_unused]] QPoint& pt) const -{ -} - -void CDisplayViewportAdapter::GetDimensions(int* width, int* height) const -{ - if (width) - { - *width = m_viewport->Width(); - } - if (height) - { - *height = m_viewport->Height(); - } -} - -void CDisplayViewportAdapter::setRay([[maybe_unused]] QPoint& vp, [[maybe_unused]] Vec3& raySrc, [[maybe_unused]] Vec3& rayDir) -{ -} - -void CDisplayViewportAdapter::setHitcontext([[maybe_unused]] QPoint& vp, [[maybe_unused]] Vec3& raySrc, [[maybe_unused]] Vec3& rayDir) -{ -} diff --git a/Code/Sandbox/Plugins/EditorCommon/DisplayViewportAdapter.h b/Code/Sandbox/Plugins/EditorCommon/DisplayViewportAdapter.h deleted file mode 100644 index 9b1d8bc27b..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/DisplayViewportAdapter.h +++ /dev/null @@ -1,64 +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 - -//Cry -#include -#include "Cry_Matrix34.h" -#include "Cry_Vector3.h" - -//Editor -#include "Include/IDisplayViewport.h" - -//Local -#include "EditorCommonAPI.h" - -class EDITOR_COMMON_API QViewport; - -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -class EDITOR_COMMON_API CDisplayViewportAdapter - : public ::IDisplayViewport -{ -public: -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING - CDisplayViewportAdapter(QViewport* viewport); - - void Update() override; - const Matrix34& GetScreenTM() const override; - float GetScreenScaleFactor(const Vec3& position) const override; - float GetScreenScaleFactor(const CCamera& camera, const Vec3& object_position) override; - bool HitTestLine(const Vec3& lineP1, const Vec3& lineP2, const QPoint& hitpoint, int pixelRadius, float* pToCameraDistance = 0) const override; - float GetDistanceToLine(const Vec3& lineP1, const Vec3& lineP2, const QPoint& point) const override; - CBaseObjectsCache* GetVisibleObjectsCache() override; - bool IsBoundsVisible(const AABB& box) const override; - void GetPerpendicularAxis(EAxis* axis, bool* is2D) const override; - const Matrix34& GetViewTM() const override; - QPoint WorldToView(const Vec3& worldPoint) const override; - QPoint WorldToViewParticleEditor(const Vec3& worldPoint, int width, int height) const override; - Vec3 WorldToView3D(const Vec3& worldPoint, int flags = 0) const override; - Vec3 ViewToWorld(const QPoint& vp, bool* collideWithTerrain = nullptr, bool onlyTerrain = false, bool bSkipVegetation = false, bool bTestRenderMesh = false, bool* collideWithObject = nullptr) const override; - void ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& rayDir) const override; - float GetGridStep() const override; - float GetAspectRatio() const override; - const Plane* GetConstructionPlane() const override; - void ScreenToClient(QPoint& pt) const override; - void GetDimensions(int* width, int* height) const override; - void setRay(QPoint& vp, Vec3& raySrc, Vec3& rayDir) override; - void setHitcontext(QPoint& vp, Vec3& raySrc, Vec3& rayDir) override; - -private: - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - mutable Matrix34 m_viewMatrix; - Matrix34 m_screenMatrix; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - QViewport* m_viewport; -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/DockTitleBarWidget.cpp b/Code/Sandbox/Plugins/EditorCommon/DockTitleBarWidget.cpp index e7de4904d1..06b3c29104 100644 --- a/Code/Sandbox/Plugins/EditorCommon/DockTitleBarWidget.cpp +++ b/Code/Sandbox/Plugins/EditorCommon/DockTitleBarWidget.cpp @@ -16,13 +16,16 @@ #include #include -static QColor Interpolate(const QColor& a, const QColor& b, float k) +namespace DockTitleBarInterpolate { - float mk = 1.0f - k; - return QColor(aznumeric_cast(a.red() * mk + b.red() * k), - aznumeric_cast(a.green() * mk + b.green() * k), - aznumeric_cast(a.blue() * mk + b.blue() * k), - aznumeric_cast(a.alpha() * mk + b.alpha() * k)); + static QColor Interpolate(const QColor& a, const QColor& b, float k) + { + float mk = 1.0f - k; + return QColor(aznumeric_cast(a.red() * mk + b.red() * k), + aznumeric_cast(a.green() * mk + b.green() * k), + aznumeric_cast(a.blue() * mk + b.blue() * k), + aznumeric_cast(a.alpha() * mk + b.alpha() * k)); + } } class CDockWidgetTitleButton @@ -60,7 +63,7 @@ public: p.setRenderHint(QPainter::Antialiasing, true); QRect r = rect().adjusted(2, 2, -3, -3); p.translate(0.5f, 0.5f); - QColor color = Interpolate(palette().color(QPalette::Window), palette().color(QPalette::Shadow), 0.2f); + QColor color = DockTitleBarInterpolate::Interpolate(palette().color(QPalette::Window), palette().color(QPalette::Shadow), 0.2f); p.setBrush(QBrush(color)); p.setPen(Qt::NoPen); p.drawRoundedRect(r, 4, 4, Qt::AbsoluteSize); diff --git a/Code/Sandbox/Plugins/EditorCommon/DrawingPrimitives/Ruler.cpp b/Code/Sandbox/Plugins/EditorCommon/DrawingPrimitives/Ruler.cpp index 18439e3aa4..6a070b364b 100644 --- a/Code/Sandbox/Plugins/EditorCommon/DrawingPrimitives/Ruler.cpp +++ b/Code/Sandbox/Plugins/EditorCommon/DrawingPrimitives/Ruler.cpp @@ -101,7 +101,7 @@ namespace DrawingPrimitives void DrawTicks(const std::vector& ticks, QPainter& painter, const QPalette& palette, const STickOptions& options) { - QColor midDark = Interpolate(palette.color(QPalette::Dark), palette.color(QPalette::Button), 0.5f); + QColor midDark = DrawingPrimitives::Interpolate(palette.color(QPalette::Dark), palette.color(QPalette::Button), 0.5f); painter.setPen(QPen(midDark)); const int height = options.m_rect.height(); @@ -149,13 +149,13 @@ namespace DrawingPrimitives painter.fillRect(shadowRect, upperBrush); } - painter.fillRect(options.m_rect, Interpolate(palette.color(QPalette::Button), palette.color(QPalette::Midlight), 0.25f)); + painter.fillRect(options.m_rect, DrawingPrimitives::Interpolate(palette.color(QPalette::Button), palette.color(QPalette::Midlight), 0.25f)); if (options.m_drawBackgroundCallback) { options.m_drawBackgroundCallback(); } - QColor midDark = Interpolate(palette.color(QPalette::Dark), palette.color(QPalette::Button), 0.5f); + QColor midDark = DrawingPrimitives::Interpolate(palette.color(QPalette::Dark), palette.color(QPalette::Button), 0.5f); painter.setPen(QPen(midDark)); QFont font; diff --git a/Code/Sandbox/Plugins/EditorCommon/EditorCommon.qrc b/Code/Sandbox/Plugins/EditorCommon/EditorCommon.qrc deleted file mode 100644 index c9dc7c4283..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/EditorCommon.qrc +++ /dev/null @@ -1,15 +0,0 @@ - - - Icons/CurveEditor/auto.png - Icons/CurveEditor/fit_horizontal.png - Icons/CurveEditor/fit_vertical.png - Icons/CurveEditor/linear_in.png - Icons/CurveEditor/linear_out.png - Icons/CurveEditor/step_in.png - Icons/CurveEditor/step_out.png - Icons/CurveEditor/zero_in.png - Icons/CurveEditor/zero_out.png - Icons/CurveEditor/break.png - Icons/CurveEditor/unify.png - - diff --git a/Code/Sandbox/Plugins/EditorCommon/Events/EventManager.cpp b/Code/Sandbox/Plugins/EditorCommon/Events/EventManager.cpp deleted file mode 100644 index 793cd119f0..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Events/EventManager.cpp +++ /dev/null @@ -1,144 +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 "EditorCommon_precompiled.h" -#include "EventManager.h" -#include "Serialization/JSONIArchive.h" -#include "Serialization/JSONOArchive.h" - -CEventManager* CEventManager::ms_pEventManager; - -CEventManager::CEventManager() - : m_nextAddress(0) - , m_nextHandlerId(0) -{ - if (ms_pEventManager) - { - CryFatalError("There should be only one event manager instance"); - } - - ms_pEventManager = this; -} - -void CEventManager::Init([[maybe_unused]] SSystemGlobalEnvironment* env) -{ -} - -CEventManager* CEventManager::GetInstance() -{ - return ms_pEventManager; -} - -uint CEventManager::GetAddressId(const char* name) -{ - auto findIter = m_nameToAddressMap.find(name); - if (findIter != m_nameToAddressMap.end()) - { - return findIter->second; - } - - uint newId = m_nextAddress++; - m_nameToAddressMap[name] = newId; - return newId; -} - -uint CEventManager::GetUniqueAddressId() -{ - return m_nextAddress++; -} - -void CEventManager::SendEventRaw(const uint address, const char* eventName, const char* message) const -{ - SendEventImplementation(address, eventName, message, DynArray()); -} - -void CEventManager::SendEventRaw(const uint address, const char* eventName, const char* message, const DynArray& excludedHandlers) const -{ - SendEventImplementation(address, eventName, message, excludedHandlers); -} - -void CEventManager::SendEventImplementation(const uint address, const string& eventName, const string& message, const DynArray& excludedHandlers) const -{ - auto handlerFindIter = m_messageRoutingMap.find(std::make_pair(address, eventName)); - if (handlerFindIter != m_messageRoutingMap.end()) - { - const std::vector >& handlers = handlerFindIter->second; - - for (uint i = 0; i < handlers.size(); ++i) - { - if (!stl::find(excludedHandlers, handlers[i].first)) - { - handlers[i].second(message); - } - } - } -} - -bool CEventManager::CanDeliverRaw(const uint address, const char* eventName) const -{ - auto handlerFindIter = m_messageRoutingMap.find(std::make_pair(address, eventName)); - if (handlerFindIter != m_messageRoutingMap.end()) - { - const std::vector >& handlers = handlerFindIter->second; - return !handlers.empty(); - } - - return false; -} - -CEventConnection CEventManager::AddEventCallbackRaw(const uint address, const char* eventName, TEventHandlerFunc callback) -{ - const uint handlerId = m_nextHandlerId++; - m_messageRoutingMap[std::make_pair(address, eventName)].push_back(std::make_pair(handlerId, callback)); - return CEventConnection(address, eventName, handlerId); -} - -string CEventManager::SerializeMessageToJSON(const Serialization::SStruct& ref) const -{ - Serialization::JSONOArchive oArchive; - oArchive(ref); - return oArchive.buffer(); -} - -void CEventManager::DeserializeFromJSON(const Serialization::SStruct& ref, const string& json) -{ - Serialization::JSONIArchive iArchive; - if (iArchive.open(json.data(), json.size())) - { - iArchive(ref); - } -} - -void CEventConnection::Disconnect() -{ - if (m_bConnected) - { - auto& messageMap = CEventManager::GetInstance()->m_messageRoutingMap; - auto findIter = messageMap.find(std::make_pair(m_address, m_eventName)); - - if (findIter != messageMap.end()) - { - stl::find_and_erase_if(findIter->second, [=](const std::pair& h) - { - return h.first == m_handlerId; - }); - } - - if (findIter->second.empty()) - { - messageMap.erase(findIter); - } - - Reset(); - } -} diff --git a/Code/Sandbox/Plugins/EditorCommon/Events/EventManager.h b/Code/Sandbox/Plugins/EditorCommon/Events/EventManager.h deleted file mode 100644 index ad35d4e0e8..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Events/EventManager.h +++ /dev/null @@ -1,204 +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_EDITORCOMMON_EVENTS_EVENTMANAGER_H -#define CRYINCLUDE_EDITORCOMMON_EVENTS_EVENTMANAGER_H -#pragma once - - -#include "platform.h" - -#include "EditorCommonAPI.h" -#include "IEditor.h" - -#include "Serialization/IArchive.h" - -struct SSystemGlobalEnvironment; - -class CEventConnection -{ - friend class CEventManager; - friend class CScopedEventConnection; - -public: - CEventConnection() - : m_bConnected(false) {} - - EDITOR_COMMON_API void Disconnect(); - - uint GetHandlerId() const { return m_handlerId; } - -private: - CEventConnection(const uint address, const string& eventName, const uint handlerId) - : m_address(address) - , m_eventName(eventName) - , m_handlerId(handlerId) - , m_bConnected(true) {} - - void Reset() - { - m_bConnected = false; - m_address = 0; - m_handlerId = 0; - m_eventName.clear(); - } - - void Move(CEventConnection& other) - { - m_bConnected = other.m_bConnected; - m_address = other.m_address; - m_handlerId = other.m_handlerId; - m_eventName.swap(other.m_eventName); - other.Reset(); - } - - bool m_bConnected; - uint m_address; - uint m_handlerId; - string m_eventName; -}; - -class CScopedEventConnection - : public CEventConnection -{ -public: - CScopedEventConnection() - : CEventConnection() {} - - CScopedEventConnection(CScopedEventConnection&& connection) - { - Move(connection); - } - - CScopedEventConnection(CEventConnection&& connection) - { - Move(connection); - } - - CScopedEventConnection& operator =(CEventConnection&& connection) - { - if (&connection != this) - { - Disconnect(); - Move(connection); - } - return *this; - } - - ~CScopedEventConnection() { Disconnect(); } - -private: - CScopedEventConnection(const CScopedEventConnection&); // no implementation - CScopedEventConnection& operator =(const CScopedEventConnection&); // no implementation -}; - -class EDITOR_COMMON_API CEventManager -{ - friend class CEventConnection; - -public: - CEventManager(); - - static CEventManager* GetInstance(); - - void Init(SSystemGlobalEnvironment* pEnv); - - // Registers an address and returns its ID. Multiple event handlers can listen to the same address, allowing broadcasts. - uint GetAddressId(const char* name); - - // Registers a new unique address - uint GetUniqueAddressId(); - -public: - - // Sends an event to an address - // - // TMessageType must be a serializable struct - // - template - void SendEvent(const uint address, const TMessageType& message) - { - const string json = SerializeMessageToJSON(Serialization::SStruct(message)); - SendEventRaw(address, TMessageType::GetName(), json); - } - - template - void SendEvent(const uint address, const TMessageType& message, const DynArray& excludedHandlers) const - { - const string json = SerializeMessageToJSON(Serialization::SStruct(message)); - SendEventRaw(address, TMessageType::GetName(), json, excludedHandlers); - } - - // For sending a raw JSON message. - void SendEventRaw(const uint address, const char* eventName, const char* message) const; - void SendEventRaw(const uint address, const char* eventName, const char* message, const DynArray& excludedHandlers) const; - - // Tests if a call to SendEvent would actually send a message (there is someone listening to this message) - bool CanDeliverRaw(const uint address, const char* eventName) const; - template - bool CanDeliver(const uint address) const - { - const char* pEventName = TMessageType::GetName(); - return CanDeliverRaw(address, pEventName); - } - - // This should be the most common way to add an event callback - // - // This example will install an event handler for OnEvent(const SMessageType &message) that is sent to a specific address: - // CEventManager::GetInstance()->AddEventCallback(componentId, this, &CEventHandler::OnEvent); - // - // TMessageType must be a serializable struct - // - // Returns a CEventConnection. The callback is removed when this object is destroyed. - // - template - CEventConnection AddEventCallback(const uint address, TClassType* pThis, void (TClassType::* pMethod)(const TMessageType&)) - { - return AddEventCallback(address, std::bind(pMethod, pThis, std::placeholders::_1)); - } - - // Same as above, but you can pass in any function object that takes TMessageType& as an argument directly. - // - template - CEventConnection AddEventCallback(const uint address, std::function callback) - { - return AddEventCallbackRaw(address, TMessageType::GetName(), [=](const string& json) - { - TMessageType message; - DeserializeFromJSON(Serialization::SStruct(message), json); - callback(message); - }); - } - - // This can be used if raw parsing of JSON is preferred. - typedef std::function TEventHandlerFunc; - CEventConnection AddEventCallbackRaw(const uint componentId, const char* eventName, TEventHandlerFunc callback); - -private: - void SendEventImplementation(const uint address, const string& eventName, const string& message, const DynArray& excludedHandlers) const; - - string SerializeMessageToJSON(const Serialization::SStruct& ref) const; - void DeserializeFromJSON(const Serialization::SStruct& ref, const string& json); - - uint m_nextAddress; - uint m_nextHandlerId; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - std::map > m_nameToAddressMap; - std::map, std::vector > > m_messageRoutingMap; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - static CEventManager* ms_pEventManager; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_EVENTS_EVENTMANAGER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/ListSelectionDialog.cpp b/Code/Sandbox/Plugins/EditorCommon/ListSelectionDialog.cpp deleted file mode 100644 index 13c0bf5d50..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/ListSelectionDialog.cpp +++ /dev/null @@ -1,224 +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 "EditorCommon_precompiled.h" -#include "Serialization/ClassFactory.h" -#include "Serialization/Pointers.h" -#include "Serialization/IArchive.h" -#include "ListSelectionDialog.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "IResourceSelectorHost.h" - -#include "DeepFilterProxyModel.h" - -// --------------------------------------------------------------------------- - -ListSelectionDialog::ListSelectionDialog(QWidget* parent) - : QDialog(parent) - , m_currentColumn(0) -{ - setWindowTitle("Choose..."); - setWindowModality(Qt::ApplicationModal); - - QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom); - setLayout(layout); - - QBoxLayout* filterBox = new QBoxLayout(QBoxLayout::LeftToRight); - layout->addLayout(filterBox); - { - filterBox->addWidget(new QLabel("Filter:", this), 0); - filterBox->addWidget(m_filterEdit = new QLineEdit(this), 1); - connect(m_filterEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onFilterChanged(const QString&))); - m_filterEdit->installEventFilter(this); - } - - QBoxLayout* infoBox = new QBoxLayout(QBoxLayout::LeftToRight); - layout->addLayout(infoBox); - - m_model = new QStandardItemModel(); - m_model->setColumnCount(1); - m_model->setHeaderData(0, Qt::Horizontal, "Name", Qt::DisplayRole); - - m_filterModel = new DeepFilterProxyModel(this); - m_filterModel->setSourceModel(m_model); - m_filterModel->setDynamicSortFilter(true); - - m_tree = new QTreeView(this); - //m_tree->setColumnCount(3); - m_tree->setModel(m_filterModel); - - m_tree->header()->setStretchLastSection(false); -#if QT_VERSION >= 0x50000 - m_tree->header()->setSectionResizeMode(0, QHeaderView::Stretch); -#else - m_tree->header()->setResizeMode(0, QHeaderView::Stretch); -#endif - //m_tree->header()->resizeSection(0, 80); - connect(m_tree, SIGNAL(activated(const QModelIndex&)), this, SLOT(onActivated(const QModelIndex&))); - - layout->addWidget(m_tree, 1); - - QDialogButtonBox* buttons = new QDialogButtonBox(this); - buttons->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(buttons, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttons, SIGNAL(rejected()), this, SLOT(reject())); - layout->addWidget(buttons, 0); -} - -bool ListSelectionDialog::eventFilter(QObject* obj, QEvent* event) -{ - if (obj == m_filterEdit && event->type() == QEvent::KeyPress) - { - QKeyEvent* keyEvent = (QKeyEvent*)event; - if (keyEvent->key() == Qt::Key_Down || - keyEvent->key() == Qt::Key_Up || - keyEvent->key() == Qt::Key_PageDown || - keyEvent->key() == Qt::Key_PageUp) - { - QCoreApplication::sendEvent(m_tree, event); - return true; - } - } - return QDialog::eventFilter(obj, event); -} - -void ListSelectionDialog::onFilterChanged(const QString& str) -{ - m_filterModel->setFilterString(str); - m_filterModel->invalidate(); - m_tree->expandAll(); - - QModelIndex currentSource = m_filterModel->mapToSource(m_tree->selectionModel()->currentIndex()); - if (!currentSource.isValid() || !m_filterModel->matchFilter(currentSource.row(), currentSource.parent())) - { - QModelIndex firstMatchingIndex = m_filterModel->findFirstMatchingIndex(QModelIndex()); - if (firstMatchingIndex.isValid()) - { - m_tree->selectionModel()->setCurrentIndex(firstMatchingIndex, QItemSelectionModel::SelectCurrent); - } - } -} - -void ListSelectionDialog::onActivated(const QModelIndex& index) -{ - m_tree->setCurrentIndex(index); - accept(); -} - -QSize ListSelectionDialog::sizeHint() const -{ - return QSize(600, 900); -} - -void ListSelectionDialog::SetColumnText(int column, const char* text) -{ - if (column >= m_model->columnCount()) - { - int oldColumnCount = m_model->columnCount(); - m_model->setColumnCount(column + 1); - for (int i = oldColumnCount; i <= column; ++i) - { -#if QT_VERSION >= 0x50000 - m_tree->header()->setSectionResizeMode(i, QHeaderView::Interactive); - #else - m_tree->header()->setResizeMode(i, QHeaderView::Interactive); - #endif - m_tree->header()->resizeSection(i, 40); - } - } - m_model->setHeaderData(column, Qt::Horizontal, text, Qt::DisplayRole); -} - -void ListSelectionDialog::SetColumnWidth(int column, int width) -{ - if (column >= m_model->columnCount()) - { - return; - } - m_tree->header()->resizeSection(column, width); -} - - -void ListSelectionDialog::AddRow(const char* name) -{ - AddRow(name, QIcon()); -} - -void ListSelectionDialog::AddRow(const char* name, const QIcon& icon) -{ - QStandardItem* item = new QStandardItem(name); - item->setEditable(false); - item->setData(name); - item->setIcon(icon); - - QList items; - items.append(item); - - m_model->appendRow(items); - m_currentColumn = 1; - m_firstColumnToItem[name] = item; -} - -void ListSelectionDialog::AddRowColumn(const char* text) -{ - int itemCount = m_model->rowCount(QModelIndex()); - if (itemCount == 0) - { - return; - } - - QStandardItem* item = new QStandardItem(); - item->setText(QString::fromLocal8Bit(text)); - if (QStandardItem* lastItem = m_model->item(itemCount - 1, 0)) - { - item->setData(lastItem->data()); - } - item->setEditable(false); - m_model->setItem(itemCount - 1, m_currentColumn, item); - ++m_currentColumn; -} - -QString ListSelectionDialog::ChooseItem(const QString& currentValue) -{ - m_tree->expandAll(); - - if (exec() == QDialog::Accepted && m_tree->selectionModel()->currentIndex().isValid()) - { - QModelIndex currentIndex = m_tree->selectionModel()->currentIndex(); - QModelIndex sourceCurrentIndex = m_filterModel->mapToSource(currentIndex); - QStandardItem* item = m_model->itemFromIndex(sourceCurrentIndex); - if (item) - { - m_chosenItem = item->data().toString().toUtf8(); - return m_chosenItem.constData(); - } - } - return currentValue; -} - -// --------------------------------------------------------------------------- - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/ListSelectionDialog.h b/Code/Sandbox/Plugins/EditorCommon/ListSelectionDialog.h deleted file mode 100644 index 5a21d92b5d..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/ListSelectionDialog.h +++ /dev/null @@ -1,73 +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_EDITORCOMMON_LISTSELECTIONDIALOG_H -#define CRYINCLUDE_EDITORCOMMON_LISTSELECTIONDIALOG_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "EditorCommonAPI.h" -#include -#include -#endif - -class DeepFilterProxyModel; -class QLineEdit; -class QModelIndex; -class QStandardItemModel; -class QStandardItem; -class QString; -class QTreeView; -class QWidget; -class QByteArray; - -class EDITOR_COMMON_API ListSelectionDialog - : public QDialog -{ - Q_OBJECT - -public: - ListSelectionDialog(QWidget* parent); - void SetColumnText(int column, const char* text); - void SetColumnWidth(int column, int width); - - void AddRow(const char* firstColumnValue); - void AddRow(const char* firstColumnValue, const QIcon& icon); - void AddRowColumn(const char* value); - - QString ChooseItem(const QString& currentValue); - - QSize sizeHint() const override; - -protected slots: - void onActivated(const QModelIndex& index); - void onFilterChanged(const QString&); - -protected: - bool eventFilter(QObject* obj, QEvent* event); - -private: - QTreeView* m_tree; - QStandardItemModel* m_model; - DeepFilterProxyModel* m_filterModel; - typedef QMap StringToItem; - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - StringToItem m_firstColumnToItem; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - QLineEdit* m_filterEdit; - QByteArray m_chosenItem; - int m_currentColumn; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_LISTSELECTIONDIALOG_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Platform/Common/UnixLike/QPropertyTree/Unicode_UnixLike.cpp b/Code/Sandbox/Plugins/EditorCommon/Platform/Common/UnixLike/QPropertyTree/Unicode_UnixLike.cpp deleted file mode 100644 index 89ab3276f9..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Platform/Common/UnixLike/QPropertyTree/Unicode_UnixLike.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates - -#include - -#include -#include - -string fromWideChar(const wchar_t* wstr) -{ - return QString::fromWCharArray(wstr).toUtf8().data(); -} - -wstring toWideChar(const char* str) -{ - QString s = QString::fromUtf8(str); - - std::vector result(s.size()+1); - s.toWCharArray(&result[0]); - return &result[0]; -} - diff --git a/Code/Sandbox/Plugins/EditorCommon/Platform/Linux/platform_linux_files.cmake b/Code/Sandbox/Plugins/EditorCommon/Platform/Linux/platform_linux_files.cmake deleted file mode 100644 index 5bfcbe55a6..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Platform/Linux/platform_linux_files.cmake +++ /dev/null @@ -1,14 +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 - ../Common/UnixLike/QPropertyTree/Unicode_UnixLike.cpp -) diff --git a/Code/Sandbox/Plugins/EditorCommon/Platform/Mac/platform_mac_files.cmake b/Code/Sandbox/Plugins/EditorCommon/Platform/Mac/platform_mac_files.cmake deleted file mode 100644 index 5bfcbe55a6..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Platform/Mac/platform_mac_files.cmake +++ /dev/null @@ -1,14 +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 - ../Common/UnixLike/QPropertyTree/Unicode_UnixLike.cpp -) diff --git a/Code/Sandbox/Plugins/EditorCommon/Platform/Windows/QPropertyTree/Unicode_Windows.cpp b/Code/Sandbox/Plugins/EditorCommon/Platform/Windows/QPropertyTree/Unicode_Windows.cpp deleted file mode 100644 index a8bd6b92ed..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Platform/Windows/QPropertyTree/Unicode_Windows.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates - -#include - -#include - -string fromWideChar(const wchar_t* wstr) -{ - // We have different implementation for windows as Qt for windows - // is built with wchar_t of diferent size (4 bytes, as on linux). - // Therefore we avoid calling any wchar_t functions in Qt. - const unsigned int codepage = CP_UTF8; - int len = WideCharToMultiByte(codepage, 0, wstr, -1, NULL, 0, 0, 0); - char* buf = (char*)alloca(len); - if (len > 1) { - WideCharToMultiByte(codepage, 0, wstr, -1, buf, len, 0, 0); - return string(buf, len - 1); - } - return string(); -} - -wstring toWideChar(const char* str) -{ - const unsigned int codepage = CP_UTF8; - int len = MultiByteToWideChar(codepage, 0, str, -1, NULL, 0); - wchar_t* buf = (wchar_t*)alloca(len * sizeof(wchar_t)); - if (len > 1) { - MultiByteToWideChar(codepage, 0, str, -1, buf, len); - return wstring(buf, len - 1); - } - return wstring(); -} - diff --git a/Code/Sandbox/Plugins/EditorCommon/Platform/Windows/platform_windows_files.cmake b/Code/Sandbox/Plugins/EditorCommon/Platform/Windows/platform_windows_files.cmake deleted file mode 100644 index 4c6a5b0644..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Platform/Windows/platform_windows_files.cmake +++ /dev/null @@ -1,14 +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 - QPropertyTree/Unicode_Windows.cpp -) diff --git a/Code/Sandbox/Plugins/EditorCommon/QAbstractQVariantTreeDataModel.cpp b/Code/Sandbox/Plugins/EditorCommon/QAbstractQVariantTreeDataModel.cpp deleted file mode 100644 index d7ccd1d8e5..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QAbstractQVariantTreeDataModel.cpp +++ /dev/null @@ -1,75 +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 - - -QAbstractQVariantTreeDataModel::Item* QAbstractQVariantTreeDataModel::itemFromIndex(const QModelIndex& index) const -{ - if (index.isValid()) - { - return (Item*)index.internalPointer(); - } - return m_root.get(); -} - -QModelIndex QAbstractQVariantTreeDataModel::indexFromItem(QAbstractQVariantTreeDataModel::Item* item, int col /*= 0*/) const -{ - if (0 == item) - { - return QModelIndex(); - } - if (!item->m_parent || !item->m_parent->asFolder()) - { - return QModelIndex(); - } - int row = item->m_parent->asFolder()->row(item); - return createIndex(row, col, item); -} - -QModelIndex QAbstractQVariantTreeDataModel::index(int row, int column, const QModelIndex& parent /*= QModelIndex()*/) const -{ - Item* parentItem = itemFromIndex(parent); - if (parentItem && parentItem->asFolder() && row < parentItem->asFolder()->m_children.size()) - { - Item* item = parentItem->asFolder()->m_children[row].get(); - return createIndex(row, column, item); - } - return QModelIndex(); -} - -QModelIndex QAbstractQVariantTreeDataModel::parent(const QModelIndex& child) const -{ - Item* item = itemFromIndex(child); - return item && item->m_parent && item->m_parent->asFolder() ? indexFromItem(item->m_parent) : QModelIndex(); -} - -bool QAbstractQVariantTreeDataModel::hasChildren(const QModelIndex& parent /* = QModelIndex() */) const -{ - Item* item = itemFromIndex(parent); - return item && item->asFolder() && item->asFolder()->m_children.size(); -} - -int QAbstractQVariantTreeDataModel::rowCount(const QModelIndex& parent /*= QModelIndex()*/) const -{ - Item* item = itemFromIndex(parent); - int res = 0; - if (item && item->asFolder()) - { - res = (int) item->asFolder()->m_children.size(); - } - return res; -} - -int QAbstractQVariantTreeDataModel::columnCount([[maybe_unused]] const QModelIndex& parent /*= QModelIndex()*/) const -{ - return 1; -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QAbstractQVariantTreeDataModel.h b/Code/Sandbox/Plugins/EditorCommon/QAbstractQVariantTreeDataModel.h deleted file mode 100644 index bdc8979c27..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QAbstractQVariantTreeDataModel.h +++ /dev/null @@ -1,87 +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 QABSTRACTQVARIANTTREEDATAMODEL_H -#define QABSTRACTQVARIANTTREEDATAMODEL_H - -#include -#include -#include - -#include "EditorCommonAPI.h" - - -class EDITOR_COMMON_API QAbstractQVariantTreeDataModel - : public QAbstractItemModel -{ -public: - QAbstractQVariantTreeDataModel(QObject* parent) - : QAbstractItemModel(parent) { } - - QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; - QModelIndex parent(const QModelIndex& child) const override; - bool hasChildren(const QModelIndex& parent = QModelIndex()) const override; - - int rowCount(const QModelIndex& parent = QModelIndex()) const override; - int columnCount(const QModelIndex& parent = QModelIndex()) const override; - -protected: - struct Folder; - - struct Item - { - Item() - : m_parent(0) { } - - QMap m_data; - Folder* m_parent; - - virtual ~Item() = default; - virtual const Folder* asFolder() const { return 0; } // need this as we don't have RTTI - }; - - struct Folder - : public Item - { - Folder(const QString& name) - { - m_data.insert(Qt::DisplayRole, name); - } - std::vector < std::shared_ptr > m_children; - const Folder* asFolder() const override { return this; } // need this as we don't have RTTI - - int row(Item* item) const - { - for (int i = 0; i < m_children.size(); ++i) - { - if (m_children[i].get() == item) - { - return i; - } - } - return -1; - } - void addChild(std::shared_ptr item) - { - item->m_parent = this; - m_children.push_back(item); - } - }; - - Item* itemFromIndex(const QModelIndex& index) const; - QModelIndex indexFromItem(Item* item, int col = 0) const; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - std::shared_ptr m_root; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; - -#endif // QABSTRACTQVARIANTTREEDATAMODEL_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QParentWndWidget.cpp b/Code/Sandbox/Plugins/EditorCommon/QParentWndWidget.cpp deleted file mode 100644 index f0bbf572df..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QParentWndWidget.cpp +++ /dev/null @@ -1,309 +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 "QParentWndWidget.h" -#include -#include -#include -#include - -#include "QParentWndWidget.h" - -#include - -#if QT_VERSION >= 0x050000 -#include -#endif -static HWND FindTopmostWindow(HWND child, bool considerWsChild) -{ - if (child == GetDesktopWindow()) - { - return 0; - } - HWND current = child; - while (GetParent(current) != 0) - { - if (considerWsChild && (GetWindowLongW(current, GWL_STYLE) & WS_CHILD) == 0) - { - break; - } - current = GetParent(current); - } - - return current; -} - -QParentWndWidget::QParentWndWidget(HWND parent) - : m_parent(parent) - , m_previousFocus(0) - , m_modalityRoot(0) - , m_parentToCenterOn(0) -{ - if (m_parent) - { - SetWindowLongA((HWND)winId(), GWL_STYLE, WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_TABSTOP); - -#if QT_VERSION >= 0x50000 - QWindow* window = windowHandle(); - window->setProperty("_q_embedded_native_parent_handle", (WId)m_parent); - SetParent((HWND)winId(), m_parent); - window->setFlags(Qt::FramelessWindowHint); -#else - SetParent((HWND)winId(), m_parent); -#endif - QEvent e(QEvent::EmbeddingControl); - QApplication::sendEvent(this, &e); - } - - m_parentToCenterOn = FindTopmostWindow(m_parent, true); - m_modalityRoot = FindTopmostWindow(m_parent, false); -} - -void QParentWndWidget::childEvent(QChildEvent* ev) -{ - QObject* child = ev->child(); - if (child->isWidgetType()) - { - if (ev->added()) - { - if (child->isWidgetType()) - { - child->installEventFilter(this); - } - } - else if (ev->removed() && m_parentWasDisabled) - { - m_parentWasDisabled = false; - EnableWindow(m_modalityRoot, true); - child->removeEventFilter(this); - } - } - QWidget::childEvent(ev); -} - -void QParentWndWidget::show() -{ - if (!m_previousFocus) - { - m_previousFocus = ::GetFocus(); - } - if (!m_previousFocus) - { - m_previousFocus = parentWindow(); - } - - QWidget::show(); -} -void QParentWndWidget::hide() -{ - QWidget::hide(); -} - -void QParentWndWidget::center() -{ - const QWidget* child = findChild(); - - RECT rect; - GetWindowRect(m_parentToCenterOn, &rect); - setGeometry((rect.right - rect.left) / 2 + rect.left, - (rect.bottom - rect.top) / 2 + rect.top, 0, 0); -} - -#if QT_VERSION >= 0x50000 -bool QParentWndWidget::nativeEvent(const QByteArray&, void* message, long* result) -#else -bool QParentWndWidget::winEvent(MSG* msg, long* result) -#endif -{ -#if QT_VERSION >= 0x50000 - MSG* msg = (MSG*)message; -#endif - if (msg->message == WM_SETFOCUS) - { - Qt::FocusReason reason; - if (::GetKeyState(VK_LBUTTON) < 0 || - ::GetKeyState(VK_RBUTTON) < 0) - { - reason = Qt::MouseFocusReason; - } - else if (::GetKeyState(VK_SHIFT) < 0) - { - reason = Qt::BacktabFocusReason; - } - else - { - reason = Qt::TabFocusReason; - } - QFocusEvent ev(QEvent::FocusIn, reason); - QApplication::sendEvent(this, &ev); - } - if (msg->message == WM_GETDLGCODE) - { - *result = DLGC_WANTARROWS | DLGC_WANTTAB; - return(true); - } - - return false; -} - -bool QParentWndWidget::eventFilter(QObject* obj, QEvent* ev) -{ - QWidget* widget = (QWidget*)obj; - switch (ev->type()) - { - case QEvent::WindowDeactivate: - { - if (widget->isModal() && isHidden()) - { - BringWindowToTop(m_parent); - } - break; - } - case QEvent::Show: - { - if (widget->isWindow()) - { - if (!m_previousFocus) - { - m_previousFocus = ::GetFocus(); - } - if (!m_previousFocus) - { - m_previousFocus = parentWindow(); - } - hide(); - if (widget->isModal() && !m_parentWasDisabled) - { - EnableWindow(m_modalityRoot, false); - m_parentWasDisabled = true; - } - } - break; - } - case QEvent::Hide: - { - if (m_parentWasDisabled) - { - EnableWindow(m_modalityRoot, true); - m_parentWasDisabled = false; - } - if (m_previousFocus) - { - ::SetFocus(m_previousFocus); - } - else - { - ::SetFocus(parentWindow()); - } - if (widget->testAttribute(Qt::WA_DeleteOnClose) && widget->isWindow()) - { - deleteLater(); - } - break; - } - case QEvent::Close: - { - ::SetActiveWindow(m_parent); - if (widget->testAttribute(Qt::WA_DeleteOnClose)) - { - deleteLater(); - } - break; - } - default: - break; - } - ; - - return QWidget::eventFilter(obj, ev); -} - -void QParentWndWidget::focusInEvent(QFocusEvent* ev) -{ - QWidget* candidate = this; - - if (ev->reason() == Qt::TabFocusReason || ev->reason() == Qt::BacktabFocusReason) - { - while (candidate && (candidate->focusPolicy() & Qt::TabFocus) == 0) - { - candidate = candidate->nextInFocusChain(); - if (candidate == this) - { - candidate = 0; - } - } - if (candidate) - { - candidate->setFocus(ev->reason()); - candidate->setAttribute(Qt::WA_KeyboardFocusChange); - candidate->window()->setAttribute(Qt::WA_KeyboardFocusChange); - if (ev->reason() == Qt::BacktabFocusReason) - { - QWidget::focusNextPrevChild(false); - } - } - } -} - -bool QParentWndWidget::focusNextPrevChild(bool next) -{ - QWidget* current = focusWidget(); - if (next) - { - QWidget* nextFocus = current; - while (true) - { - nextFocus = nextFocus->nextInFocusChain(); - if (nextFocus->isWindow()) - { - break; - } - if (nextFocus->focusPolicy() & Qt::TabFocus) - { - return QWidget::focusNextPrevChild(true); - } - } - } - else - { - if (!current->isWindow()) - { - QWidget* nextFocus = current->nextInFocusChain(); - QWidget* prevFocus = 0; - QWidget* topLevel = 0; - while (nextFocus != current) - { - if ((nextFocus->focusPolicy() & Qt::TabFocus) != 0) - { - prevFocus = nextFocus; - topLevel = 0; - } - else if (nextFocus->isWindow()) - { - topLevel = nextFocus; - } - nextFocus = nextFocus->nextInFocusChain(); - } - - if (!topLevel) - { - return QWidget::focusNextPrevChild(false); - } - } - } - - ::SetFocus(m_parent); - return true; -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QParentWndWidget.h b/Code/Sandbox/Plugins/EditorCommon/QParentWndWidget.h deleted file mode 100644 index a608261b9b..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QParentWndWidget.h +++ /dev/null @@ -1,67 +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 -#ifndef CRYINCLUDE_EDITORCOMMON_QPARENTWNDWIDGET_H -#define CRYINCLUDE_EDITORCOMMON_QPARENTWNDWIDGET_H - -#if !defined(Q_MOC_RUN) -#include - -#include "EditorCommonAPI.h" -#endif - -// QParentWndWidget can be used to show Qt popup windows/dialogs on top on -// Win32/MFC windows. -// -// Example of usage: -// QParentWndWidget parent(parentHwnd); -// -// QDialog dialog(parent); -// dialog.exec(...); -class EDITOR_COMMON_API QParentWndWidget - : public QWidget -{ - Q_OBJECT -public: - QParentWndWidget(HWND parent); - - void show(); - void hide(); - void center(); - - HWND parentWindow() const { return m_parent; } - -protected: - void childEvent(QChildEvent* e) override; - void focusInEvent(QFocusEvent* ev) override; - bool focusNextPrevChild(bool next) override; - - bool eventFilter(QObject* o, QEvent* e) override; -#if QT_VERSION >= 0x50000 - bool nativeEvent(const QByteArray&, void* message, long*); -#else - bool winEvent(MSG* msg, long*); -#endif - -private: - HWND m_parent; - HWND m_parentToCenterOn; - HWND m_modalityRoot; - - HWND m_previousFocus; - - bool m_parentWasDisabled; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPARENTWNDWIDGET_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyCtrl.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyCtrl.h deleted file mode 100644 index 5cea9535a1..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyCtrl.h +++ /dev/null @@ -1,49 +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 "EditorCommonAPI.h" -#include "Controls/PropertyCtrl.h" -#include - -template -class TemplatePropertyCtrl - : public QWinHost -{ -public: - TemplatePropertyCtrl(QWidget* parent) - : QWinHost(parent) { } - - T m_props; -protected: - virtual HWND createWindow(HWND parent, HINSTANCE instance) - { - CWnd* parentWindow = CWnd::FromHandle(parent); - m_props.Create(WS_CHILD | WS_VISIBLE, CRect(0, 0, 100, 100), parentWindow /*, IDC_GRAPH_PROPERTIES*/); - m_props.ModifyStyleEx(0, WS_EX_CLIENTEDGE); - m_props.SetParent(parentWindow); - return m_props.m_hWnd; - } -}; - -class QPropertyCtrl - : public TemplatePropertyCtrl -{ -public: - QPropertyCtrl(QWidget* parent) - : TemplatePropertyCtrl(parent) - { - } -}; - - diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Color.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Color.cpp deleted file mode 100644 index f8ce31ae66..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Color.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "Color.h" -#include "Serialization/IArchive.h" -#include -#include "MathUtils.h" - - -// HSV -// h=0..360, s=0..1, v=0..1 -inline void HSVtoRGB(float h,float s,float v, - float& r,float& g,float& b) -{ - const float min=1e-5f; - int i; - float f,m,n,k; - - if(s=360.0f) - h=0; - else - h=h/60.0f; - - i=xround(floor(h)); - f=h-i; - m=v*(1-s); - n=v*(1-s*f); - k=v*(1-s*(1-f)); - - switch(i){ - case 0: - r=v; g=k; b=m; - break; - case 1: - r=n; g=v; b=m; - break; - case 2: - r=m; g=v; b=k; - break; - case 3: - r=m; g=n; b=v; - break; - case 4: - r=k; g=m; b=v; - break; - case 5: - r=v; g=m; b=n; - break; - default: - YASLI_ASSERT(0); - } - } - - YASLI_ASSERT(r>=0 && r<=1); - YASLI_ASSERT(g>=0 && g<=1); - YASLI_ASSERT(b>=0 && b<=1); -} - -void Color::setHSV(float h,float s,float v, unsigned char alpha) -{ - float rf,gf,bf; - HSVtoRGB(h,s,v, rf,gf,bf); - r = xround(rf*255); - g = xround(gf*255); - b = xround(bf*255); - a = alpha; -} - - -void Color::toHSV(float& h,float& s,float& v) -{ - float rf = r/255.f; - float gf = g/255.f; - float bf = b/255.f; - v = max(max(rf,gf),bf); - float temp=min(min(rf,gf),bf); - if(v==0) - s=0; - else - s=(v-temp)/v; - - if(s==0) - h=0; - else { - float Cr=(v-rf)/(v-temp); - float Cg=(v-gf)/(v-temp); - float Cb=(v-bf)/(v-temp); - - if(rf==v) { - h=Cb-Cg; - } - else if(gf==v) { - h=2+Cr-Cb; - } - else if(bf==v) { - h=4+Cg-Cr; - } - - h=60*h; - if(h<0)h+=360; - } -} - -void Color::Serialize(Serialization::IArchive& ar) -{ - ar(r, "", "^R"); - ar(g, "", "^G"); - ar(b, "", "^B"); - ar(a, "", "^A"); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Color.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Color.h deleted file mode 100644 index 57c12d53dc..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Color.h +++ /dev/null @@ -1,66 +0,0 @@ -// Modifications copyright Amazon.com, Inc. or its affiliates. -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_COLOR_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_COLOR_H -#pragma once - - -namespace Serialization { - class IArchive; -} - -struct Color -{ - unsigned char b, g, r, a; - - Color() : r(255), g(255), b(255), a(255) { } - Color(unsigned char _r, unsigned char _g, unsigned char _b, unsigned char _a = 255) { r=_r; g=_g; b=_b; a=_a; } - explicit Color(unsigned long _argb) { argb() = _argb; } - void set(int rc,int gc,int bc,int ac = 255) { r=rc; g=gc; b=bc; a=ac; } - - Color& setGDI(unsigned long color) { - b = (unsigned char)(color >> 16); - g = (unsigned char)(color >> 8); - r = (unsigned char)(color); - a = 255; - return *this; - } - - void setHSV(float h,float s,float v, unsigned char alpha = 255); - void toHSV(float& h,float& s, float& v); - - Color& operator*= (float f) { r=int(r*f); g=int(g*f); b=int(b*f); a=int(a*f); return *this; } - Color& operator+= (Color &p) { r+=p.r; g+=p.g; b+=p.b; a+=p.a; return *this; } - Color& operator-= (Color &p) { r-=p.r; g-=p.g; b-=p.b; a-=p.a; return *this; } - Color operator+ (Color &p) { return Color(r+p.r,g+p.g,b+p.b,a+p.a); } - Color operator- (Color &p) { return Color(r-p.r,g-p.g,b-p.b,a-p.a); } - Color operator* (float f) const { return Color(int(r*f), int(g*f), int(b*f), int(a*f)); } - Color operator* (int f) const { return Color(r*f,g*f,b*f,a*f); } - Color operator/ (int f) const { if(f!=0) f=(1<<16)/f; else f=1<<16; return Color((r*f)>>16,(g*f)>>16,(b*f)>>16,(a*f)>>16); } - - bool operator==(const Color& rhs) const { return argb() == rhs.argb(); } - bool operator!=(const Color& rhs) const { return argb() != rhs.argb(); } - - unsigned long argb() const { return *reinterpret_cast(this); } - unsigned long& argb() { return *reinterpret_cast(this); } - unsigned long rgb() const { return r | g << 8 | b << 16; } - unsigned long rgba() const { return r | g << 8 | b << 16 | a << 24; } - unsigned char& operator[](int i) { return ((unsigned char*)this)[i];} - Color interpolate(const Color &v, float f) const - { - return Color(int(r+int(v.r-r)*f), - int(g+int(v.g-g)*f), - int(b+int(v.b-b)*f), - int(a+(v.a-a)*f)); - } - void Serialize(Serialization::IArchive& ar); -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_COLOR_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ConstStringList.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ConstStringList.cpp deleted file mode 100644 index 15900bcbe4..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ConstStringList.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "ConstStringList.h" -#include -#include "Serialization/STL.h" -#include "Serialization/IArchive.h" -#include "Serialization/STLImpl.h" - -ConstStringList globalConstStringList; - -const char* ConstStringList::findOrAdd(const char* string) -{ - // TODO: try sorted vector of const char* - Strings::iterator it = std::find(strings_.begin(), strings_.end(), string); - if (it == strings_.end()) { - strings_.push_back(string); - return strings_.back().c_str(); - } - else { - return it->c_str(); - } -} - - -ConstStringWrapper::ConstStringWrapper(ConstStringList* list, const char*& string) - : list_(list ? list : &globalConstStringList) - , string_(string) -{ - YASLI_ASSERT(string_); -} - -using Serialization::string; - -bool Serialize(Serialization::IArchive& ar, ConstStringWrapper& val, const char* name, const char* label) -{ - if (ar.IsOutput()) { - YASLI_ASSERT(val.string_); - string out = val.string_; - return ar(out, name, label); - } - else { - string in; - bool result = ar(in, name, label); - - val.string_ = val.list_->findOrAdd(in.c_str()); - return result; - } -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ConstStringList.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ConstStringList.h deleted file mode 100644 index 709c85d6b4..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ConstStringList.h +++ /dev/null @@ -1,46 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - // Modifications copyright Amazon.com, Inc. or its affiliates - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_CONSTSTRINGLIST_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_CONSTSTRINGLIST_H -#pragma once - - -#include -#include -#include "EditorCommonAPI.h" - -class ConstStringWrapper; - -namespace Serialization { class IArchive; } - -bool Serialize(Serialization::IArchive& ar, ConstStringWrapper &wrapper, const char* name, const char* label); - -class ConstStringList{ -public: - const char* findOrAdd(const char* string); -protected: - typedef std::list Strings; - Strings strings_; -}; - -class ConstStringWrapper { -public: - ConstStringWrapper(ConstStringList* list, const char*& string); -protected: - ConstStringList* list_; - const char*& string_; - friend bool ::Serialize(Serialization::IArchive& ar, ConstStringWrapper &wrapper, const char* name, const char* label); -}; - -extern ConstStringList globalConstStringList; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_CONSTSTRINGLIST_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ContextList.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ContextList.h deleted file mode 100644 index 47d8558a0b..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ContextList.h +++ /dev/null @@ -1,76 +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_EDITORCOMMON_QPROPERTYTREE_CONTEXTLIST_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_CONTEXTLIST_H -#pragma once - -#include - -namespace Serialization -{ - class CContextList - { - public: - template - void Update(T* contextObject) - { - for (size_t i = 0; i < links_.size(); ++i) - { - if (links_[i]->type == TypeID::get()) - { - links_[i]->contextObject = (void*)contextObject; - return; - } - } - - SContextLink* newLink = new SContextLink; - newLink->type = TypeID::get(); - newLink->outer = links_.empty() ? connectedList_ : links_.back(); - newLink->contextObject = (void*)contextObject; - tail_.outer = newLink; - links_.push_back(newLink); - } - - CContextList() - { - tail_.outer = 0; - tail_.contextObject = 0; - connectedList_ = 0; - } - - explicit CContextList(SContextLink* connectedList) - { - tail_.outer = 0; - tail_.contextObject = 0; - connectedList_ = connectedList; - } - - ~CContextList() - { - for (size_t i = 0; i < links_.size(); ++i) - { - delete links_[i]; - } - links_.clear(); - } - - SContextLink* Tail() { return &tail_; } - private: - SContextLink tail_; - std::vector links_; - SContextLink* connectedList_; - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_CONTEXTLIST_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Factory.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Factory.h deleted file mode 100644 index 83f8ef3ad3..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Factory.h +++ /dev/null @@ -1,156 +0,0 @@ -/** - * yasli - Serialization Library. - * Copyright (C) 2007-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_FACTORY_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_FACTORY_H -#pragma once - -#include -#include -#include "Serialization/Assert.h" - -template> -class Factory { -public: - typedef AZStd::map<_Key, AZStd::function<_Product *()>, _KeyPred, AZ::StdLegacyAllocator> Creators; - typedef _Product* (*ProductConstructionFunction)(void); - - Factory() {} - - struct Creator - { - Creator() - { - if (s_creatorsHead) - { - m_next = s_creatorsHead; - } - s_creatorsHead = this; - } - - Creator(Factory& factory, _Key key, ProductConstructionFunction construction_function_) - : Creator() - { - // capture key and construction_function_ by value so the lazy load won't try to access possibly deleted data - Register = [&, key, construction_function_]() - { - factory.add(key, construction_function_); - }; - } - - Creator(_Key key, ProductConstructionFunction construction_function_) - : Creator() - { - // capture key and construction_function_ by value so the lazy load won't try to access possibly deleted data - Register = [&, key, construction_function_]() - { - Factory::the().add(key, construction_function_); - }; - } - - AZStd::function Register; - Creator* m_next = nullptr; - }; - - void add(const _Key& key, AZStd::function<_Product *()> creator) { - YASLI_ASSERT(creators_.find(key) == creators_.end()); - YASLI_ASSERT(creator); - creators_[key] = creator; - } - - void remove(const _Key& key) { - auto& entry = creators_.find(key); - if (entry != creators_.end()) { - creators_.erase(entry); - } - } - - _Product* create(const _Key& key) const - { - lazyRegisterCreators(); - typename Creators::const_iterator it = creators_.find(key); - if (it != creators_.end()) { - return it->second(); - } - else - return 0; - } - - std::size_t size() const - { - lazyRegisterCreators(); - return creators_.size(); - } - - _Product* createByIndex(int index) const - { - lazyRegisterCreators(); - YASLI_ASSERT(index >= 0 && index < creators_.size()); - typename Creators::const_iterator it = creators_.begin(); - std::advance(it, index); - return it->second(); - } - - - const Creators& creators() const - { - lazyRegisterCreators(); - return creators_; - } - - static Factory& the() - { - static Factory* genericFactory = nullptr; - static AZStd::aligned_storage_for_t s_storage; - if (!genericFactory) - { - genericFactory = new(&s_storage) Factory(); - } - return *genericFactory; - } - -private: - void lazyRegisterCreators() const - { - if (s_creatorsHead) - { - Creator* creator = s_creatorsHead; - while (creator) - { - creator->Register(); - creator = creator->m_next; - } - s_creatorsHead = nullptr; - } - } - -protected: - Creators creators_; - - static Creator* s_creatorsHead; -}; - -template -typename Factory<_Key, _Product, _KeyPred>::Creator* Factory<_Key, _Product, _KeyPred>::s_creatorsHead = nullptr; - -#define REGISTER_IN_FACTORY(factory, key, product, construction_function) \ - static factory::Creator factory##product##Creator(key, construction_function); - -#define REGISTER_IN_FACTORY_INSTANCE(factory, factoryType, key, product) \ - static factoryType::Creator factoryType##product##Creator(factory, key); - -#define DECLARE_SEGMENT(fileName) int dataSegment##fileName; - -#define FORCE_SEGMENT(fileName) \ - extern int dataSegment##fileName; \ - int* dataSegmentPtr##fileName = &dataSegment##fileName; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_FACTORY_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/MathUtils.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/MathUtils.h deleted file mode 100644 index 82c49a8806..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/MathUtils.h +++ /dev/null @@ -1,54 +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_EDITORCOMMON_QPROPERTYTREE_MATHUTILS_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_MATHUTILS_H -#pragma once - -inline int xround(float v) -{ - return int(v + 0.5f); -} - -inline int min(int a, int b) -{ - return a < b ? a : b; -} - -inline int max(int a, int b) -{ - return a > b ? a : b; -} - -inline float min(float a, float b) -{ - return a < b ? a : b; -} - -inline float max(float a, float b) -{ - return a > b ? a : b; -} - -inline float clamp(float value, float min, float max) -{ - return ::min(::max(min, value), max); -} - -inline int clamp(int value, int min, int max) -{ - return ::min(::max(min, value), max); -} - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_MATHUTILS_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyDrawContext.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyDrawContext.cpp deleted file mode 100644 index b13c89464d..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyDrawContext.cpp +++ /dev/null @@ -1,466 +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. -* -*/ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "PropertyDrawContext.h" -#include -#include "QPropertyTree.h" -#include "Serialization/Decorators/IconXPM.h" -#include "Unicode.h" -#include -#include -#include -#include - -// required to create context for the draw calls -#include -#include -#include - -#include - -#ifndef _MSC_VER -# define _stricmp strcasecmp -#endif - -// --------------------------------------------------------------------------- - -QColor interpolateColor(const QColor& a, const QColor& b, float k); - -IconXPMCache::~IconXPMCache() -{ - flush(); -} - - -void IconXPMCache::flush() -{ - IconToBitmap::iterator it; - for (it = iconToImageMap_.begin(); it != iconToImageMap_.end(); ++it) - delete it->second.bitmap; - iconToImageMap_.clear(); -} - -struct RGBAImage -{ - int width_; - int height_; - std::vector pixels_; - - RGBAImage() : width_(0), height_(0) {} -}; - -bool IconXPMCache::parseXPM(RGBAImage* out, const Serialization::IconXPM& icon) -{ - if (icon.lineCount < 3) { - return false; - } - - // parse values - std::vector pixels; - int width = 0; - int height = 0; - int charsPerPixel = 0; - int colorCount = 0; - int hotSpotX = -1; - int hotSpotY = -1; - - int scanResult = azsscanf(icon.source[0], "%d %d %d %d %d %d", &width, &height, &colorCount, &charsPerPixel, &hotSpotX, &hotSpotY); - if (scanResult != 4 && scanResult != 6) - return false; - - if (charsPerPixel > 4) - return false; - - if (icon.lineCount != 1 + colorCount + height) { - YASLI_ASSERT(0 && "Wrong line count"); - return false; - } - - // parse colors - std::vector > colors; - colors.resize(colorCount); - - for (int colorIndex = 0; colorIndex < colorCount; ++colorIndex) { - const char* p = icon.source[colorIndex + 1]; - int code = 0; - for (int charIndex = 0; charIndex < charsPerPixel; ++charIndex) { - if (*p == '\0') - return false; - code = (code << 8) | *p; - ++p; - } - colors[colorIndex].first = code; - - while (*p == '\t' || *p == ' ') - ++p; - - if (*p == '\0') - return false; - - if (*p != 'c' && *p != 'g') - return false; - ++p; - - while (*p == '\t' || *p == ' ') - ++p; - - if (*p == '\0') - return false; - - if (*p == '#') { - ++p; - if (strlen(p) == 6) { - int colorCode; - if (azsscanf(p, "%x", &colorCode) != 1) - return false; - Color color((colorCode & 0xff0000) >> 16, - (colorCode & 0xff00) >> 8, - (colorCode & 0xff), - 255); - colors[colorIndex].second = color; - } - } - else { - if (_stricmp(p, "None") == 0) - colors[colorIndex].second = Color(0, 0, 0, 0); - else if (_stricmp(p, "Black") == 0) - colors[colorIndex].second = Color(0, 0, 0, 255); - else { - // unknown color - colors[colorIndex].second = Color(255, 0, 0, 255); - } - } - } - - // parse pixels - pixels.resize(width * height); - int pi = 0; - for (int y = 0; y < height; ++y) { - const char* p = icon.source[1 + colorCount + y]; - if (strlen(p) != width * charsPerPixel) - return false; - - for (int x = 0; x < width; ++x) { - int code = 0; - for (int i = 0; i < charsPerPixel; ++i) { - code = (code << 8) | *p; - ++p; - } - - for (size_t i = 0; i < size_t(colorCount); ++i) - if (colors[i].first == code) - pixels[pi] = colors[i].second; - ++pi; - } - } - - out->pixels_.swap(pixels); - out->width_ = width; - out->height_ = height; - return true; -} - - -QImage* IconXPMCache::getImageForIcon(const Serialization::IconXPM& icon) -{ - IconToBitmap::iterator it = iconToImageMap_.find(icon.source); - if (it != iconToImageMap_.end()) - return it->second.bitmap; - - RGBAImage image; - if (!parseXPM(&image, icon)) - return 0; - - BitmapCache& cache = iconToImageMap_[icon.source]; - cache.pixels.swap(image.pixels_); - cache.bitmap = new QImage((unsigned char*)&cache.pixels[0], image.width_, image.height_, QImage::Format_ARGB32); - return cache.bitmap; -} - -// --------------------------------------------------------------------------- - -void drawRoundRectangle(QPainter& p, const QRect &_r, unsigned int color, int radius, [[maybe_unused]] int width) -{ - QRect r = _r; - int dia = 2 * radius; - - p.setPen(QColor(color)); - p.drawRoundedRect(r, dia, dia); -} - -void fillRoundRectangle(QPainter& p, const QBrush& brush, const QRect& _r, const QColor& border, int radius) -{ - bool wasAntialisingSet = p.renderHints().testFlag(QPainter::Antialiasing); - p.setRenderHints(QPainter::Antialiasing, true); - - p.setBrush(brush); - QPen pen(QBrush(border), 1.0, Qt::SolidLine); - p.setPen(pen); - QRectF adjustedRect = _r; - adjustedRect.adjust(0.5f, 0.5f, -0.5f, -0.5f); - p.drawRoundedRect(adjustedRect, radius, radius); - - p.setRenderHints(QPainter::Antialiasing, wasAntialisingSet); -} - -// --------------------------------------------------------------------------- - -void PropertyDrawContext::drawIcon(const QRect& rect, const Serialization::IconXPM& icon) const -{ - QImage* image = tree->_iconCache()->getImageForIcon(icon); - if (!image) - return; - int x = rect.left() + (rect.width() - image->width()) / 2; - int y = rect.top() + (rect.height() - image->height()) / 2; - painter->drawImage(x, y, *image); -} - -void PropertyDrawContext::drawCheck(const QRect& rect, bool disabled, CheckState checked) const -{ - QStyleOptionButton option; - if (!disabled) - option.state |= QStyle::State_Enabled; - else { - option.state |= QStyle::State_ReadOnly; - option.palette.setCurrentColorGroup(QPalette::Disabled); - } - if (checked == CHECK_SET) - option.state |= QStyle::State_On; - else if (checked == CHECK_IN_BETWEEN) - option.state |= QStyle::State_NoChange; - else - option.state |= QStyle::State_Off; - - // create a widget so that the style sheet has context for its draw calls - QCheckBox forContext; - QSize checkboxSize = tree->style()->subElementRect(QStyle::SE_CheckBoxIndicator, &option, &forContext).size(); - option.rect = QRect(rect.left(), rect.center().y() - checkboxSize.height() / 2, checkboxSize.width(), checkboxSize.height()); - tree->style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &option, painter, &forContext); - if (disabled) { - // With Fusion theme difference between disabled and enabled checkbox is very subtle, let's amplify it - QColor readOnlyOverlay = tree->backgroundColor(); - readOnlyOverlay.setAlpha(128); - painter->fillRect(option.rect, QBrush(readOnlyOverlay)); - } -} - -void PropertyDrawContext::drawButton(const QRect& rect, const wchar_t* text, int buttonFlags, const QFont* font, const Color* colorOverride) const -{ - QPushButton button; - button.ensurePolished(); - QStyleOptionButton option; - option.initFrom(&button); - if (buttonFlags & BUTTON_DISABLED) { - option.state |= QStyle::State_ReadOnly; - option.palette.setCurrentColorGroup(QPalette::Disabled); - } - else - option.state |= QStyle::State_Enabled; - if (buttonFlags & BUTTON_PRESSED) { - option.state |= QStyle::State_On; - option.state |= QStyle::State_Sunken; - } - else - option.state |= QStyle::State_Raised; - - if (buttonFlags & BUTTON_FOCUSED) - option.state |= QStyle::State_HasFocus; - option.rect = rect.adjusted(0, 0, -1, -1); - - QWidget* pseudoDrawWidget = &button; - - if (colorOverride) { - QPalette& palette = option.palette; - palette.setCurrentColorGroup(QPalette::Normal); - QColor tintTarget(colorOverride->r, colorOverride->g, colorOverride->b, colorOverride->a); - - QPalette::ColorRole groups[] = { QPalette::Button, QPalette::Light, QPalette::Dark, QPalette::Midlight, QPalette::Mid, QPalette::Shadow }; - for (int i = 0; i < sizeof(groups) / sizeof(groups[0]); ++i) - palette.setColor(groups[i], interpolateColor(palette.color(groups[i]), tintTarget, 0.11f)); - - tree->style()->drawControl(QStyle::CE_PushButtonBevel, &option, painter, pseudoDrawWidget); - } - else - { - // Previously, a temporary QPushButton widget was used as the drawing aid - // for this control. However, our stylesheets didn't seem to affect the - // QPushButton as intended, which left some of them with incorrect background - // colors. It seemed to work to let the tree be the drawing aid, but we should - // probably revisit this in the future. - tree->style()->drawControl(QStyle::CE_PushButtonBevel, &option, painter, pseudoDrawWidget); - } - - QRect textRect; - if ((buttonFlags & BUTTON_DISABLED) == 0 && buttonFlags & BUTTON_POPUP_ARROW) - { - QStyleOption arrowOption; - arrowOption.rect = QRect(rect.right() - 11, rect.top(), 8, rect.height()); - arrowOption.state |= QStyle::State_Enabled; - - // part of the above context change - tree->style()->drawPrimitive(QStyle::PE_IndicatorArrowDown, &arrowOption, painter, tree); - - textRect = rect.adjusted(0, 0, -8, 0); - } - else - { - textRect = rect; - } - - if (buttonFlags & BUTTON_PRESSED) - { - textRect = textRect.adjusted(1, 0, 1, 0); - } - if ((buttonFlags & BUTTON_CENTER) == 0) - { - textRect.adjust(4, 0, -5, 0); - } - - QColor textColor; - if (colorOverride && !(buttonFlags & BUTTON_DISABLED)) - { - textColor = interpolateColor(tree->palette().color(QPalette::Normal, QPalette::ButtonText), - QColor(colorOverride->r, colorOverride->g, colorOverride->b, colorOverride->a), 0.4f); - } - else - { - textColor = tree->palette().color((buttonFlags & BUTTON_DISABLED) ? QPalette::Disabled : QPalette::Normal, QPalette::ButtonText); - } - tree->_drawRowValue(*painter, text, font, textRect, textColor, false, (buttonFlags & BUTTON_CENTER) != 0); -} - -void PropertyDrawContext::drawButtonWithIcon(const QIcon& icon, const QRect& rect, const wchar_t* text, bool selected, bool pressed, bool focused, bool enabled, bool showButtonFrame, const QFont* font) const -{ - QStyleOptionButton option; - if (enabled) - option.state |= QStyle::State_Enabled; - else - option.state |= QStyle::State_ReadOnly; - if (pressed) { - option.state |= QStyle::State_On; - option.state |= QStyle::State_Sunken; - } - else - option.state |= QStyle::State_Raised; - - if (focused) - option.state |= QStyle::State_HasFocus; - option.rect = rect.adjusted(0, 0, -1, -1); - - // See the comment in the drawButton method above for why we don't use the - // QPushButton as the drawing aid for this control - if (showButtonFrame) - tree->style()->drawControl(QStyle::CE_PushButton, &option, painter, tree); - - int iconSize = 16; - QRect iconRect(rect.topLeft(), QPoint(rect.left() + iconSize, rect.bottom())); - QRect textRect; - if (enabled) - textRect = rect.adjusted(iconSize, 0, -8, 0); - else - textRect = rect.adjusted(iconSize, 0, 0, 0); - - if (pressed) - { - textRect.adjust(5, 0, 1, 0); - iconRect.adjust(4, 0, 4, 0); - } - else - { - textRect.adjust(4, 0, 0, 0); - iconRect.adjust(3, 0, 3, 0); - } - icon.paint(painter, iconRect); - - QColor textColor = tree->palette().color(enabled ? QPalette::Active : QPalette::Disabled, selected && !showButtonFrame ? QPalette::HighlightedText : QPalette::ButtonText); - tree->_drawRowValue(*painter, text, font, textRect, textColor, false, false); -} - -void PropertyDrawContext::drawValueText(bool highlighted, const wchar_t* text) const -{ - QColor textColor = highlighted ? tree->palette().highlight().color() : tree->palette().buttonText().color(); - QRect textRect(widgetRect.left() + 3, widgetRect.top() + 2, widgetRect.width() - 6, widgetRect.height() - 4); - tree->_drawRowValue(*painter, text, &tree->font(), textRect, textColor, false, false); -} - -void PropertyDrawContext::drawEntry(const wchar_t* text, bool pathEllipsis, bool grayBackground, int trailingOffset) const -{ - QRect rt = widgetRect; - rt.adjust(0, 0, -trailingOffset, 0); - - // the drawing context requires context so that the style sheet can be used: - QFrame frameForContext; - QLineEdit forContext; -#if (QT_VERSION < QT_VERSION_CHECK(5, 11, 0)) - QStyleOptionFrameV2 option; - option.features = QStyleOptionFrameV2::None; -#else - QStyleOptionFrame option; - option.features = QStyleOptionFrame::None; -#endif - option.state = QStyle::State_Sunken; - option.lineWidth = tree->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &option, &frameForContext); - option.midLineWidth = 0; - if (!grayBackground) - option.state |= QStyle::State_Enabled; - else { - option.palette.setCurrentColorGroup(QPalette::Disabled); - } - if (captured) - option.state |= QStyle::State_HasFocus; - option.rect = rt; // option.rect is the rectangle to be drawn on. - QRect textRect = tree->style()->subElementRect(QStyle::SE_LineEditContents, &option, &forContext); - if (!textRect.isValid()) - { - textRect = rt; - textRect.adjust(3, 1, -3, -2); - } - else { - textRect.adjust(2, 1, -2, -1); - } - - // make sure the context control is polished (ie, ready for rendering) since we need to use its color palette: - forContext.ensurePolished(); - - // some styles rely on default pens - painter->setPen(QPen(forContext.palette().color(QPalette::Text))); - painter->setBrush(QBrush(forContext.palette().color(QPalette::Base))); - - tree->style()->drawPrimitive(QStyle::PE_PanelLineEdit, &option, painter, &forContext); - tree->_drawRowValue(*painter, text, &tree->font(), textRect, forContext.palette().color(QPalette::Text), pathEllipsis, false); - // end amazno changes -} - - -QFont* propertyTreeDefaultFont() -{ - static QFont font; - return &font; -} - -QFont* propertyTreeDefaultBoldFont() -{ - static QFont font; - font.setBold(true); - return &font; -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyDrawContext.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyDrawContext.h deleted file mode 100644 index 611216eb73..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyDrawContext.h +++ /dev/null @@ -1,98 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - // Modifications copyright Amazon.com, Inc. or its affiliates. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYDRAWCONTEXT_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYDRAWCONTEXT_H -#pragma once - - -#include -#include -#include -#include "Color.h" -#include "EditorCommonAPI.h" - -class QPainter; -class QImage; -class QBrush; -class QRect; -class QIcon; -class QColor; -class QFont; -struct RGBAImage; -namespace Serialization { struct IconXPM; } -struct Color; - -struct IconXPMCache -{ - void initialize(); - void finalize(); - void flush(); - - ~IconXPMCache(); - - QImage* getImageForIcon(const Serialization::IconXPM& icon); -private: - struct BitmapCache { - std::vector pixels; - QImage* bitmap; - }; - - static bool parseXPM(RGBAImage* out, const Serialization::IconXPM& xpm); - typedef std::map IconToBitmap; - IconToBitmap iconToImageMap_; -}; - - -void fillRoundRectangle(QPainter& p, const QBrush& brush, const QRect& r, const QColor& borderColor, int radius); -void drawRoundRectangle(QPainter& p, const QRect &_r, unsigned int color, int radius, int width); - - -enum CheckState { - CHECK_SET, - CHECK_NOT_SET, - CHECK_IN_BETWEEN -}; - -enum { - BUTTON_POPUP_ARROW = 1 << 0, - BUTTON_DISABLED = 1 << 1, - BUTTON_FOCUSED = 1 << 2, - BUTTON_PRESSED = 1 << 3, - BUTTON_CENTER = 1 << 4 -}; - -class QPropertyTree; -struct EDITOR_COMMON_API PropertyDrawContext { - const QPropertyTree* tree; - QPainter* painter; - QRect widgetRect; - QRect lineRect; - bool captured; - bool m_pressed; - - void drawIcon(const QRect& rect, const Serialization::IconXPM& icon) const; - void drawCheck(const QRect& rect, bool disabled, CheckState checked) const; - void drawButton(const QRect& rect, const wchar_t* text, int buttonFlags, const QFont* font, const Color* optionalColorOverride = 0) const; - void drawButtonWithIcon(const QIcon& icon, const QRect& rect, const wchar_t* text, bool selected, bool pressed, bool focused, bool enabled, bool showButtonFrame, const QFont* font) const; - void drawValueText(bool highlighted, const wchar_t* text) const; - void drawEntry(const wchar_t* text, bool pathEllipsis, bool grayBackground, int trailingOffset) const; - - PropertyDrawContext() - : tree(0) - , painter(0) - , captured(false) - , m_pressed(false) - { - } -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYDRAWCONTEXT_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyIArchive.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyIArchive.cpp deleted file mode 100644 index 4b03246db5..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyIArchive.cpp +++ /dev/null @@ -1,377 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "Serialization.h" -#include "Serialization/Enum.h" -#include "Serialization/Callback.h" -#include "PropertyTreeModel.h" -#include "PropertyIArchive.h" -#include "PropertyRowBool.h" -#include "PropertyRowString.h" -#include "PropertyRowNumber.h" -#include "PropertyRowPointer.h" -#include "PropertyRowObject.h" -#include "Unicode.h" - -using Serialization::TypeID; - -PropertyIArchive::PropertyIArchive(PropertyTreeModel* model, PropertyRow* root) -: IArchive(INPUT | EDIT) -, model_(model) -, currentNode_(0) -, lastNode_(0) -, root_(root) -{ - stack_.push_back(Level()); - - if (!root_) - root_ = model_->root(); - else - currentNode_ = root; -} - -bool PropertyIArchive::operator()(Serialization::IString& value, const char* name, const char* label) -{ - if(openRow(name, label, "string")){ - if(PropertyRowString* row = static_cast(currentNode_)) - value.set(fromWideChar(row->value().c_str()).c_str()); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(Serialization::IWString& value, const char* name, const char* label) -{ - if(openRow(name, label, "string")){ - if(PropertyRowString* row = static_cast(currentNode_)) { - value.set(row->value().c_str()); - } - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(bool& value, const char* name, const char* label) -{ - if(openRow(name, label, "bool")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(char& value, const char* name, const char* label) -{ - if(openRow(name, label, "char")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -// Signed types -bool PropertyIArchive::operator()(int8& value, const char* name, const char* label) -{ - if(openRow(name, label, "int8")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(int16& value, const char* name, const char* label) -{ - if(openRow(name, label, "int16")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(int32& value, const char* name, const char* label) -{ - if(openRow(name, label, "int32")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(int64& value, const char* name, const char* label) -{ - if(openRow(name, label, "int64")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -// Unsigned types -bool PropertyIArchive::operator()(uint8& value, const char* name, const char* label) -{ - if(openRow(name, label, "uint8")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(uint16& value, const char* name, const char* label) -{ - if(openRow(name, label, "uint16")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(uint32& value, const char* name, const char* label) -{ - if(openRow(name, label, "uint32")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(uint64& value, const char* name, const char* label) -{ - if(openRow(name, label, "uint64")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(float& value, const char* name, const char* label) -{ - if(openRow(name, label, "float")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(double& value, const char* name, const char* label) -{ - if(openRow(name, label, "double")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(Serialization::IContainer& ser, const char* name, const char* label) -{ - const char* typeName = ser.containerType().name(); - if(!openRow(name, label, typeName)) - return false; - - size_t size = 0; - if(currentNode_->multiValue()) - size = ser.size(); - else{ - size = currentNode_->count(); - size = ser.resize(size); - } - - stack_.push_back(Level()); - - size_t index = 0; - if(ser.size() > 0) - while(index < size) - { - ser(*this, "", "<"); - ser.next(); - ++index; - } - - stack_.pop_back(); - - closeRow(name); - return true; -} - -bool PropertyIArchive::operator()(const Serialization::SStruct& ser, const char* name, const char* label) -{ - PropertyRow* nonLeafNode = 0; - if(openRow(name, label, ser.type().name())){ - if (currentNode_->isLeaf()) { - if(!currentNode_->isRoot()){ - currentNode_->assignTo(ser); - closeRow(name); - return true; - } - } - else - nonLeafNode = currentNode_; - } - else - return false; - - stack_.push_back(Level()); - - ser(*this); - - stack_.pop_back(); - - if (nonLeafNode) - nonLeafNode->closeNonLeaf(ser, *this); - closeRow(name); - return true; -} - - -bool PropertyIArchive::operator()(Serialization::IPointer& ser, const char* name, const char* label) -{ - const char* baseName = ser.baseType().name(); - - if(openRow(name, label, baseName)){ - if (!currentNode_->isPointer()) { - closeRow(name); - return false; - } - - YASLI_ASSERT(currentNode_); - PropertyRowPointer* row = static_cast(currentNode_); - if(!row){ - closeRow(name); - return false; - } - row->assignTo(ser); - } - else - return false; - - stack_.push_back(Level()); - - if(ser.get() != 0) - ser.serializer()( *this ); - - stack_.pop_back(); - - closeRow(name); - return true; -} - -bool PropertyIArchive::operator()(Serialization::ICallback& callback, const char* name, const char* label) -{ - return callback.SerializeValue(*this, name, label); -} - -bool PropertyIArchive::operator()(Serialization::Object& obj, const char* name, const char* label) -{ - if(openRow(name, label, obj.type().name())){ - bool result = false; - if (currentNode_->isObject()) { - PropertyRowObject* rowObj = static_cast(currentNode_); - result = rowObj->assignTo(&obj); - } - closeRow(name); - return result; - } - else - return false; -} - -bool PropertyIArchive::OpenBlock(const char* name, const char* label) -{ - if(openRow(name, label, "block")){ - stack_.push_back(Level()); - return true; - } - else - return false; -} - -void PropertyIArchive::CloseBlock() -{ - closeRow("block"); - stack_.pop_back(); -} - -bool PropertyIArchive::openRow(const char* name, [[maybe_unused]] const char* label, const char* typeName) -{ - if(!name) - return false; - - if(!currentNode_){ - lastNode_ = currentNode_ = model_->root(); - YASLI_ASSERT(currentNode_); - if (currentNode_ && strcmp(currentNode_->typeName(), typeName) != 0) - return false; - return true; - } - - YASLI_ESCAPE(currentNode_, return false); - - if(currentNode_->empty()) - return false; - - Level& level = stack_.back(); - - PropertyRow* node = 0; - if(currentNode_->isContainer()){ - if (level.rowIndex < int(currentNode_->children_.size())) - node = currentNode_->children_[level.rowIndex]; - ++level.rowIndex; - } - else { - node = currentNode_->findFromIndex(&level.rowIndex, name, typeName, level.rowIndex); - ++level.rowIndex; - } - - if(node){ - lastNode_ = node; - if(node->isContainer() || !node->multiValue()){ - currentNode_ = node; - if (currentNode_ && strcmp(currentNode_->typeName(), typeName) != 0) - return false; - return true; - } - } - return false; -} - -void PropertyIArchive::closeRow([[maybe_unused]] const char* name) -{ - YASLI_ESCAPE(currentNode_, return); - currentNode_ = currentNode_->parent(); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyIArchive.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyIArchive.h deleted file mode 100644 index 265a819cf7..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyIArchive.h +++ /dev/null @@ -1,80 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYIARCHIVE_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYIARCHIVE_H -#pragma once - - -#include "Serialization/IArchive.h" - -namespace Serialization{ - class CEnumDescription; - class Object; -} - -class PropertyRow; -class PropertyTreeModel; - -class PropertyIArchive : public Serialization::IArchive{ -public: - PropertyIArchive(PropertyTreeModel* model, PropertyRow* root); - -protected: - bool operator()(Serialization::IString& value, const char* name, const char* label); - bool operator()(Serialization::IWString& value, const char* name, const char* label); - bool operator()(bool& value, const char* name, const char* label); - bool operator()(char& value, const char* name, const char* label); - - // Signed types - bool operator()(int8& value, const char* name, const char* label); - bool operator()(int16& value, const char* name, const char* label); - bool operator()(int32& value, const char* name, const char* label); - bool operator()(int64& value, const char* name, const char* label); - // Unsigned types - bool operator()(uint8& value, const char* name, const char* label); - bool operator()(uint16& value, const char* name, const char* label); - bool operator()(uint32& value, const char* name, const char* label); - bool operator()(uint64& value, const char* name, const char* label); - - bool operator()(float& value, const char* name, const char* label); - bool operator()(double& value, const char* name, const char* label); - - bool operator()(const Serialization::SStruct& ser, const char* name, const char* label); - bool operator()(Serialization::IPointer& ser, const char* name, const char* label); - bool operator()(Serialization::IContainer& ser, const char* name, const char* label); - bool operator()(Serialization::Object& obj, const char* name, const char* label); - bool operator()(Serialization::ICallback& callback, const char* name, const char* label); - using Serialization::IArchive::operator(); - - bool OpenBlock(const char* name, const char* label); - void CloseBlock(); - -protected: - bool needDefaultArchive([[maybe_unused]] const char* baseName) const { return false; } -private: - bool openRow(const char* name, const char* label, const char* typeName); - void closeRow(const char* name); - - struct Level { - int rowIndex; - Level() : rowIndex(0) {} - }; - - vector stack_; - - PropertyTreeModel* model_; - PropertyRow* currentNode_; - PropertyRow* lastNode_; - PropertyRow* root_; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYIARCHIVE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyOArchive.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyOArchive.cpp deleted file mode 100644 index fd6773f4da..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyOArchive.cpp +++ /dev/null @@ -1,487 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include -#include - -#include "PropertyTreeModel.h" -#include "QPropertyTree.h" - -#include "PropertyRowContainer.h" -#include "PropertyRowBool.h" -#include "PropertyRowString.h" -#include "PropertyRowNumber.h" -#include "PropertyRowPointer.h" -#include "PropertyRowObject.h" -#include "ConstStringList.h" -#include "Unicode.h" - -#include "Serialization.h" -#include "PropertyOArchive.h" -#include "Serialization/Callback.h" -using Serialization::TypeID; - - -PropertyOArchive::PropertyOArchive(PropertyTreeModel* model, PropertyRow* root, ValidatorBlock* validator) -: IArchive(OUTPUT | EDIT | VALIDATION | DOCUMENTATION) -, model_(model) -, currentNode_(root) -, lastNode_(0) -, updateMode_(false) -, defaultValueCreationMode_(false) -, rootNode_(root) -, outlineMode_(false) -, validator_(validator) -{ - stack_.push_back(Level()); - YASLI_ASSERT(model != 0); - if(!rootNode_->empty()){ - updateMode_ = true; - stack_.back().oldRows.swap(rootNode_->children_); - } -} - - - -PropertyOArchive::PropertyOArchive(PropertyTreeModel* model, bool forDefaultType) -: IArchive(OUTPUT | EDIT | VALIDATION | DOCUMENTATION) -, model_(model) -, currentNode_(0) -, lastNode_(0) -, updateMode_(false) -, defaultValueCreationMode_(forDefaultType) -, rootNode_(0) -, outlineMode_(false) -, validator_(0) -{ - rootNode_ = new PropertyRow(); - rootNode_->setName("root"); - currentNode_ = rootNode_.get(); - stack_.push_back(Level()); -} - -PropertyOArchive::~PropertyOArchive() -{ -} - -PropertyRow* PropertyOArchive::defaultValueRootNode() -{ - if (!rootNode_) - return 0; - return rootNode_->childByIndex(0); -} - -void PropertyOArchive::enterNode(PropertyRow* row) -{ - currentNode_ = row; - - stack_.push_back(Level()); - Level& level = stack_.back(); - level.oldRows.swap(row->children_); - row->children_.reserve(level.oldRows.size()); -} - -void PropertyOArchive::closeStruct([[maybe_unused]] const char* name) -{ - stack_.pop_back(); - - if(currentNode_){ - lastNode_ = currentNode_; - currentNode_ = currentNode_->parent(); - } -} - -static PropertyRow* findRow(int* index, PropertyRows& rows, const char* name, const char* typeName, int startIndex) -{ - int count = int(rows.size()); - for(int i = startIndex; i < count; ++i){ - PropertyRow* row = rows[i]; - if (!row) - continue; - if(((row->name() == name) || strcmp(row->name(), name) == 0) && - (row->typeName() == typeName || strcmp(row->typeName(), typeName) == 0)) { - *index = (int)i; - return row; - } - } - for(int i = 0; i < startIndex; ++i){ - PropertyRow* row = rows[i]; - if (!row) - continue; - if(((row->name() == name) || strcmp(row->name(), name) == 0) && - (row->typeName() == typeName || strcmp(row->typeName(), typeName) == 0)) { - *index = (int)i; - return row; - } - } - return 0; -} - -template -RowType* PropertyOArchive::updateRow(const char* name, const char* label, const char* typeName, const ValueType& value) -{ - SharedPtr newRow; - if(currentNode_ == 0){ - if (rootNode_) - newRow = static_cast(rootNode_.get()); - else - newRow.reset(new RowType()); - newRow->setNames(name, label, typeName); - if(updateMode_){ - model_->setRoot(newRow); - return newRow; - } - else{ - if(defaultValueCreationMode_) - rootNode_ = newRow; - else - model_->setRoot(newRow); - newRow->setValueAndContext(value, *this); - return newRow; - } - } - else{ - - Level& level = stack_.back(); - int rowIndex; - PropertyRow* oldRow = findRow(&rowIndex, level.oldRows, name, typeName, level.rowIndex); - - const char* oldLabel = 0; - if(oldRow){ - oldRow->setMultiValue(false); - newRow = static_cast(oldRow); - level.oldRows[rowIndex] = 0; - level.rowIndex = rowIndex + 1; - oldLabel = oldRow->label(); - newRow->setNames(name, label, typeName); - } - else{ - PropertyRowFactory& factory = PropertyRowFactory::the(); - newRow = static_cast(factory.create(typeName)); - if(!newRow) - newRow.reset(new RowType()); - newRow->setNames(name, label, typeName); - if(model_->expandLevels() != 0 && (model_->expandLevels() == -1 || model_->expandLevels() >= currentNode_->level())) - newRow->_setExpanded(true); - } - currentNode_->add(newRow); - if (!oldRow || oldLabel != label) { - // for new rows we should mark all parents with labelChanged_ - newRow->setLabelChanged(); - newRow->setLabelChangedToChildren(); - } - newRow->setValueAndContext(value, *this); - return newRow; - } -} - -template -PropertyRow* PropertyOArchive::updateRowPrimitive(const char* name, const char* label, const char* typeName, const ValueType& value, const void* handle, const Serialization::TypeID& typeId) -{ - SharedPtr newRow; - - if(currentNode_ == 0) - return 0; - - int rowIndex; - Level& level = stack_.back(); - PropertyRow* oldRow = findRow(&rowIndex, level.oldRows, name, typeName, level.rowIndex); - - const char* oldLabel = 0; - if(oldRow){ - oldRow->setMultiValue(false); - newRow.reset(static_cast(oldRow)); - level.oldRows[rowIndex] = 0; - level.rowIndex = rowIndex + 1; - oldLabel = oldRow->label(); - oldRow->setNames(name, label, typeName); - } - else{ - newRow = new RowType(); - newRow->setNames(name, label, typeName); - if(model_->expandLevels() != 0){ - if(model_->expandLevels() == -1 || model_->expandLevels() >= currentNode_->level()) - newRow->_setExpanded(true); - } - } - currentNode_->add(newRow); - if (!oldRow || oldLabel != label) - { - // for new rows we should mark all parents with labelChanged_ - newRow->setLabelChanged(); - } - - newRow->setValue(value, handle, typeId); - return newRow; -} - -bool PropertyOArchive::operator()(const Serialization::SStruct& ser, const char* name, const char* label) -{ - const char* typeName = ser.type().name(); - - lastNode_ = currentNode_; - bool hideChildren = outlineMode_ && currentNode_ && currentNode_->isContainer(); - PropertyRow* row = updateRow(name, label, typeName, ser); - row->setHideChildren(hideChildren); - - PropertyRow* nonLeaf = 0; - if(!row->isLeaf() || currentNode_ == 0){ - enterNode(row); - - if(currentNode_->isLeaf()) - return false; - else - nonLeaf = currentNode_; - } - else{ - lastNode_ = row; - return true; - } - - if (ser) - ser(*this); - - if (nonLeaf) - nonLeaf->closeNonLeaf(ser, *this); - - closeStruct(name); - return true; -} - -bool PropertyOArchive::operator()(Serialization::IString& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive(name, label, "string", value.get(), value.handle(), value.type()); - return true; -} - -bool PropertyOArchive::operator()(Serialization::IWString& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive(name, label, "string", value.get(), value.handle(), value.type()); - return true; -} - -bool PropertyOArchive::operator()(bool& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive(name, label, "bool", value, &value, Serialization::TypeID::get()); - return true; -} - -bool PropertyOArchive::operator()(char& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "char", value, &value, Serialization::TypeID::get()); - return true; -} - -// --- - -bool PropertyOArchive::operator()(int8& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "int8", value, &value, Serialization::TypeID::get()); - return true; -} - -bool PropertyOArchive::operator()(int16& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "int16", value, &value, Serialization::TypeID::get()); - return true; -} - -bool PropertyOArchive::operator()(int32& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "int32", value, &value, Serialization::TypeID::get()); - return true; -} - -bool PropertyOArchive::operator()(int64& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "int64", value, &value, Serialization::TypeID::get()); - return true; -} - -// --- - -bool PropertyOArchive::operator()(uint8& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "uint8", value, &value, Serialization::TypeID::get()); - return true; -} - -bool PropertyOArchive::operator()(uint16& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "uint16", value, &value, Serialization::TypeID::get()); - return true; -} - -bool PropertyOArchive::operator()(uint32& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "uint32", value, &value, Serialization::TypeID::get()); - return true; -} - -bool PropertyOArchive::operator()(uint64& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "uint64", value, &value, Serialization::TypeID::get()); - return true; -} - -// --- - -bool PropertyOArchive::operator()(float& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "float", value, &value, Serialization::TypeID::get()); - return true; -} - -bool PropertyOArchive::operator()(double& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "double", value, &value, Serialization::TypeID::get()); - return true; -} - - -bool PropertyOArchive::operator()(Serialization::IContainer& ser, const char *name, const char *label) -{ - const char* elementTypeName = ser.elementType().name(); - enterNode(updateRow(name, label, ser.containerType().name(), ser)); - - if (!model_->defaultTypeRegistered(elementTypeName)) { - PropertyOArchive ar(model_, true); - ar.SetOutlineMode(outlineMode_); - ar.SetFilter(GetFilter()); - ar.SetInnerContext(GetInnerContext()); - model_->addDefaultType(0, elementTypeName); // add empty default to prevent recursion - ser.serializeNewElement(ar, "", (label&&*label=='!')?"!<":"<"); - if (ar.defaultValueRootNode() != 0) - model_->addDefaultType(ar.defaultValueRootNode(), elementTypeName); - } - if ( ser.size() > 0 ) - while( true ) { - ser(*this, "", (label&&*label=='!')?"!<":"<"); - if ( !ser.next() ) - break; - } - currentNode_->labelChanged(); - closeStruct(name); - return true; -} - -bool PropertyOArchive::operator()(Serialization::IPointer& ptr, const char *name, const char *label) -{ - lastNode_ = currentNode_; - - bool hideChildren = outlineMode_ && currentNode_ && currentNode_->isContainer(); - PropertyRow* row = updateRow(name, label, ptr.baseType().name(), ptr); - row->setHideChildren(hideChildren); - enterNode(row); - { - TypeID baseType = ptr.baseType(); - Serialization::IClassFactory* factory = ptr.factory(); - size_t count = factory->size(); - - const char* nullLabel = factory->nullLabel(); - if (!(nullLabel && nullLabel[0] == '\0')) - { - PropertyDefaultDerivedTypeValue nullValue; - nullValue.factory = factory; - nullValue.factoryIndex = -1; - nullValue.label = nullLabel ? nullLabel : "[ null ]"; - model_->addDefaultType(baseType, nullValue); - } - - for(size_t i = 0; i < count; ++i) { - const Serialization::TypeDescription *desc = factory->descriptionByIndex((int)i); - if (!model_->defaultTypeRegistered(baseType, desc->name())){ - PropertyOArchive ar(model_, true); - ar.SetOutlineMode(outlineMode_); - ar.SetInnerContext(GetInnerContext()); - ar.SetFilter(GetFilter()); - - PropertyDefaultDerivedTypeValue defaultValue; - defaultValue.registeredName = desc->name(); - defaultValue.factory = factory; - defaultValue.factoryIndex = int(i); - defaultValue.label = desc->label(); - - model_->addDefaultType(baseType, defaultValue); - factory->serializeNewByIndex(ar, (int)i, "name", "label"); - if (ar.defaultValueRootNode() != 0) { - ar.defaultValueRootNode()->setTypeName(desc->name()); - defaultValue.root = ar.defaultValueRootNode(); - model_->addDefaultType(baseType, defaultValue); - } - } - } - } - - if(Serialization::SStruct ser = ptr.serializer()) - ser(*this); - closeStruct(name); - return true; -} - -bool PropertyOArchive::operator()(Serialization::ICallback& callback, const char* name, const char* label) -{ - if (!callback.SerializeValue(*this, name, label)) - return false; - - lastNode_->setCallback(callback.Clone()); - return true; -} - -bool PropertyOArchive::operator()(Serialization::Object& obj, const char *name, const char *label) -{ - PropertyRowObject* row = 0; - row = updateRow(name, label, obj.type().name(), obj); - - lastNode_ = row; - return true; -} - -bool PropertyOArchive::OpenBlock(const char* name, const char* label) -{ - PropertyRow* row = updateRow(name, label, "block", Serialization::SStruct()); - lastNode_ = currentNode_; - enterNode(row); - return true; -} - -void PropertyOArchive::ValidatorMessage(bool error, const void* handle, const Serialization::TypeID& type, const char* message) -{ - if (validator_) - { - ValidatorEntry entry(error ? VALIDATOR_ENTRY_ERROR : VALIDATOR_ENTRY_WARNING, - handle, - type, - message); - validator_->AddEntry(entry); - } -} - -void PropertyOArchive::DocumentLastField(const char* message) -{ - if (lastNode_ && (!currentNode_ || lastNode_->parent() == currentNode_)) - lastNode_->setTooltip(message ? message : ""); - else if (currentNode_) - currentNode_->setTooltip(message ? message : ""); -} - -void PropertyOArchive::CloseBlock() -{ - closeStruct("block"); -} - -void PropertyOArchive::SetOutlineMode(bool outlineMode) -{ - outlineMode_ = outlineMode; -} - -// vim:ts=4 sw=4: diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyOArchive.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyOArchive.h deleted file mode 100644 index 33be92466c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyOArchive.h +++ /dev/null @@ -1,112 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYOARCHIVE_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYOARCHIVE_H -#pragma once - - -#include "Serialization/IArchive.h" -#include "Serialization/Pointers.h" - -namespace Serialization -{ - class CEnumDescription; - class Object; - struct ICallback; -} - -class PropertyRow; -class PropertyTreeModel; -class ValidatorBlock; - -using Serialization::SharedPtr; - -class PropertyOArchive : public Serialization::IArchive{ -public: - PropertyOArchive(PropertyTreeModel* model, PropertyRow* root, ValidatorBlock* validator); - ~PropertyOArchive(); - - void SetOutlineMode(bool outlineMode); - - inline const SharedPtr& currentNode() const { - return currentNode_; - } - -protected: - bool operator()(Serialization::IString& value, const char* name, const char* label); - bool operator()(Serialization::IWString& value, const char* name, const char* label); - bool operator()(bool& value, const char* name, const char* label); - bool operator()(char& value, const char* name, const char* label); - - bool operator()(int8& value, const char* name, const char* label); - bool operator()(int16& value, const char* name, const char* label); - bool operator()(int32& value, const char* name, const char* label); - bool operator()(int64& value, const char* name, const char* label); - - bool operator()(uint8& value, const char* name, const char* label); - bool operator()(uint16& value, const char* name, const char* label); - bool operator()(uint32& value, const char* name, const char* label); - bool operator()(uint64& value, const char* name, const char* label); - - bool operator()(float& value, const char* name, const char* label); - bool operator()(double& value, const char* name, const char* label); - - bool operator()(const Serialization::SStruct& ser, const char* name, const char* label); - bool operator()(Serialization::IPointer& ptr, const char *name, const char *label); - bool operator()(Serialization::IContainer& ser, const char *name, const char *label); - bool operator()(Serialization::Object& obj, const char *name, const char *label); - bool operator()(Serialization::ICallback& ser, const char *name, const char *label); - using Serialization::IArchive::operator(); - - bool OpenBlock(const char* name, const char* label); - void CloseBlock(); - void ValidatorMessage(bool error, const void* handle, const Serialization::TypeID& type, const char* message); - void DocumentLastField(const char* docString); - -protected: - PropertyOArchive(PropertyTreeModel* model, bool forDefaultType); - -private: - struct Level { - std::vector > oldRows; - int rowIndex; - Level() : rowIndex(0) {} - }; - std::vector stack_; - - template - PropertyRow* updateRowPrimitive(const char* name, const char* label, const char* typeName, const ValueType& value, const void* handle, const Serialization::TypeID& typeId); - - template - RowType* updateRow(const char* name, const char* label, const char* typeName, const ValueType& value); - - void enterNode(PropertyRow* row); // sets currentNode - void closeStruct(const char* name); - PropertyRow* defaultValueRootNode(); - - bool updateMode_; - bool defaultValueCreationMode_; - PropertyTreeModel* model_; - ValidatorBlock* validator_; - SharedPtr currentNode_; - SharedPtr lastNode_; - - // for defaultArchive - SharedPtr rootNode_; - std::string typeName_; - const char* derivedTypeName_; - std::string derivedTypeNameAlt_; - bool outlineMode_; -}; - -// vim:ts=4 sw=4: - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYOARCHIVE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRow.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRow.cpp deleted file mode 100644 index 05b073cda6..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRow.cpp +++ /dev/null @@ -1,1906 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "QPropertyTree.h" -#include "QPropertyTreeStyle.h" -#include "PropertyTreeModel.h" -#include "PropertyRowContainer.h" -#include "PropertyDrawContext.h" -#include "Unicode.h" -#include "Serialization.h" -#include "Serialization/BinArchive.h" -#include "Serialization/Callback.h" -#include "Serialization/Decorators/IconXPM.h" - -#include -#include -#include -#include -#include -#include -#include "MathUtils.h" -#include "warning.xpm" -#include "error.xpm" - -#if 0 -# define DEBUG_TRACE(fmt, ...) printf(fmt "\n", __VA_ARGS__) -# define DEBUG_TRACE_ROW(fmt, ...) for(PropertyRow* zzzz = this; zzzz; zzzz = zzzz->parent()) printf(" "); printf(fmt "\n", __VA_ARGS__) -#else -# define DEBUG_TRACE(...) -# define DEBUG_TRACE_ROW(...) -#endif - -enum { TEXT_VALUE_SPACING = 3 }; - -QColor interpolateColor(const QColor& a, const QColor& b, float k) -{ - float mk = 1.0f - k; - return QColor(aznumeric_cast(a.red() * mk + b.red() * k), - aznumeric_cast(a.green() * mk + b.green() * k), - aznumeric_cast(a.blue() * mk + b.blue() * k), - aznumeric_cast(a.alpha() * mk + b.alpha() * k)); -} - -// --------------------------------------------------------------------------- - -template -static void visitPulledRows(PropertyRow* row, T& drawFunc) -{ - int count = (int)row->count(); - for (int i = 0; i < count; ++i) { - PropertyRow* child = row->childByIndex(i); - if (child->pulledUp() || child->pulledBefore()) { - drawFunc(child); - visitPulledRows(child, drawFunc); - } - } -}; - -// --------------------------------------------------------------------------- - -ConstStringList* PropertyRow::constStrings_ = 0; - -PropertyRow::PropertyRow() -{ - parent_ = 0; - callback_ = 0; - - expanded_ = false; - selected_ = false; - visible_ = true; - labelUndecorated_ = 0; - belongsToFilteredRow_ = false; - matchFilter_ = true; - - pos_ = QPoint(0, 0); - size_ = QPoint(-1, -1); - plusSize_ = 0; - textPos_ = 0; - textSizeInitial_ = 0; - textHash_ = 0; - textSize_ = 0; - widgetPos_ = 0; - widgetSize_ = 0; - userWidgetSize_ = -1; - heightIncludingChildren_ = 0; - - name_ = ""; - typeName_ = ""; - - pulledUp_ = false; - pulledBefore_ = false; - packedAfterPreviousRow_ = false; - hasPulled_ = false; - userReadOnly_ = false; - userReadOnlyRecurse_ = false; - userFullRow_ = false; - userPackCheckboxes_ = false; - userWidgetToContent_ = false; - multiValue_ = false; - fontWeight_ = FontWeight::Undefined; - userNonCopyable_ = false; - - label_ = ""; - labelChanged_ = true; - layoutChanged_ = true; - hideChildren_ = false; - validatorHasErrors_ = false; - validatorHasWarnings_ = false; - - tooltip_ = ""; -} - -PropertyRow::~PropertyRow() -{ - size_t count = children_.size(); - for (size_t i = 0; i < count; ++i) - if (children_[i]->parent() == this) - children_[i]->setParent(0); - if (callback_) - callback_->Release(); - callback_ = 0; -} - -void PropertyRow::setNames(const char* name, const char* label, const char* typeName) -{ - name_ = name; - label_ = label ? label : ""; - typeName_ = typeName; -} - -PropertyRow* PropertyRow::childByIndex(int index) -{ - if(index >= 0 && index < int(children_.size())) - return children_[index]; - else - return 0; -} - -const PropertyRow* PropertyRow::childByIndex(int index) const -{ - if(index >= 0 && index < int(children_.size())) - return children_[index]; - else - return 0; -} - -void PropertyRow::_setExpanded(bool expanded) -{ - expanded_ = expanded; - int numChildren = (int)children_.size(); - - for (int i = 0; i < numChildren; ++i) { - PropertyRow* child = children_[i]; - if(child->pulledUp()) - child->_setExpanded(expanded); - } - - layoutChanged_ = true; - setLayoutChangedToChildren(); - -} - -struct SetExpandedOp { - bool expanded_; - SetExpandedOp(bool expanded) : expanded_(expanded) {} - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, [[maybe_unused]] int index) - { - if(row->canBeToggled(tree)) - row->_setExpanded(expanded_); - return SCAN_CHILDREN_SIBLINGS; - } -}; - -void PropertyRow::setExpandedRecursive(QPropertyTree* tree, bool expanded) -{ - if(canBeToggled(tree)) - _setExpanded(expanded); - - SetExpandedOp op(expanded); - scanChildren(op, tree); -} - -int PropertyRow::childIndex(const PropertyRow* row) const -{ - YASLI_ASSERT(row); - Rows::const_iterator it = std::find(children_.begin(), children_.end(), row); - YASLI_ESCAPE(it != children_.end(), return -1); - return aznumeric_cast(std::distance(children_.begin(), it)); -} - -bool PropertyRow::isChildOf(const PropertyRow* row) const -{ - const PropertyRow* p = parent(); - while(p){ - if(p == row) - return true; - p = p->parent(); - } - return false; -} - -void PropertyRow::add(PropertyRow* row) -{ - children_.push_back(row); - row->setParent(this); -} - -void PropertyRow::addAfter(PropertyRow* row, PropertyRow* after) -{ - iterator it = std::find(children_.begin(), children_.end(), after); - if(it != children_.end()){ - ++it; - children_.insert(it, row); - } - else{ - children_.push_back(row); - } - - row->setParent(this); -} - -void PropertyRow::assignRowState(const PropertyRow& row, bool recurse) -{ - expanded_ = row.expanded_; - selected_ = row.selected_; - if(recurse){ - int numChildren = (int)children_.size(); - for (int i = 0; i < numChildren; ++i) { - PropertyRow* child = children_[i].get(); - YASLI_ESCAPE(child, continue); - int unusedIndex; - const PropertyRow* rhsChild = row.findFromIndex(&unusedIndex, child->name(), child->typeName(), i); - if(rhsChild) - child->assignRowState(*rhsChild, true); - } - } -} - -void PropertyRow::assignRowProperties(PropertyRow* row) -{ - YASLI_ESCAPE(row, return); - parent_ = row->parent_; - - userReadOnly_ = row->userReadOnly_; - userReadOnlyRecurse_ = row->userReadOnlyRecurse_; - userFixedWidget_ = row->userFixedWidget_; - pulledUp_ = row->pulledUp_; - pulledBefore_ = row->pulledBefore_; - size_ = row->size_; - pos_ = row->pos_; - plusSize_ = row->plusSize_; - textPos_ = row->textPos_; - textSizeInitial_ = row->textSizeInitial_; - textHash_ = row->textHash_; - textSize_ = row->textSize_; - widgetPos_ = row->widgetPos_; - widgetSize_ = row->widgetSize_; - userWidgetSize_ = row->userWidgetSize_; - userWidgetToContent_ = row->userWidgetToContent_; - callback_ = row->callback_; - row->callback_ = 0; - - assignRowState(*row, false); -} - -void PropertyRow::replaceAndPreserveState(PropertyRow* oldRow, PropertyRow* newRow, PropertyTreeModel* model) -{ - Rows::iterator it = std::find(children_.begin(), children_.end(), oldRow); - YASLI_ASSERT(it != children_.end()); - if(it != children_.end()){ - newRow->assignRowProperties(*it); - newRow->labelChanged_ = true; - *it = newRow; - if (model) - model->callRowCallback(newRow); - } -} - -void PropertyRow::erase(PropertyRow* row) -{ - PropertyRow* childToRemove = PropertyRow::findChildFromDescendant(row); - if(childToRemove) - { - childToRemove->setParent(nullptr); - children_.erase(std::find(children_.begin(), children_.end(), childToRemove)); - } -} - -void PropertyRow::swapChildren(PropertyRow* row, PropertyTreeModel* model) -{ - children_.swap(row->children_); - iterator it; - for( it = children_.begin(); it != children_.end(); ++it) - (**it).setParent(this); - for( it = row->children_.begin(); it != row->children_.end(); ++it) - (**it).setParent(row); - if (model){ - for(it = children_.begin(); it != children_.end(); ++it){ - PropertyRow* child = *it; - if (PropertyRow* srcChild = row->find(child->name(), child->label(), child->typeName())) { - child->setCallback(srcChild->callback_); - srcChild->setCallback(0); - model->callRowCallback(child); - } - } - } -} - -void PropertyRow::addBefore(PropertyRow* row, PropertyRow* before) -{ - if(before == 0) - children_.insert(children_.begin(), row); - else{ - iterator it = std::find(children_.begin(), children_.end(), before); - if(it != children_.end()) - children_.insert(it, row); - else - children_.push_back(row); - } - row->setParent(this); -} - -wstring PropertyRow::valueAsWString() const -{ - return toWideChar(valueAsString().c_str()); -} - -string PropertyRow::valueAsString() const -{ - return string(); -} - -SharedPtr PropertyRow::clone(ConstStringList* constStrings) const -{ - PropertyRow::setConstStrings(constStrings); - Serialization::BinOArchive oa; - SharedPtr self(const_cast(this)); - oa(self, "row", "Row"); - - Serialization::BinIArchive ia; - ia.open(oa); - SharedPtr clonedRow; - ia(clonedRow, "row", "Row"); - PropertyRow::setConstStrings(0); - if (clonedRow) - clonedRow->setHideChildren(hideChildren_); - return clonedRow; -} - -void PropertyRow::drawStaticText([[maybe_unused]] QPainter& p, [[maybe_unused]] const QRect& widgetRect) -{ -} - -void PropertyRow::Serialize(IArchive& ar) -{ - serializeValue(ar); - - ar(ConstStringWrapper(constStrings_, name_), "name", "name"); - ar(ConstStringWrapper(constStrings_, label_), "label", "label"); - ar(ConstStringWrapper(constStrings_, typeName_), "type", "type"); - ar(reinterpret_cast >&>(children_), "children", "!^children"); - if(ar.IsInput()){ - labelChanged_ = true; - layoutChanged_ = true; - PropertyRow::iterator it; - for(it = begin(); it != end(); ){ - PropertyRow* row = *it; - if(row){ - row->setParent(this); - ++it; - } - else{ - YASLI_ASSERT_STR(false, "Missing property row"); - it = erase(it); - } - } - } -} - -bool PropertyRow::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason != e.REASON_RELEASE) - return e.tree->spawnWidget(this, e.force); - else - return false; -} - -void PropertyRow::setLabelChanged() -{ - for(PropertyRow* row = this; row != 0; row = row->parent()) - row->labelChanged_ = true; -} - -void PropertyRow::setLayoutChanged() -{ - layoutChanged_ = true; -} - -void PropertyRow::setLabelChangedToChildren() -{ - size_t numChildren = children_.size(); - for (size_t i = 0; i < numChildren; ++i) { - children_[i]->labelChanged_ = true; - children_[i]->setLabelChangedToChildren(); - } -} - -void PropertyRow::setLayoutChangedToChildren() -{ - size_t numChildren = children_.size(); - for (size_t i = 0; i < numChildren; ++i) { - children_[i]->layoutChanged_ = true; - children_[i]->setLayoutChangedToChildren(); - } -} - -void PropertyRow::setLabel(const char* label) -{ - if (!label) - label = ""; - if (label_ != label) { - label_ = label; - setLabelChanged(); - } -} - -void PropertyRow::propagateFlagsTopToBottom() -{ - // these flags are reset in parseControlCodes - if (!userReadOnly_ && !userWidgetToContent_) - return; - size_t numChildren = children_.size(); - for (size_t i = 0; i < numChildren; ++i) { - PropertyRow* r = children_[i]; - if (userReadOnly_) - r->userReadOnly_ = true; - if (userWidgetToContent_) { - r->userWidgetToContent_ = true; - r->userFixedWidget_ = true; - } - r->propagateFlagsTopToBottom(); - } -} - -void PropertyRow::setTooltip(const char* tooltip) -{ - tooltip_ = tooltip; -} - -bool PropertyRow::setValidatorEntry(int index, int count) -{ - if (index != validatorIndex_ || count != validatorCount_) { - validatorIndex_ = min(index, 0xffff); - validatorCount_ = min(count, 0xff); - validatorsHeight_ = 0; - return true; - } - return false; -} - -void PropertyRow::resetValidatorIcons() -{ - validatorHasWarnings_ = false; - validatorHasErrors_ = false; -} - -void PropertyRow::addValidatorIcons(bool hasWarnings, bool hasErrors) -{ - if (hasWarnings ) - validatorHasWarnings_ = true; - if (hasErrors) - validatorHasErrors_ = true; -} - -void PropertyRow::updateLabel(const QPropertyTree* tree, [[maybe_unused]] int index, bool parentHidesNonInlineChildren) -{ - if (!labelChanged_) { - if (pulledUp_) - parent()->hasPulled_ = true; - return; - } - - hasPulled_ = false; - - int numChildren = (int)children_.size(); - for (int i = 0; i < numChildren; ++i) { - PropertyRow* row = children_[i]; - row->updateLabel(tree, i, hideChildren_); - } - - parseControlCodes(tree, label_, true); - bool hiddenByParentFlag = parentHidesNonInlineChildren && !pulledUp_; - visible_ = (*labelUndecorated_ != '\0' || userFullRow_ || pulledUp_ || isRoot()) && !hiddenByParentFlag; - - propagateFlagsTopToBottom(); - - if(pulledContainer()) - pulledContainer()->_setExpanded(expanded()); - - layoutChanged_ = true; - labelChanged_ = false; -} - -struct ResetSerializerOp{ - ScanResult operator()(PropertyRow* row) - { - row->setSerializer(SStruct()); - return SCAN_CHILDREN_SIBLINGS; - } -}; - -void PropertyRow::parseControlCodes(const QPropertyTree* tree, const char* ptr, bool changeLabel) -{ - if (changeLabel) { - userFullRow_ = false; - pulledUp_ = false; - pulledBefore_ = false; - userFixedWidget_ = false; - userPackCheckboxes_ = false; - userWidgetSize_ = -1; - userWidgetToContent_ = false; - fontWeight_ = FontWeight::Undefined; - userNonCopyable_ = false; - } - - while(true){ - if(*ptr == '^'){ - if(parent() && !parent()->isRoot()){ - if(pulledUp_) - pulledBefore_ = true; - pulledUp_ = true; - parent()->hasPulled_ = true; - - if(pulledUp() && isContainer()) - parent()->setPulledContainer(this); - } - } - else if(*ptr == '='){ - userWidgetToContent_ = true; - } - else if(*ptr == '+'){ - bool isFirstUpdate = labelUndecorated_ == 0; - if (isFirstUpdate) - _setExpanded(true); - } - else if(*ptr == '-'){ - bool isFirstUpdate = labelUndecorated_ == 0; - if (isFirstUpdate) - _setExpanded(false); - } - else if(*ptr == '<') - userFullRow_ = true; - else if(*ptr == '>'){ - userFixedWidget_ = true; - const char* p = ++ptr; - while(*p >= '0' && *p <= '9') - ++p; - if(*p == '>'){ - userWidgetSize_ = atoi(ptr); - ptr = ++p; - } - continue; - } - else if(*ptr == '~'){ - ResetSerializerOp op; - scanChildren(op); - } - else if(*ptr == '!'){ - if(userReadOnly_) - userReadOnlyRecurse_ = true; - userReadOnly_ = true; - } - else if(*ptr == '|'){ - userPackCheckboxes_ = true; - } - else if(*ptr == '['){ - ++ptr; - PropertyRow::iterator it; - for(it = children_.begin(); it != children_.end(); ++it) - (*it)->parseControlCodes(tree, ptr, false); - - int counter = 1; - while(*ptr){ - if(*ptr == ']' && !--counter) - break; - else if(*ptr == '[') - ++counter; - ++ptr; - } - } - else if(*ptr == '@'){ - switch (ptr[1]) - { - case 'b': case 'B': - fontWeight_ = FontWeight::Bold; - ++ptr; - break; - - case 'r': case 'R': - fontWeight_ = FontWeight::Regular; - ++ptr; - break; - - default: - break; - } - } - else if(*ptr == ':'){ - userNonCopyable_ = true; - } - else - break; - ++ptr; - } - - if (isContainer()) { - // automatically inline children for short arrays - PropertyRowContainer* container = static_cast(this); - int numChildren = (int)container->count(); - if (container->isFixedSize() && numChildren > 0 && numChildren <= 4) { - if (container->childByIndex(0)->inlineInShortArrays()) { - for(int i = 0; i < numChildren; ++i) { - PropertyRow* child = container->childByIndex(i); - child->pulledUp_ = true; - if (child->label_) - child->labelUndecorated_ = child->label_ + strlen(child->label_); - } - hasPulled_ = true; - container->setInlined(true); - } - } - } - - if (changeLabel) - labelUndecorated_ = ptr; - - labelChanged(); -} - -const char* PropertyRow::typeNameForFilter([[maybe_unused]] QPropertyTree* tree) const -{ - return typeName(); -} - -void PropertyRow::updateTextSizeInitial(const QPropertyTree* tree, int index, bool fontChanged) -{ - char containerLabel[1024] = ""; - const char* text = rowText(containerLabel, sizeof(containerLabel), tree, index); - if(text[0] == '\0' || widgetPlacement() == WIDGET_INSTEAD_OF_TEXT) { - textSizeInitial_ = 0; - textHash_ = 0; - } - else{ - unsigned hash = calculateHash(text); - const QFont* font = rowFont(tree); - hash = calculateHash(font, hash); - if(hash != textHash_ || fontChanged){ - QFontMetrics fm(*font); - textSizeInitial_ = fm.horizontalAdvance(text); - textHash_ = hash; - } - } -} - -void PropertyRow::calculateMinimalSize(const QPropertyTree* tree, int posX, int availableWidth, bool force, int* _extraSizeRemainder, int* _extraSize, int index) -{ - PropertyRow* nonPulled = nonPulledParent(); - if (!layoutChanged_ && !force && !nonPulled->layoutChanged_) { - DEBUG_TRACE_ROW("... skipping size for %s", label()); - return; - } - plusSize_ = 0; - if(isRoot()) - expanded_ = true; - else{ - if(nonPulled->isRoot() || (tree->treeStyle().compact && nonPulled->parent()->isRoot())) - _setExpanded(true); - else if(!pulledUp()) - plusSize_ = int(tree->treeStyle().firstLevelIndent * tree->_defaultRowHeight()); - - if(parent()->pulledUp()) - pulledBefore_ = false; - - if(!visible(tree) && !(isContainer() && pulledUp())){ - size_ = QPoint(0, 0); - DEBUG_TRACE_ROW("row '%s' got zero size", label()); - layoutChanged_ = false; - return; - } - } - - int minWidgetSize = widgetSizeMin(tree); - widgetSize_ = minWidgetSize; - if (_extraSizeRemainder && *_extraSizeRemainder) { - widgetSize_ += *_extraSizeRemainder; - *_extraSizeRemainder = 0; - } - - updateTextSizeInitial(tree, index, force); - - int height = isRoot() ? 0 : tree->_defaultRowHeight() + floorHeight(); - size_.setY(height); - - pos_.setX(posX); - posX += plusSize_; - - int extraSizeStorage = 0; - int& extraSize = !pulledUp() || !_extraSize ? extraSizeStorage : *_extraSize; - - int validatorIconsWidth = 0; - if (validatorHasErrors_) - validatorIconsWidth += tree->_defaultRowHeight(); - if (validatorHasWarnings_) - validatorIconsWidth += tree->_defaultRowHeight(); - - int freePulledChildren = 0; - if(!pulledUp()){ - int minTextSize = 0; - int totalMinimalWidth = 0; - calcPulledRows(&minTextSize, &freePulledChildren, &totalMinimalWidth, tree, index); - DEBUG_TRACE_ROW("%s minTextSize: %i, totalMinimalWidth: %i", label(), minTextSize, totalMinimalWidth); - size_.setX(totalMinimalWidth); - extraSize = (tree->rightBorder() - tree->leftBorder()) - totalMinimalWidth - posX - validatorIconsWidth; - DEBUG_TRACE_ROW("%s extraSize 0: %i", label(), extraSize); - - float textScale = 1.0f; - bool hideOwnText = false; - if(extraSize < 0){ - // hide container item text first - if (parent() && parent()->isContainer()){ - extraSize += textSizeInitial_; - minTextSize -= textSizeInitial_; - hideOwnText = true; - } - - textScale = minTextSize ? clamp(1.0f - float(-extraSize) / minTextSize, 0.0f, 1.0f) : 0; - } - setTextSize(tree, index, textScale); - - if (hideOwnText) { - textSize_ = 0; - DEBUG_TRACE_ROW("%s hideOwnText", label()); - } - } - - DEBUG_TRACE_ROW("%s extraSize 1: %i", label(), extraSize); - - WidgetPlacement widgetPlace = widgetPlacement(); - - int numChildren = (int)children_.size(); - - if(widgetPlace == WIDGET_ICON){ - if (tree->treeStyle().alignLabelsToRight && !pulledUp_ && !pulledBefore_ && !hasPulled_ && numChildren == 0) - widgetPos_ = widgetSize_ ? tree->leftBorder() + xround((tree->rightBorder() - tree->leftBorder())* (1.f - tree->treeStyle().valueColumnWidth)) : -1000; - else - widgetPos_ = widgetSize_ ? posX : -1000; - posX += widgetSize_; - if (tree->treeStyle().alignLabelsToRight) - textPos_ = widgetPos_ + widgetSize_ + TEXT_VALUE_SPACING; - else - textPos_ = posX; - posX += textSize_; - } - - bool hasPulledBefore = false; - if (hasPulled_) { - for (int i = 0; i < numChildren; ++i) { - PropertyRow* row = children_[i]; - if(row->visible(tree) && row->pulledBefore()){ - row->calculateMinimalSize(tree, posX, availableWidth, force, 0, &extraSize, i); - posX += row->size_.x(); - hasPulledBefore = true; - } - } - if (hasPulledBefore) - posX += TEXT_VALUE_SPACING; - } - - if(widgetPlace != WIDGET_ICON){ - textPos_ = posX; - posX += textSize_; - } - - if(widgetPlace == WIDGET_AFTER_NAME){ - if (textSize_) - posX += TEXT_VALUE_SPACING; - widgetPos_ = posX; - posX += widgetSize_; - } - - if (widgetPlace == WIDGET_INSTEAD_OF_TEXT) - widgetPos_ = posX; - - if(widgetPlace == WIDGET_VALUE || widgetPlace == WIDGET_AFTER_PULLED || (freePulledChildren > 0)){ - if (textSize_) - posX += TEXT_VALUE_SPACING; - - if(!pulledUp() && extraSize > 0){ - // align widget value to value column - if(!isFullRow(tree)) - { - int oldX = posX; - - bool rightAlignment = tree->treeStyle().alignLabelsToRight && !hasPulledBefore; - int maxX = rightAlignment ? textSize_ + TEXT_VALUE_SPACING: posX; - int newX = max(tree->leftBorder() + xround((tree->rightBorder() - tree->leftBorder())* (1.f - tree->treeStyle().valueColumnWidth)), maxX); - - if (rightAlignment) { - textPos_ = newX - textSize_ - TEXT_VALUE_SPACING; - widgetPos_ = textPos_ - widgetSize_ - TEXT_VALUE_SPACING; - } - - int xDelta = newX - oldX; - if (xDelta <= extraSize) - { - extraSize -= xDelta; - posX = newX; - } - else - { - posX += extraSize; - extraSize = 0; - } - } - } - } - - int extraSizeRemainder = 0; - if (freePulledChildren > 0) { - extraSizeRemainder = extraSize % freePulledChildren; - extraSize = extraSize / freePulledChildren; - } - - if (widgetPlace == WIDGET_VALUE || widgetPlace == WIDGET_INSTEAD_OF_TEXT) { - if(minWidgetSize && !isWidgetFixed() && extraSize > 0) { - DEBUG_TRACE_ROW("%s widget extraSize: %i+%d", label(), extraSize, extraSizeRemainder); - widgetSize_ += extraSize + extraSizeRemainder; - extraSizeRemainder = 0; - } - - if (widgetPlace != WIDGET_INSTEAD_OF_TEXT) - widgetPos_ = posX; - DEBUG_TRACE_ROW("textSize: %i widgetPos: %i", int(textSize_), int(widgetPos_)); - posX += widgetSize_; - } - - size_.setX(textSize_ + (textSize_ ? TEXT_VALUE_SPACING : 0) + widgetSize_ + validatorIconsWidth); - - int childrenLeft = nonPulled->pos_.x(); - if (parent() != 0){ - if (parent()->parent() == 0) { - if (!tree->treeStyle().doNotIndentSecondLevel) - childrenLeft = aznumeric_cast(childrenLeft + tree->treeStyle().firstLevelIndent * tree->_defaultRowHeight()); - } - else - childrenLeft = aznumeric_cast(childrenLeft + tree->treeStyle().levelIndent * tree->_defaultRowHeight()); - } - - int checkBoxChildren = 0; - for (int i = 0; i < numChildren; ++i) { - PropertyRow* row = children_[i]; - if(!row->visible(tree)) { - DEBUG_TRACE_ROW("skipping invisible child: %s", row->label()); - continue; - } - if(row->pulledUp()){ - if(!row->pulledBefore()){ - row->calculateMinimalSize(tree, posX, availableWidth, force, &extraSizeRemainder, &extraSize, i); - posX += row->size_.x(); - posX += TEXT_VALUE_SPACING; - } - size_.setX(size_.x() + TEXT_VALUE_SPACING + row->size_.x()); - size_.setY(max(size_.y(), row->size_.y())); - } - else if(expanded()){ - - row->calculateMinimalSize(tree, childrenLeft, availableWidth, force, 0, &extraSize, i); - if (row->widgetPlacement() == WIDGET_ICON && row->count() == 0) - ++checkBoxChildren; - } - } - - // align checkboxes into two columns - if (tree->packCheckboxes() || userPackCheckboxes_) { - if (expanded() && checkBoxChildren > 0 && hasVisibleChildren(tree)) { - int widthTotal = tree->rightBorder() - 16 - childrenLeft - plusSize_; - int widthNextToLastCheckbox = 0; - int left = childrenLeft + plusSize_; - PropertyRow* previousCheckbox = nullptr; - - std::vector checkboxesToRealign; - bool hasChanges = false; - - for (int i = 0; i < numChildren; ++i) { - PropertyRow* row = children_[i]; - if(!row->visible(tree)) - continue; - if(row->widgetPlacement() != WIDGET_ICON || row->count() > 0) { - previousCheckbox = 0; - continue; - } - if(!row->pulledUp()){ - int checkboxWidth = row->textSize_ + tree->_defaultRowHeight()/* + TEXT_VALUE_SPACING*/; - - if (previousCheckbox && widthNextToLastCheckbox >= widthTotal / 2 && checkboxWidth < widthTotal / 2) { - row->packedAfterPreviousRow_ = true; - widthNextToLastCheckbox = 0; - - row->pos_.setX(left + widthTotal / 2); - row->widgetPos_ = row->pos_.x(); - row->textPos_ = row->pos_.x() + row->widgetSize_; - row->size_.setX(widthTotal / 2); - - previousCheckbox->size_.setX(widthTotal / 2); - previousCheckbox->pos_.setX(left); - previousCheckbox->widgetPos_ = left; - previousCheckbox->textPos_ = left + previousCheckbox->widgetSize_; - row->size_.setX(widthTotal / 2); - previousCheckbox = 0; - hasChanges = true; - } - else { - row->packedAfterPreviousRow_ = false; - widthNextToLastCheckbox = widthTotal - checkboxWidth; - previousCheckbox = row; - } - - if (previousCheckbox && tree->treeStyle().alignLabelsToRight) - checkboxesToRealign.push_back(previousCheckbox); - } - } - - if (hasChanges) { - for (int i = 0; i < checkboxesToRealign.size(); ++i) { - PropertyRow* row = checkboxesToRealign[i]; - row->size_.setX(widthTotal / 2); - row->pos_.setX(left); - row->widgetPos_ = left; - row->textPos_ = left + row->widgetSize_; - } - } - } - } - - if (widgetPlace == WIDGET_AFTER_PULLED) - { - posX += TEXT_VALUE_SPACING; - widgetPos_ = posX; - } - - if(!pulledUp()) - size_.setX(tree->rightBorder() - pos_.x()); - DEBUG_TRACE_ROW("calculateMinimalSize: '%s' %i %i (%s)", label(), size_.x(), size_.y(), isRoot() ? "root" : "non-root"); - layoutChanged_ = false; - - validatorsHeight_ = 0; - if (!pulledUp() && !pulledBefore() && (validatorCount_ != 0 || hasPulled_)) { - QFontMetrics fm(tree->font()); - int padding = aznumeric_cast(0.1f * tree->_defaultRowHeight()); - auto calculateValidatorHeight = [&](PropertyRow* row) { - const ValidatorEntry* entries = tree->_validatorBlock()->GetEntry(row->validatorIndex_, row->validatorCount_); - if (entries) { - for (int i = 0; i < row->validatorCount_; ++i) { - int startPos = pos_.x() + plusSize_; - QRect r = fm.boundingRect(0, 0, availableWidth - startPos - tree->_defaultRowHeight() - padding * 2, 0, - Qt::TextWordWrap|Qt::AlignTop, QString::fromUtf8(entries[i].message.c_str())); - validatorsHeight_ += max(tree->_defaultRowHeight(), r.height() + padding * 2) + padding * 3; - } - } - }; - calculateValidatorHeight(this); - visitPulledRows(this, calculateValidatorHeight); - } - - size_.setY(size_.y() + validatorsHeight_); -} - -void PropertyRow::adjustVerticalPosition(const QPropertyTree* tree, int& totalHeight) -{ - int defaultRowHeight = tree->_defaultRowHeight(); - pos_.setY(totalHeight); - int rowHeight = size_.y() + int(defaultRowHeight * (tree->treeStyle().rowSpacing - 1.0f) + 0.5f); - - if (packedAfterPreviousRow_) - pos_.setY(totalHeight - rowHeight); - else - pos_.setY(totalHeight); - - if(!pulledUp()) { - if (!packedAfterPreviousRow_) - totalHeight += rowHeight; - } - else{ - pos_.setY(parent()->pos_.y()); - expanded_ = parent()->expanded(); - } - PropertyRow* nonPulled = nonPulledParent(); - - DEBUG_TRACE_ROW("adjustRect: %s %i %i %i %i %s", label(), pos_.x(), pos_.y(), size_.x(), size_.y(), pulledUp() ? "pulled" : ""); - - if (expanded_ || hasPulled_) { - for(PropertyRows::iterator it = children_.begin(); it != children_.end(); ++it){ - PropertyRow* row = *it; - if(row->visible(tree) && (nonPulled->expanded() || row->pulledUp())) - row->adjustVerticalPosition(tree, totalHeight); - } - } - int delta = totalHeight - pos_.y(); - if (delta > USHRT_MAX) - delta = USHRT_MAX; - heightIncludingChildren_ = delta; -} - -void PropertyRow::setTextSize(const QPropertyTree* tree, int index, float mult) -{ - updateTextSizeInitial(tree, index, false); - - textSize_ = int(textSizeInitial_ * mult); - - size_t numChildren = children_.size(); - for (size_t i = 0; i < numChildren; ++i) { - PropertyRow* row = children_[i]; - if(row->pulledUp()) - row->setTextSize(tree, 0, mult); - } -} - -void PropertyRow::calcPulledRows(int* minTextSize, int* freePulledChildren, int* minimalWidth, const QPropertyTree *tree, int index) -{ - updateTextSizeInitial(tree, index, false); - - *minTextSize += textSizeInitial_; - WidgetPlacement widgetPlace = widgetPlacement(); - if((widgetPlace == WIDGET_VALUE || widgetPlace == WIDGET_INSTEAD_OF_TEXT || widgetPlace == WIDGET_AFTER_PULLED) && !isWidgetFixed()) - *freePulledChildren += 1; - *minimalWidth += textSizeInitial_ + widgetSizeMin(tree); // spacing - bool hasWidget = widgetPlace == WIDGET_VALUE || - widgetPlace == WIDGET_INSTEAD_OF_TEXT || - widgetPlace == WIDGET_AFTER_PULLED; - if (textSizeInitial_ && (hasWidget || hasPulled_)) - *minimalWidth += TEXT_VALUE_SPACING; - if (hasWidget && hasPulled_) - *minimalWidth += TEXT_VALUE_SPACING; - - size_t numChildren = children_.size(); - int pulledCount = 0; - for (size_t i = 0; i < numChildren; ++i) { - PropertyRow* row = children_[i]; - if(row->pulledUp()) - { - ++pulledCount; - row->calcPulledRows(minTextSize, freePulledChildren, minimalWidth, tree, index); - } - } - if (hasPulled_) - *minimalWidth += (pulledCount - 1) * TEXT_VALUE_SPACING; -} - -PropertyRow* PropertyRow::findSelected() -{ - if(selected()) - return this; - iterator it; - for(it = children_.begin(); it != children_.end(); ++it){ - PropertyRow* result = (*it)->findSelected(); - if(result) - return result; - } - return 0; -} - -PropertyRow* PropertyRow::find(const char* name, const char* nameAlt, const char* typeName) -{ - iterator it; - for(it = children_.begin(); it != children_.end(); ++it){ - PropertyRow* row = *it; - if(((row->name() == name) || strcmp(row->name(), name) == 0) && - ((nameAlt == 0) || (row->label() != 0 && strcmp(row->label(), nameAlt) == 0)) && - ((typeName == 0) || (row->typeName() != 0 && strcmp(row->typeName(), typeName) == 0))) - return row; - } - return 0; -} - -PropertyRow* PropertyRow::findFromIndex(int* outIndex, const char* name, const char* typeName, int startIndex) const -{ - int numChildren = (int)children_.size(); - startIndex = min(startIndex, numChildren); - - for (int i = startIndex; i < numChildren; ++i) { - PropertyRow* row = children_[i]; - if(((row->name() == name) || strcmp(row->name(), name) == 0) && - ((row->typeName() == typeName || strcmp(row->typeName(), typeName) == 0))) { - *outIndex = i; - return row; - } - } - - for (int i = 0; i < startIndex; ++i) { - PropertyRow* row = children_[i]; - if(((row->name() == name) || strcmp(row->name(), name) == 0) && - ((row->typeName() == typeName || strcmp(row->typeName(), typeName) == 0))) { - *outIndex = i; - return row; - } - } - - *outIndex = -1; - return 0; -} - -const PropertyRow* PropertyRow::find(const char* name, const char* nameAlt, const char* typeName) const -{ - return const_cast(this)->find(name, nameAlt, typeName); -} - -bool PropertyRow::processesKey([[maybe_unused]] QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete && ev->modifiers() == Qt::NoModifier) - { - return true; - } - else if (ev->key() == Qt::Key_Insert && ev->modifiers() == Qt::SHIFT) - { - return true; - } - - return false; -} - -bool PropertyRow::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if(parent() && parent()->isContainer() && !parent()->userReadOnly()){ - PropertyRowContainer* container = static_cast(parent()); - std::unique_ptr menuHandler = - std::unique_ptr(createMenuHandler(tree, container)); - menuHandler->element = this; - if(ev->key() == Qt::Key_Delete && ev->modifiers() == Qt::NoModifier) { - menuHandler->onMenuChildRemove(); - return true; - } - else if(ev->key() == Qt::Key_Insert && ev->modifiers() == Qt::SHIFT){ - menuHandler->onMenuChildInsertBefore(); - return true; - } - } - return false; -} - -ContainerMenuHandler* PropertyRow::createMenuHandler(QPropertyTree* tree, PropertyRowContainer* container) -{ - return new ContainerMenuHandler(tree, container); -} - -bool PropertyRow::onContextMenu(QMenu &menu, QPropertyTree* tree) -{ - PropertyRowContainer* container = 0; - if (parent() && parent()->isContainer()) - container = static_cast(parent()); - if (!container) { - PropertyRow* nonPulled = nonPulledParent(); - if (nonPulled->parent() && nonPulled->parent()->isContainer()) - container = static_cast(nonPulled->parent()); - } - if(container){ - PropertyRow* containerElement = this; - ContainerMenuHandler* handler = createMenuHandler(tree, container); - handler->element = containerElement; - tree->addMenuHandler(handler); - if(!container->isFixedSize()){ - if(!menu.isEmpty()) - { - menu.addSeparator(); - } - - menu.addAction("Insert Before", handler, SLOT(onMenuChildInsertBefore()), QKeySequence("Shift+Insert"))->setEnabled(!container->userReadOnly()); - menu.addAction("Remove", handler, SLOT(onMenuChildRemove()), QKeySequence("Delete"))->setEnabled(!container->userReadOnly()); - } - } - - if(hasVisibleChildren(tree)){ - if(!menu.isEmpty()) - { - menu.addSeparator(); - } - - menu.addAction("Expand", tree, SLOT(expandAll())); - menu.addAction("Collapse", tree, SLOT(collapseAll())); - } - - return !menu.isEmpty(); -} - -int PropertyRow::level() const -{ - int result = 0; - const PropertyRow* row = this; - while(row){ - row = row->parent(); - ++result; - } - return result; -} - -PropertyRow* PropertyRow::nonPulledParent() -{ - PropertyRow* row = this; - while(row->pulledUp()) - row = row->parent(); - return row; -} - -bool PropertyRow::pulledSelected() const -{ - if(selected()) - return true; - const PropertyRow* row = this; - while(row->parent() && row->pulledUp()){ - row = row->parent(); - if(row->selected()) - return true; - } - return false; -} - - -const QFont* PropertyRow::rowFont(const QPropertyTree* tree) const -{ - switch (fontWeight_) - { - case FontWeight::Regular: - return &tree->font(); - - case FontWeight::Bold: - return &tree->_boldFont(); - - default: - // Bold for structures/containers - return hasVisibleChildren(tree) || (isContainer() && !static_cast(this)->isInlined()) ? &tree->_boldFont() : &tree->font(); - } -} - -QRect PropertyRow::rectIncludingChildren(const QPropertyTree* tree) const -{ - QRect r = rect(); - if (expanded()) - for (size_t i = 0; i < children_.size(); ++i) - if (children_[i]->visible(tree)) - r = r.united(children_[i]->rectIncludingChildren(tree)); - return r; -} - -static void drawVerticalGradient(QPainter& painter, const QRect& rect, const QColor& topColor, const QColor& bottomColor) -{ - QLinearGradient gradient(rect.left(), rect.top(), rect.left(), rect.bottom()); - gradient.setColorAt(0.0f, topColor); - gradient.setColorAt(1.0f, bottomColor); - painter.fillRect(rect, QBrush(gradient)); -} - - -void PropertyRow::drawRow(QPainter& painter, const QPropertyTree* tree, int index, bool selectionPass) -{ - QRect rowRect = rect(); - QRect selectionRect = rowRect; - if (!isRoot()) { - bool selectionDrawn = !tree->hideSelection() || tree->hasFocusOrInplaceHasFocus(); - if(!pulledUp()) - selectionRect = rowRect.adjusted(plusSize_ - (tree->treeStyle().compact ? 2 : 3), -2, 1, 1); - else - selectionRect = rowRect.adjusted(-2, -2, 2, 1); - if (selectionPass) { - if (tree->treeStyle().groupShadows && this->level() == 2 && !children_.empty()) { - QRect childrenRect = this->rectIncludingChildren(tree); - int top = rowRect.bottom() + 2; - if (top < childrenRect.bottom()) - { - childrenRect = QRect(-tree->leftBorder(), top, tree->width() - 16 + tree->leftBorder(), childrenRect.bottom() + 3 - top); - QColor windowColor = tree->palette().color(QPalette::Button); - QColor shadowColor = tree->palette().color(QPalette::Mid); - QColor backgroundColor(interpolateColor(windowColor, shadowColor, tree->treeStyle().groupShade)); - painter.fillRect(childrenRect, QBrush(backgroundColor)); - - int levelShadowOpacity = tree->treeStyle().levelShadowOpacity; - int h = int(tree->_defaultRowHeight() * 0.75f); - drawVerticalGradient(painter, QRect(childrenRect.left()+1, childrenRect.top(), childrenRect.width()-2, h), QColor(0, 0, 0, levelShadowOpacity), QColor(0, 0, 0, 0)); - drawVerticalGradient(painter, QRect(childrenRect.left(), childrenRect.top(), 1, h*2), QColor(0, 0, 0, levelShadowOpacity), QColor(0, 0, 0, 0)); - drawVerticalGradient(painter, QRect(childrenRect.width()-2, childrenRect.top(), 1, h*2), QColor(0, 0, 0, levelShadowOpacity), QColor(0, 0, 0, 0)); - - h = (int(tree->_defaultRowHeight() * 0.25f)); - drawVerticalGradient(painter, QRect(childrenRect.left() + 1, childrenRect.bottom() - h, childrenRect.width() - 2, h), QColor(0, 0, 0, 0), QColor(0, 0, 0, levelShadowOpacity)); - drawVerticalGradient(painter, QRect(childrenRect.left(), childrenRect.bottom() - h*2, 1, h*2), QColor(0, 0, 0, 0), QColor(0, 0, 0, levelShadowOpacity)); - drawVerticalGradient(painter, QRect(childrenRect.width()-2, childrenRect.bottom() - h*2, 1, h*2), QColor(0, 0, 0, 0), QColor(0, 0, 0, levelShadowOpacity)); - } - } - if (tree->treeStyle().groupRectangle && this->level() < 3 && (canBeToggled(tree) || isContainer() || widgetPlacement() == WIDGET_NONE)) - { - QColor windowColor = tree->palette().color(QPalette::Button); - QColor shadowColor = tree->palette().color(QPalette::Mid); - QColor backgroundColor(interpolateColor(windowColor, shadowColor, tree->treeStyle().groupShade)); - painter.setRenderHint(QPainter::Antialiasing, true); - painter.setBrush(QBrush(backgroundColor)); - painter.setPen(Qt::NoPen); - painter.drawRoundedRect(rowRect.adjusted(0, tree->_defaultRowHeight() / 8, 0, -tree->_defaultRowHeight() / 8), 4, 4); - painter.setRenderHint(QPainter::Antialiasing, false); - - } - } - else{ - PropertyDrawContext context; - context.tree = tree; - context.widgetRect = widgetRect(tree); - context.lineRect = floorRect(tree); - context.painter = &painter; - context.captured = tree->_isCapturedRow(this); - context.m_pressed = tree->_pressedRow() == this; - - QColor textColor = tree->palette().buttonText().color(); - - char containerLabel[1024] = ""; - wstring text = toWideChar(rowText(containerLabel, sizeof(containerLabel), tree, index)); - - if (tree->treeStyle().showHorizontalLines) { - if(textSize_ && !isStatic() && widgetPlacement() == WIDGET_VALUE && - !pulledUp() && !isFullRow(tree) && !hasPulled() && floorHeight() == 0) - { - QRect rect(textPos_ - 1, rowRect.bottom() - 2, context.lineRect.width() - (textPos_ - 1), 1); - - QLinearGradient gradient(rect.left(), rect.top(), rect.right(), rect.top()); - gradient.setColorAt(0.0f, tree->palette().color(QPalette::Button)); - gradient.setColorAt(0.6f, tree->palette().color(QPalette::Light)); - gradient.setColorAt(0.95f, tree->palette().color(QPalette::Light)); - gradient.setColorAt(1.0f, tree->palette().color(QPalette::Button)); - QBrush brush(gradient); - painter.fillRect(rect, brush); - } - } - - - if(selectionDrawn && pulledSelected()){ - textColor = tree->palette().highlight().color(); - } - else{ - overrideTextColor(textColor); - } - - if(!tree->treeStyle().compact || !parent()->isRoot()){ - if(hasVisibleChildren(tree)){ - drawPlus(painter, tree, plusRect(tree), expanded(), selected(), expanded()); - } - } - - if(!isStatic() && context.widgetRect.isValid()) - redraw(context); - - if(textSize_ > 0){ - const QFont* font = rowFont(tree); - tree->_drawRowLabel(painter, text.c_str(), font, textRect(tree), textColor); - } - - if (validatorHasWarnings_) { - QImage* icon = tree->_iconCache()->getImageForIcon(Serialization::IconXPM(warning_xpm)); - - QRect r = validatorWarningIconRect(tree); - r.setWidth(tree->_defaultRowHeight()); - painter.drawImage(r.center() - QPoint(icon->width() / 2, icon->height() / 2), *icon); - } - if (validatorHasErrors_) { - QImage* icon = tree->_iconCache()->getImageForIcon(Serialization::IconXPM(error_xpm)); - QRect r = validatorErrorIconRect(tree); - r.setWidth(tree->_defaultRowHeight()); - painter.drawImage(r.center() - QPoint(icon->width() / 2, icon->height() / 2), *icon); - } - } - } - - if (!selectionPass && validatorsHeight_ > 0) - { - QRect totalRect = validatorRect(tree); - QFontMetrics fm(tree->font()); - const int padding = aznumeric_cast(tree->_defaultRowHeight() * 0.1f); - int offset = padding; - auto drawFunc = [&](PropertyRow* row) { - if (const ValidatorEntry* validatorEntries = tree->_validatorBlock()->GetEntry(row->validatorIndex_, row->validatorCount_)) { - for (int i = 0; i < row->validatorCount_; ++i) { - const ValidatorEntry* validatorEntry = validatorEntries + i; - bool isError = validatorEntry->type == VALIDATOR_ENTRY_ERROR; - - QImage* icon = tree->_iconCache()->getImageForIcon(isError ? Serialization::IconXPM(error_xpm) : Serialization::IconXPM(warning_xpm)); - QColor brushColor = isError ? QColor(255, 64, 64, 192) : QPalette().color(QPalette::ToolTipBase); - QColor penColor = isError ? QColor(64, 0, 0, 255) : QPalette().color(QPalette::ToolTipText); - - QRect rect(totalRect.left(), totalRect.top() + offset, - totalRect.width(), totalRect.height() - offset); - QRect textRect = rect.adjusted(tree->_defaultRowHeight() + padding, padding, -padding, -padding); - const char* text = validatorEntry->message.c_str(); - int textHeight = max(tree->_defaultRowHeight(), - fm.boundingRect(textRect, Qt::TextWordWrap, text, 0, 0).height() + padding * 2); - rect.setHeight(textHeight + padding * 2); - textRect.setHeight(textHeight); - - QPen pen(penColor); - pen.setWidth(1); - painter.setPen(QPen(penColor)); - painter.setRenderHint(QPainter::Antialiasing); - painter.setBrush(brushColor); - painter.translate(-0.5f, -0.5f); - painter.drawRoundedRect(rect, 5, 5, Qt::AbsoluteSize); - painter.translate(0.5f, 0.5f); - painter.setPen(penColor); - painter.setBrush(QBrush()); - QTextOption opt; - opt.setWrapMode(QTextOption::WordWrap); - opt.setAlignment(Qt::AlignLeft | Qt::AlignVCenter); - painter.drawText(textRect, text, opt); - textRect.setHeight(0xffff); - QRect iconRect(rect.left(), rect.top(), tree->_defaultRowHeight(), rect.height()); - painter.drawImage(iconRect.center() - QPoint(icon->width() / 2, icon->height() / 2), *icon); - offset += rect.height() + padding; - } - } - }; - drawFunc(this); - visitPulledRows(this, drawFunc); - } -} - -void PropertyRow::drawPlus(QPainter& p, const QPropertyTree* tree, const QRect& rect, bool expanded, [[maybe_unused]] bool selected, [[maybe_unused]] bool grayed) const -{ - QStyleOption option; - option.rect = rect; - option.state = QStyle::State_Enabled | QStyle::State_Children; - if (expanded) - option.state |= QStyle::State_Open; - p.setPen(QPen()); - p.setBrush(QBrush()); - - // create a widget for context so that the stylesheet is applied: - QWidget tempWidgetForContext; - QStyle::PrimitiveElement elementToUse = QStyle::PE_IndicatorArrowRight; - if (expanded) - elementToUse = QStyle::PE_IndicatorArrowDown; - - tree->style()->drawPrimitive(elementToUse, &option, &p, &tempWidgetForContext); -} - -bool PropertyRow::visible(const QPropertyTree* tree) const -{ - if (tree->_isDragged(this)) - return false; - return ((visible_ || !tree->hideUntranslated()) && (matchFilter_ || belongsToFilteredRow_)); -} - -bool PropertyRow::canBeToggled(const QPropertyTree* tree) const -{ - if(!visible(tree)) - return false; - if((tree->treeStyle().compact && (parent() && parent()->isRoot())) || (isContainer() && pulledUp()) || !hasVisibleChildren(tree)) - return false; - return !empty(); -} - -bool PropertyRow::canBeDragged() const -{ - if(parent()){ - if(parent()->isContainer()) - return true; - } - return false; -} - -bool PropertyRow::canBeDroppedOn(const PropertyRow* parentRow, const PropertyRow* beforeChild, const QPropertyTree* tree) const -{ - YASLI_ASSERT(parentRow); - - if(parentRow->pulledContainer()) - parentRow = parentRow->pulledContainer(); - - if(parentRow->isContainer()){ - const PropertyRowContainer* container = static_cast(parentRow); - - if((container->isFixedSize() || container->userReadOnly()) && parent() != parentRow) - return false; - - if(beforeChild && beforeChild->parent() != parentRow) - return false; - - const PropertyRow* defaultRow = container->defaultRow(tree->model()); - if(defaultRow && strcmp(defaultRow->typeName(), typeName()) == 0) - return true; - } - return false; -} - -void PropertyRow::dropInto(PropertyRow* parentRow, PropertyRow* cursorRow, QPropertyTree* tree, bool before) -{ - SharedPtr ref(this); - - PropertyTreeModel* model = tree->model(); - PropertyTreeModel::UpdateLock lock = model->lockUpdate(); - if(parentRow->pulledContainer()) - parentRow = parentRow->pulledContainer(); - if(parentRow->isContainer()){ - tree->model()->rowAboutToBeChanged(tree->model()->root()); // FIXME: select optimal row - setSelected(false); - PropertyRow* oldParent = parent(); - TreePath oldParentPath = tree->model()->pathFromRow(oldParent); - oldParent->erase(this); - if(before) - parentRow->addBefore(this, cursorRow); - else - parentRow->addAfter(this, cursorRow); - model->selectRow(this, true); - TreePath thisPath = tree->model()->pathFromRow(this); - TreePath parentRowPath = tree->model()->pathFromRow(parentRow); - oldParent = tree->model()->rowFromPath(oldParentPath); - if (oldParent) - model->rowChanged(oldParent); // after this call we can get invalid this - if(PropertyRow* newThis = tree->model()->rowFromPath(thisPath)) { - TreeSelection selection; - selection.push_back(thisPath); - model->setSelection(selection); - - // we use path to obtain new row - tree->ensureVisible(newThis); - model->rowChanged(newThis); // after this call row pointers are invalidated - } - parentRow = tree->model()->rowFromPath(parentRowPath); - if (parentRow) - model->rowChanged(parentRow); // after this call row pointers are invalidated - } -} - -void PropertyRow::intersect(const PropertyRow* row) -{ - setMultiValue(multiValue() || row->multiValue() || valueAsString() != row->valueAsString()); - - - int indexSource = 0; - for(int i = 0; i < int(children_.size()); ++i) - { - PropertyRow* testRow = children_[i]; - PropertyRow* matchingRow = row->findFromIndex(&indexSource, testRow->name_, testRow->typeName_, indexSource); - ++indexSource; - if (matchingRow == 0) { - children_.erase(children_.begin() + i); - --i; - } - else { - children_[i]->intersect(matchingRow); - } - } -} - -const char* PropertyRow::rowText(char *containerLabelBuffer, size_t bufsiz, const QPropertyTree* tree, int index) const -{ - if(parent() && parent()->isContainer() && !pulledUp()){ - if (tree->showContainerIndices()) { - if (tree->showContainerIndexLabels()) { - azsnprintf(containerLabelBuffer, bufsiz, " %i. %s", - index + 1 - tree->containerIndicesZeroBased(), - labelUndecorated() ? labelUndecorated() : ""); - } - else { - azsnprintf(containerLabelBuffer, bufsiz, "%i.", - index + 1 - tree->containerIndicesZeroBased()); - } - return containerLabelBuffer; - } - else - return ""; - } - else - return labelUndecorated() ? labelUndecorated() : ""; -} - -bool PropertyRow::hasVisibleChildren(const QPropertyTree* tree, bool internalCall) const -{ - if(empty() || (!internalCall && pulledUp())) - return false; - - PropertyRow::const_iterator it; - for(it = children_.begin(); it != children_.end(); ++it){ - const PropertyRow* child = *it; - if(child->pulledUp()){ - if(child->hasVisibleChildren(tree, true)) - return true; - } - else if(child->visible(tree)) - return true; - } - return false; -} - -const PropertyRow* PropertyRow::hit(const QPropertyTree* tree, QPoint point) const -{ - return const_cast(this)->hit(tree, point); -} - -PropertyRow* PropertyRow::hit(const QPropertyTree* tree, QPoint point) -{ - bool expanded = this->expanded(); - if(isContainer() && pulledUp()) - expanded = parent() ? parent()->expanded() : true; - bool onlyPulled = !expanded; - PropertyRow::const_iterator it; - for(it = children_.begin(); it != children_.end(); ++it){ - PropertyRow* child = *it; - if (!child->visible(tree)) - continue; - if(!onlyPulled || child->pulledUp()) - if(PropertyRow* result = child->hit(tree, point)) - return result; - } - if (QRect(pos_.x(), pos_.y(), size_.x(), size_.y()).contains(point)) - return this; - return 0; -} - -PropertyRow* PropertyRow::findByAddress(const void* addr) -{ - if(searchHandle() == addr) - return this; - else{ - Rows::iterator it; - for(it = children_.begin(); it != children_.end(); ++it){ - PropertyRow* result = it->get()->findByAddress(addr); - if(result) - return result; - } - } - return 0; -} - -const void* PropertyRow::searchHandle() const -{ - return serializer_.pointer(); -} - - -PropertyRow* PropertyRow::findChildFromDescendant(PropertyRow* row) const -{ - PropertyRow* child = row; - Rows::const_iterator it = std::find(children_.begin(), children_.end(), child); - while( it == children_.end() && child ) - { - child = child->parent(); - it = std::find(children_.begin(), children_.end(), child); - } - - return child; -} - -struct GetVerticalIndexOp{ - int index_; - const PropertyRow* row_; - - GetVerticalIndexOp(const PropertyRow* row) : row_(row), index_(0) {} - - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, [[maybe_unused]] int index) - { - if(row == row_) - return SCAN_FINISHED; - if(row->visible(tree) && row->isSelectable() && !row->pulledUp() && !row->packedAfterPreviousRow()) - ++index_; - return row->expanded() ? SCAN_CHILDREN_SIBLINGS : SCAN_SIBLINGS; - } -}; - -int PropertyRow::verticalIndex(QPropertyTree* tree, PropertyRow* row) -{ - GetVerticalIndexOp op(row); - scanChildren(op, tree); - return op.index_; -} - - -struct RowByVerticalIndexOp{ - int index_; - PropertyRow* row_; - - RowByVerticalIndexOp(int index) : row_(0), index_(index) {} - - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, [[maybe_unused]] int index) - { - if(row->visible(tree) && !row->pulledUp() && row->isSelectable() && !row->packedAfterPreviousRow()){ - row_ = row; - if(index_-- <= 0) - return SCAN_FINISHED; - } - return row->expanded() ? SCAN_CHILDREN_SIBLINGS : SCAN_SIBLINGS; - } -}; - -PropertyRow* PropertyRow::rowByVerticalIndex(QPropertyTree* tree, int index) -{ - RowByVerticalIndexOp op(index); - scanChildren(op, tree); - return op.row_; -} - -struct HorizontalIndexOp{ - int index_; - PropertyRow* row_; - bool pulledBefore_; - - HorizontalIndexOp(PropertyRow* row) : row_(row), index_(0), pulledBefore_(row->pulledBefore()) {} - - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, [[maybe_unused]] int index) - { - if(!row->pulledUp()) - return SCAN_SIBLINGS; - if(row->visible(tree) && row->isSelectable() && row->pulledUp() && row->pulledBefore() == pulledBefore_){ - index_ += pulledBefore_ ? -1 : 1; - if(row == row_) - return SCAN_FINISHED; - } - return SCAN_CHILDREN_SIBLINGS; - } -}; - -int PropertyRow::horizontalIndex(QPropertyTree* tree, PropertyRow* row) -{ - if(row == this) - return 0; - HorizontalIndexOp op(row); - if(row->pulledBefore()) - scanChildrenReverse(op, tree); - else - scanChildren(op, tree); - return op.index_; -} - -struct RowByHorizontalIndexOp{ - int index_; - PropertyRow* row_; - bool pulledBefore_; - - RowByHorizontalIndexOp(int index) : row_(0), index_(index), pulledBefore_(index < 0) {} - - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, [[maybe_unused]] int index) - { - if(!row->pulledUp()) - return SCAN_SIBLINGS; - if(row->visible(tree) && row->isSelectable() && row->pulledUp() && row->pulledBefore() == pulledBefore_){ - row_ = row; - if(pulledBefore_ ? ++index_ >= 0 : --index_ <= 0) - return SCAN_FINISHED; - } - return SCAN_CHILDREN_SIBLINGS; - } -}; - -PropertyRow* PropertyRow::rowByHorizontalIndex(QPropertyTree* tree, int index) -{ - if(!index) - return this; - RowByHorizontalIndexOp op(index); - if(index < 0) - scanChildrenReverse(op, tree); - else - scanChildren(op, tree); - return op.row_ ? op.row_ : this; -} - -void PropertyRow::redraw([[maybe_unused]] const PropertyDrawContext& context) -{ - -} - -bool PropertyRow::isFullRow(const QPropertyTree* tree) const -{ - if (tree->treeStyle().fullRowMode) - return true; - if (parent() && parent()->isContainer()) - return true; - return userFullRow(); -} - -QRect PropertyRow::textRect(const QPropertyTree* tree) const -{ - return QRect(textPos_, pos_.y(), textSize_ < textSizeInitial_ ? textSize_ - 1 : textSize_, tree->_defaultRowHeight()); -} - -QRect PropertyRow::widgetRect(const QPropertyTree* tree) const -{ - return QRect(widgetPos_, pos_.y(), widgetSize_, tree->_defaultRowHeight()); -} - -QRect PropertyRow::validatorRect([[maybe_unused]] const QPropertyTree* tree) const -{ - return QRect(pos_.x() + plusSize_, pos_.y() + size_.y() - validatorsHeight_, size_.x() - plusSize_, validatorsHeight_); -} - -QRect PropertyRow::validatorErrorIconRect(const QPropertyTree* tree) const -{ - int rowHeight = tree->_defaultRowHeight(); - int width = validatorHasErrors_ && !expanded_ ? rowHeight : 0; - int normalX = pos_.x() + size_.x() - width; - int minimalX = max(widgetPos_ + widgetSize_, textPos_ + textSize_); - return QRect(max(minimalX, normalX), pos_.y(), width, rowHeight); -} - -QRect PropertyRow::validatorWarningIconRect(const QPropertyTree* tree) const -{ - QRect r = validatorErrorIconRect(tree); - int width = validatorHasWarnings_ && !expanded_ ? r.height() : 0; - return QRect(r.left() - width, pos_.y(), width, r.height()); -} - -QRect PropertyRow::plusRect(const QPropertyTree* tree) const -{ - return QRect(pos_.x(), pos_.y(), plusSize_, tree->_defaultRowHeight()); -} - -QRect PropertyRow::floorRect(const QPropertyTree* tree) const -{ - return QRect(textPos_, pos_.y() + tree->_defaultRowHeight(), size_.x() - (textPos_ - pos_.x()) , size_.y() - tree->_defaultRowHeight()); -} - -void PropertyRow::setCallback(Serialization::ICallback* callback) -{ - callback_ = callback; -} - -SERIALIZATION_CLASS_NAME(PropertyRow, PropertyRow, "PropertyRow", "Structure"); - -// --------------------------------------------------------------------------- - -EDITOR_COMMON_API PropertyRowFactory& GlobalPropertyRowFactory() -{ - return PropertyRowFactory::the(); -} - -EDITOR_COMMON_API Serialization::ClassFactory& GlobalPropertyRowClassFactory() -{ - return Serialization::ClassFactory::the(); -} - -// --------------------------------------------------------------------------- - -PropertyRowWidget::PropertyRowWidget(PropertyRow* row, QPropertyTree* tree) -: row_(row) -, model_(tree->model()) -, tree_(tree) -{ -} - -PropertyRowWidget::~PropertyRowWidget() -{ - if(actualWidget()) - actualWidget()->setParent(0); - tree_->setFocus(); -} - -// --------------------------------------------------------------------------- -Serialization::ClassFactory& GetPropertyRowClassFactory() -{ - return Serialization::ClassFactory::the(); -} -PropertyRowFactory& GetPropertyRowFactory() -{ - return PropertyRowFactory::the(); -} - -int RowWidthCache::getOrUpdate(const QPropertyTree* tree, const PropertyRow* rowForValue, int extraSpace) -{ - string value = rowForValue->valueAsString(); - const QFont* font = rowForValue->rowFont(tree); - unsigned int newHash = calculateHash(value.c_str()); - newHash = calculateHash(font, valueHash); - if (newHash != valueHash) - { - QFontMetrics fm(*font); - width = fm.horizontalAdvance(value.c_str()) + 6 + extraSpace; - if (width < 24) - width = 24; - valueHash = newHash; - } - return width; -} - -// --------------------------------------------------------------------------- - -FORCE_SEGMENT(PropertyRowNumber) -FORCE_SEGMENT(PropertyRowStringList) -/* -FORCE_SEGMENT(PropertyRowDecorators) -FORCE_SEGMENT(PropertyRowBitVector) -FORCE_SEGMENT(PropertyRowFileSelector) -FORCE_SEGMENT(PropertyRowColor) -FORCE_SEGMENT(PropertyRowHotkey) -FORCE_SEGMENT(PropertyRowSlider) -FORCE_SEGMENT(PropertyRowIcon) -*/ -#include - diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRow.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRow.h deleted file mode 100644 index d5556857b7..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRow.h +++ /dev/null @@ -1,575 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include -#include "Serialization/Serializer.h" -#include "Serialization/StringList.h" -#include -#include "Factory.h" -#include "ConstStringList.h" -#include "Strings.h" -#include "../EditorCommonAPI.h" -#include "Serialization/ClassFactory.h" - -#include -#include -#include -#include -#endif - -namespace Serialization { struct ICallback; } - -class QWidget; -class QFont; -class QPainter; -class QMenu; -class QKeyEvent; - -using std::vector; -class QPropertyTree; -class PropertyRow; -class PropertyTreeModel; -class PopupMenuItem; -struct PropertyDrawContext; -struct EDITOR_COMMON_API ContainerMenuHandler; -class PropertyRowContainer; - -enum ScanResult { - SCAN_FINISHED, - SCAN_CHILDREN, - SCAN_SIBLINGS, - SCAN_CHILDREN_SIBLINGS, -}; - -struct EDITOR_COMMON_API PropertyRowMenuHandler : QObject -{ -public: - virtual ~PropertyRowMenuHandler() {} - -}; - -struct PropertyActivationEvent -{ - enum Reason - { - REASON_PRESS, - REASON_RELEASE, - REASON_DOUBLECLICK, - REASON_KEYBOARD, - REASON_NEW_ELEMENT - }; - - QPropertyTree* tree; - Reason reason; - bool force; - QPoint clickPoint; - - PropertyActivationEvent() - : force(false) - , clickPoint(0, 0) - , tree(0) - , reason(REASON_PRESS) - { - } -}; - -struct PropertyDragEvent -{ - QPropertyTree* tree; - QPoint pos; - QPoint start; - QPoint lastDelta; - QPoint totalDelta; -}; - -struct PropertyHoverInfo -{ - QCursor cursor; - QString toolTip; - - PropertyHoverInfo() - : cursor() - { - } -}; - -enum DragCheckBegin { - DRAG_CHECK_IGNORE, - DRAG_CHECK_SET, - DRAG_CHECK_UNSET -}; - -class PropertyRowWidget : public QObject -{ - Q_OBJECT -public: - PropertyRowWidget(PropertyRow* row, QPropertyTree* tree); - virtual ~PropertyRowWidget(); - virtual QWidget* actualWidget() { return 0; } - virtual void showPopup() {} - virtual void commit() = 0; - PropertyRow* row() { return row_; } - PropertyTreeModel* model() { return model_; } -protected: - PropertyRow* row_; - QPropertyTree* tree_; - PropertyTreeModel* model_; -}; - -class PropertyTreeTransaction; - -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -class EDITOR_COMMON_API PropertyRow : public Serialization::RefCounter -{ -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING -public: - enum WidgetPlacement { - WIDGET_NONE, - WIDGET_ICON, - WIDGET_AFTER_NAME, - WIDGET_VALUE, - WIDGET_AFTER_PULLED, - WIDGET_INSTEAD_OF_TEXT - }; - - typedef std::vector< Serialization::SharedPtr > Rows; - typedef Rows::iterator iterator; - typedef Rows::const_iterator const_iterator; - - PropertyRow(); - virtual ~PropertyRow(); - - void setNames(const char* name, const char* label, const char* typeName); - - bool selected() const{ return selected_; } - void setSelected(bool selected) { selected_ = selected; } - bool expanded() const{ return expanded_; } - void _setExpanded(bool expanded); // use QPropertyTree::expandRow - void setExpandedRecursive(QPropertyTree* tree, bool expanded); - - void setMatchFilter(bool matchFilter) { matchFilter_ = matchFilter; } - bool matchFilter() const { return matchFilter_; } - - void setBelongsToFilteredRow(bool belongs) { belongsToFilteredRow_ = belongs; } - bool belongsToFilteredRow() const { return belongsToFilteredRow_; } - - bool visible(const QPropertyTree* tree) const; - bool hasVisibleChildren(const QPropertyTree* tree, bool internalCall = false) const; - - const PropertyRow* hit(const QPropertyTree* tree, QPoint point) const; - PropertyRow* hit(const QPropertyTree* tree, QPoint point); - PropertyRow* parent() { return parent_; } - const PropertyRow* parent() const{ return parent_; } - void setParent(PropertyRow* row) { parent_ = row; } - bool isRoot() const { return !parent_; } - int level() const; - - void add(PropertyRow* row); - void addAfter(PropertyRow* row, PropertyRow* after); - void addBefore(PropertyRow* row, PropertyRow* before); - - template bool scanChildren(Op& op); - template bool scanChildren(Op& op, QPropertyTree* tree); - template bool scanChildrenReverse(Op& op, QPropertyTree* tree); - template bool scanChildrenBottomUp(Op& op, QPropertyTree* tree); - - PropertyRow* childByIndex(int index); - const PropertyRow* childByIndex(int index) const; - int childIndex(const PropertyRow* row) const; - bool isChildOf(const PropertyRow* row) const; - - bool empty() const{ return children_.empty(); } - iterator find(PropertyRow* row) { return std::find(children_.begin(), children_.end(), row); } - PropertyRow* findFromIndex(int* outIndex, const char* name, const char* typeName, int startIndex) const; - PropertyRow* findByAddress(const void* handle); - virtual const void* searchHandle() const; - iterator begin() { return children_.begin(); } - iterator end() { return children_.end(); } - const_iterator begin() const{ return children_.begin(); } - const_iterator end() const{ return children_.end(); } - std::size_t count() const{ return children_.size(); } - iterator erase(iterator it){ return children_.erase(it); } - void clear(){ children_.clear(); } - void erase(PropertyRow* row); - void swapChildren(PropertyRow* row, PropertyTreeModel* model); - - void assignRowState(const PropertyRow& row, bool recurse); - void assignRowProperties(PropertyRow* row); - void replaceAndPreserveState(PropertyRow* oldRow, PropertyRow* newRow, PropertyTreeModel* model); - - const char* name() const{ return name_; } - void setName(const char* name) { name_ = name; } - const char* label() const { return label_; } - const char* labelUndecorated() const { return labelUndecorated_; } - void setLabel(const char* label); - void setLabelChanged(); - void setTooltip(const char* tooltip); - bool setValidatorEntry(int index, int count); - int validatorCount() const{ return validatorCount_; } - int validatorIndex() const{ return validatorIndex_; } - void resetValidatorIcons(); - void addValidatorIcons(bool hasWarnings, bool hasErrors); - const char* tooltip() const { return tooltip_; } - void setLayoutChanged(); - void setLabelChangedToChildren(); - void setLayoutChangedToChildren(); - void setHideChildren(bool hideChildren) { hideChildren_ = hideChildren; } - bool hideChildren() const { return hideChildren_; } - void updateLabel(const QPropertyTree* tree, int index, bool parentHidesNonInlineChildren); - void updateTextSizeInitial(const QPropertyTree* tree, int index, bool force); - virtual void labelChanged() {} - void parseControlCodes(const QPropertyTree* tree, const char* label, bool changeLabel); - const char* typeName() const{ return typeName_; } - virtual const char* typeNameForFilter(QPropertyTree* tree) const; - void setTypeName(const char* typeName) { typeName_ = typeName; } - const char* rowText(char* containerLabelBuffer, size_t bufsiz, const QPropertyTree* tree, int rowIndex) const; - - PropertyRow* findSelected(); - PropertyRow* find(const char* name, const char* nameAlt, const char* typeName); - const PropertyRow* find(const char* name, const char* nameAlt, const char* typeName) const; - void intersect(const PropertyRow* row); - - int verticalIndex(QPropertyTree* tree, PropertyRow* row); - PropertyRow* rowByVerticalIndex(QPropertyTree* tree, int index); - int horizontalIndex(QPropertyTree* tree, PropertyRow* row); - PropertyRow* rowByHorizontalIndex(QPropertyTree* tree, int index); - - virtual bool assignToPrimitive([[maybe_unused]] void* object, [[maybe_unused]] size_t size) const{ return false; } - virtual bool assignTo([[maybe_unused]] const Serialization::SStruct& ser) const{ return false; } - virtual bool assignToByPointer(void* instance, const Serialization::TypeID& type) const{ return assignTo(Serialization::SStruct(type, instance, type.sizeOf(), 0)); } - virtual void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) { serializer_ = ser; } - virtual void handleChildrenChange() {} - virtual string valueAsString() const; - virtual wstring valueAsWString() const; - - int height() const{ return size_.y(); } - - virtual int widgetSizeMin(const QPropertyTree*) const { return userWidgetSize() >= 0 ? userWidgetSize() : 0; } - virtual int floorHeight() const{ return 0; } - - void calcPulledRows(int* minTextSize, int* freePulledChildren, int* minimalWidth, const QPropertyTree* tree, int index); - void calculateMinimalSize(const QPropertyTree* tree, int posX, int availableWidth, bool force, int* extraSizeRemainder, int* _extraSize, int index); - void setTextSize(const QPropertyTree* tree, int rowIndex, float multiplier); - void calculateTotalSizes(int* minTextSize); - void adjustVerticalPosition(const QPropertyTree* tree, int& totalHeight); - - virtual bool isWidgetFixed() const{ return userFixedWidget_ || (widgetPlacement() != WIDGET_VALUE && widgetPlacement() != WIDGET_INSTEAD_OF_TEXT); } - - virtual WidgetPlacement widgetPlacement() const{ return WIDGET_NONE; } - - QRect rect() const{ return QRect(pos_.x(), pos_.y(), size_.x(), size_.y()); } - QRect rectIncludingChildren(const QPropertyTree* tree) const; - QRect textRect(const QPropertyTree* tree) const; - QRect widgetRect(const QPropertyTree* tree) const; - QRect plusRect(const QPropertyTree* tree) const; - QRect floorRect(const QPropertyTree* tree) const; - QRect validatorRect(const QPropertyTree* tree) const; - QRect validatorWarningIconRect(const QPropertyTree* tree) const; - QRect validatorErrorIconRect(const QPropertyTree* tree) const; - void adjustHoveredRect(QRect& hoveredRect); - int heightIncludingChildren() const{ return heightIncludingChildren_; } - const QFont* rowFont(const QPropertyTree* tree) const; - - void drawRow(QPainter& painter, const QPropertyTree* tree, int rowIndex, bool selectionPass); - void drawPlus(QPainter& p, const QPropertyTree* tree, const QRect& rect, bool expanded, bool selected, bool grayed) const; - void drawStaticText(QPainter& p, const QRect& widgetRect); - - virtual void redraw(const PropertyDrawContext& context); - virtual PropertyRowWidget* createWidget([[maybe_unused]] QPropertyTree* tree) { return 0; } - - virtual bool isContainer() const{ return false; } - virtual bool isPointer() const{ return false; } - virtual bool isObject() const{ return false; } - - virtual bool isLeaf() const{ return false; } - virtual void closeNonLeaf([[maybe_unused]] const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) {} - virtual bool isStatic() const{ return pulledContainer_ == 0; } - virtual bool isSelectable() const{ return (!userReadOnly() && !userReadOnlyRecurse()) || (!pulledUp() && !pulledBefore()); } - virtual bool activateOnAdd() const{ return false; } - virtual bool inlineInShortArrays() const{ return false; } - - bool canBeToggled(const QPropertyTree* tree) const; - bool canBeDragged() const; - bool canBeDroppedOn(const PropertyRow* parentRow, const PropertyRow* beforeChild, const QPropertyTree* tree) const; - void dropInto(PropertyRow* parentRow, PropertyRow* cursorRow, QPropertyTree* tree, bool before); - virtual bool getHoverInfo(PropertyHoverInfo* hit, [[maybe_unused]] const QPoint& cursorPos, [[maybe_unused]] const QPropertyTree* tree) const { - hit->toolTip = QString::fromUtf8(tooltip_); - return true; - } - - virtual bool onActivate(const PropertyActivationEvent& e); - virtual bool processesKey(QPropertyTree* tree, const QKeyEvent* ev); // returns true if it wants to process key events; otherwise, they will get processed by shortcuts in some cases, like delete - virtual bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev); - virtual bool onMouseDown([[maybe_unused]] QPropertyTree* tree, [[maybe_unused]] QPoint point, [[maybe_unused]] bool& changed) { return false; } - virtual void onMouseDrag([[maybe_unused]] const PropertyDragEvent& e) {} - virtual void onMouseStill([[maybe_unused]] const PropertyDragEvent& e) {} - virtual void onMouseUp([[maybe_unused]] QPropertyTree* tree, [[maybe_unused]] QPoint point) {} - // "drag check" allows you to "paint" with the mouse through checkboxes to set all values at once - virtual DragCheckBegin onMouseDragCheckBegin() { return DRAG_CHECK_IGNORE; } - virtual bool onMouseDragCheck([[maybe_unused]] QPropertyTree* tree, [[maybe_unused]] bool value) { return false; } - virtual bool onContextMenu(QMenu &menu, QPropertyTree* tree); - virtual ContainerMenuHandler* createMenuHandler(QPropertyTree* tree, PropertyRowContainer* container); - - virtual bool isFullRow(const QPropertyTree* tree) const; - - // User states. - // Assigned using control codes (characters in the beginning of label) - // fixed widget doesn't expand automatically to occupy all available place - bool userFixedWidget() const{ return userFixedWidget_; } - bool userFullRow() const { return userFullRow_; } - void setUserReadOnly(bool userReadOnly) { userReadOnly_ = userReadOnly; } - virtual bool userReadOnly() const { return userReadOnly_; } - void propagateFlagsTopToBottom(); - virtual bool userReadOnlyRecurse() const { return userReadOnlyRecurse_; } - bool userWidgetToContent() const { return userWidgetToContent_; } - int userWidgetSize() const{ return userWidgetSize_; } - bool userNonCopyable() const { return userNonCopyable_; } - - // multiValue is used to edit properties of multiple objects simulateneously - bool multiValue() const { return multiValue_; } - void setMultiValue(bool multiValue) { multiValue_ = multiValue; } - - // pulledRow - is the one that is pulled up to the parents row - // (created with ^ in the beginning of label) - bool pulledUp() const { return pulledUp_; } - bool pulledBefore() const { return pulledBefore_; } - bool hasPulled() const { return hasPulled_; } - bool packedAfterPreviousRow() const { return packedAfterPreviousRow_; } - bool pulledSelected() const; - PropertyRow* nonPulledParent(); - void setPulledContainer(PropertyRow* container){ pulledContainer_ = container; } - PropertyRow* pulledContainer() { return pulledContainer_; } - const PropertyRow* pulledContainer() const{ return pulledContainer_; } - - Serialization::SharedPtr clone(ConstStringList* constStrings) const; - - Serialization::SStruct serializer() const{ return serializer_; } - virtual Serialization::TypeID typeId() const{ return serializer_.type(); } - void setSerializer(const Serialization::SStruct& ser) { serializer_ = ser; } - virtual void serializeValue([[maybe_unused]] Serialization::IArchive& ar) {} - void setCallback(Serialization::ICallback* callback); - Serialization::ICallback* callback() { return callback_; } - virtual void Serialize(Serialization::IArchive& ar); - - static void setConstStrings(ConstStringList* constStrings){ constStrings_ = constStrings; } - -protected: - void init(const char* name, const char* nameAlt, const char* typeName); - PropertyRow* findChildFromDescendant(PropertyRow* row) const; - - virtual void overrideTextColor([[maybe_unused]] QColor& textColor) {} - - const char* name_; - const char* label_; - const char* labelUndecorated_; - const char* typeName_; - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - Serialization::SStruct serializer_; - PropertyRow* parent_; - Serialization::ICallback* callback_; - const char* tooltip_; - Rows children_; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - unsigned int textHash_; - - // do we really need QPoint here? - QPoint pos_; - QPoint size_; - short int textPos_; - short int textSizeInitial_; - short int textSize_; - short int widgetPos_; // widget == icon! - short int widgetSize_; - short int userWidgetSize_; - unsigned short heightIncludingChildren_; - unsigned short validatorIndex_; - unsigned short validatorsHeight_; - unsigned char validatorCount_; - unsigned char plusSize_; - bool visible_ : 1; - bool matchFilter_ : 1; - bool belongsToFilteredRow_ : 1; - bool expanded_ : 1; - bool selected_ : 1; - bool labelChanged_ : 1; - bool layoutChanged_ : 1; - bool userReadOnly_ : 1; - bool userReadOnlyRecurse_ : 1; - bool userFixedWidget_ : 1; - bool userFullRow_ : 1; - bool userPackCheckboxes_ : 1; - bool userWidgetToContent_ : 1; - bool pulledUp_ : 1; - bool pulledBefore_ : 1; - bool packedAfterPreviousRow_ : 1; - bool hasPulled_ : 1; - bool multiValue_ : 1; - bool hideChildren_ : 1; - bool validatorHasErrors_ : 1; - bool validatorHasWarnings_ : 1; - bool userNonCopyable_ : 1; - enum class FontWeight - { - Undefined, - Bold, - Regular - }; - FontWeight fontWeight_; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - Serialization::SharedPtr pulledContainer_; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - static ConstStringList* constStrings_; - friend class PropertyOArchive; - friend class PropertyIArchive; -}; - -inline unsigned int calculateHash(const char* str, unsigned hash = 5381) -{ - while(*str) - hash = hash * 33 + (unsigned char)*str++; - return hash; -} - -template -inline unsigned int calculateHash(const T& t, unsigned hash = 5381) -{ - for (int i = 0; i < sizeof(T); i++) - hash = hash * 33 + ((unsigned char*)&t)[i]; - return hash; -} - -struct RowWidthCache -{ - unsigned int valueHash; - int width; - - RowWidthCache() : valueHash(0), width(-1) {} - int getOrUpdate(const QPropertyTree* tree, const PropertyRow* rowForValue, int extraSpace); -}; - -typedef vector > PropertyRows; - -template -struct StaticBool{ - enum { Value = value }; -}; - -struct LessStrCmp -{ - bool operator()(const char* a, const char* b) const { - return strcmp(a, b) < 0; - } -}; - -typedef Factory PropertyRowFactory; - -template -bool PropertyRow::scanChildren(Op& op) -{ - Rows::iterator it; - - for(it = children_.begin(); it != children_.end(); ++it){ - ScanResult result = op(*it); - if(result == SCAN_FINISHED) - return false; - if(result == SCAN_CHILDREN || result == SCAN_CHILDREN_SIBLINGS){ - if(!(*it)->scanChildren(op)) - return false; - if(result == SCAN_CHILDREN) - return false; - } - } - return true; -} - -template -bool PropertyRow::scanChildren(Op& op, QPropertyTree* tree) -{ - int numChildren = int(children_.size()); - for(int index = 0; index < numChildren; ++index){ - PropertyRow* child = children_[index]; - ScanResult result = op(child, tree, index); - if(result == SCAN_FINISHED) - return false; - if(result == SCAN_CHILDREN || result == SCAN_CHILDREN_SIBLINGS){ - if(!child->scanChildren(op, tree)) - return false; - if(result == SCAN_CHILDREN) - return false; - } - } - return true; -} - -template -bool PropertyRow::scanChildrenReverse(Op& op, QPropertyTree* tree) -{ - int numChildren = (int)children_.size(); - for(int index = numChildren - 1; index >= 0; --index){ - PropertyRow* child = children_[index]; - ScanResult result = op(child, tree, index); - if(result == SCAN_FINISHED) - return false; - if(result == SCAN_CHILDREN || result == SCAN_CHILDREN_SIBLINGS){ - if(!child->scanChildrenReverse(op, tree)) - return false; - if(result == SCAN_CHILDREN) - return false; - } - } - return true; -} - -template -bool PropertyRow::scanChildrenBottomUp(Op& op, QPropertyTree* tree) -{ - size_t numChildren = children_.size(); - for(size_t i = 0; i < numChildren; ++i) - { - PropertyRow* child = children_[i]; - if(!child->scanChildrenBottomUp(op, tree)) - return false; - ScanResult result = op(child, tree); - if(result == SCAN_FINISHED) - return false; - } - return true; -} - -EDITOR_COMMON_API PropertyRowFactory& GlobalPropertyRowFactory(); -EDITOR_COMMON_API Serialization::ClassFactory& GlobalPropertyRowClassFactory(); - -struct PropertyRowPtrSerializer : Serialization::SharedPtrSerializer -{ - PropertyRowPtrSerializer(Serialization::SharedPtr& ptr) : SharedPtrSerializer(ptr) {} - Serialization::ClassFactory* factory() const override { return &GlobalPropertyRowClassFactory(); } -}; - -inline bool Serialize(Serialization::IArchive& ar, Serialization::SharedPtr& ptr, const char* name, const char* label) -{ - PropertyRowPtrSerializer serializer(ptr); - return ar(static_cast(serializer), name, label); -} - -#define REGISTER_PROPERTY_ROW(DataType, RowType) \ - PropertyRow* _Factory_For_##RowType() {return new RowType; }; \ - REGISTER_IN_FACTORY(PropertyRowFactory, Serialization::TypeID::get().name(), RowType, _Factory_For_##RowType); \ - SERIALIZATION_CLASS_NAME_FOR_FACTORY(GlobalPropertyRowClassFactory(), PropertyRow, RowType, #DataType, #DataType); - -// Exposes the necessary class factories to extend the property tree -// Exposes the necessary class factories to extend the property tree -EDITOR_COMMON_API Serialization::ClassFactory& GetPropertyRowClassFactory(); -EDITOR_COMMON_API PropertyRowFactory& GetPropertyRowFactory(); diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowActionButton.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowActionButton.cpp deleted file mode 100644 index d268c87311..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowActionButton.cpp +++ /dev/null @@ -1,168 +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. -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "platform.h" - -#include - -#include "Serialization/ClassFactory.h" -#include "PropertyDrawContext.h" -#include "PropertyRowImpl.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Serialization.h" -#include "Color.h" -#include "Unicode.h" -#include "Serialization/Decorators/ActionButton.h" - -using Serialization::IActionButton; -using Serialization::IActionButtonPtr; - -class PropertyRowActionButton - : public PropertyRow -{ -public: - PropertyRowActionButton() - : underMouse_() - , pressed_() - , minimalWidth_() {} - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - bool isSelectable() const override { return true; } - - bool onActivate(const PropertyActivationEvent& e) override - { - if (e.reason == PropertyActivationEvent::REASON_KEYBOARD) - { - if (value_) - { - value_->Callback(); - } - } - return true; - } - - bool onMouseDown(QPropertyTree* tree, QPoint point, [[maybe_unused]] bool& changed) override - { - if (userReadOnly()) - { - return false; - } - if (widgetRect(tree).contains(point)) - { - underMouse_ = true; - pressed_ = true; - tree->update(); - return true; - } - return false; - } - - void onMouseDrag(const PropertyDragEvent& e) override - { - if (userReadOnly()) - { - return; - } - bool underMouse = widgetRect(e.tree).contains(e.pos); - if (underMouse != underMouse_) - { - underMouse_ = underMouse; - e.tree->update(); - } - } - - void onMouseUp(QPropertyTree* tree, QPoint point) override - { - if (userReadOnly()) - { - return; - } - if (widgetRect(tree).contains(point)) - { - pressed_ = false; - if (value_) - { - value_->Callback(); - } - tree->update(); - } - } - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override - { - value_ = static_cast(ser.pointer())->Clone(); - const char* icon = value_->Icon(); - icon_ = icon && icon[0] ? QIcon() : QIcon(QString::fromLocal8Bit(icon)); - } - bool assignTo([[maybe_unused]] const Serialization::SStruct& ser) const override { return true; } - wstring valueAsWString() const override { return L""; } - WidgetPlacement widgetPlacement() const override { return WIDGET_INSTEAD_OF_TEXT; } - void serializeValue([[maybe_unused]] Serialization::IArchive& ar) override { } - - int widgetSizeMin(const QPropertyTree* tree) const override - { - if (minimalWidth_ == 0) - { - QFontMetrics fm(tree->font()); - minimalWidth_ = (int)fm.horizontalAdvance(QString::fromLocal8Bit(labelUndecorated())) + 6 + (icon_.isNull() ? 0 : 18); - } - return minimalWidth_; - } - - void redraw(const PropertyDrawContext& context) - { - QRect rect = context.widgetRect.adjusted(-1, -1, 1, 1); - bool pressed = pressed_ && underMouse_; - - wstring text = toWideChar(labelUndecorated()); - if (icon_.isNull()) - { - int buttonFlags = BUTTON_CENTER; - if (pressed) - { - buttonFlags |= BUTTON_PRESSED; - } - if (selected()) - { - buttonFlags |= BUTTON_FOCUSED; - } - if (userReadOnly()) - { - buttonFlags |= BUTTON_DISABLED; - } - context.drawButton(rect, text.c_str(), buttonFlags, &context.tree->font()); - } - else - { - context.drawButtonWithIcon(icon_, rect, text.c_str(), selected(), pressed, selected(), !userReadOnly(), true, &context.tree->font()); - } - } - bool isFullRow(const QPropertyTree* tree) const override - { - if (PropertyRow::isFullRow(tree)) - { - return true; - } - return !userFixedWidget(); - } -protected: - mutable int minimalWidth_; - bool underMouse_; - bool pressed_; - QIcon icon_; - IActionButtonPtr value_; -}; - -REGISTER_PROPERTY_ROW(IActionButton, PropertyRowActionButton); diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowBool.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowBool.cpp deleted file mode 100644 index a2704601b0..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowBool.cpp +++ /dev/null @@ -1,116 +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. -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "PropertyRowBool.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "PropertyDrawContext.h" -#include "Serialization/ClassFactory.h" -#include "Serialization.h" -#include - -SERIALIZATION_CLASS_NAME(PropertyRow, PropertyRowBool, "PropertyRowBool", "bool"); - -PropertyRowBool::PropertyRowBool() - : value_(false) -{ -} - -bool PropertyRowBool::assignToPrimitive(void* object, [[maybe_unused]] size_t size) const -{ - YASLI_ASSERT(size == sizeof(bool)); - *reinterpret_cast(object) = value_; - return true; -} - -bool PropertyRowBool::assignToByPointer(void* instance, const Serialization::TypeID& type) const -{ - return assignToPrimitive(instance, type.sizeOf()); -} - -void PropertyRowBool::redraw(const PropertyDrawContext& context) -{ - context.drawCheck(widgetRect(context.tree), userReadOnly(), multiValue() ? CHECK_IN_BETWEEN : (value_ ? CHECK_SET : CHECK_NOT_SET)); -} - -bool PropertyRowBool::processesKey(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (QKeySequence(ev->key()) == QKeySequence(Qt::Key_Space)) - { - return true; - } - - return PropertyRow::processesKey(tree, ev); -} - -bool PropertyRowBool::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (QKeySequence(ev->key()) == QKeySequence(Qt::Key_Space)) - { - PropertyActivationEvent e; - e.tree = tree; - e.reason = e.REASON_KEYBOARD; - onActivate(e); - return true; - } - - return PropertyRow::onKeyDown(tree, ev); -} - -bool PropertyRowBool::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason != e.REASON_RELEASE) - { - if (!this->userReadOnly()) - { - e.tree->model()->rowAboutToBeChanged(this); - value_ = !value_; - e.tree->model()->rowChanged(this); - return true; - } - } - return false; -} - -DragCheckBegin PropertyRowBool::onMouseDragCheckBegin() -{ - if (userReadOnly()) - { - return DRAG_CHECK_IGNORE; - } - return value_ ? DRAG_CHECK_UNSET : DRAG_CHECK_SET; -} - -bool PropertyRowBool::onMouseDragCheck(QPropertyTree* tree, bool value) -{ - if (value_ != value) - { - tree->model()->rowAboutToBeChanged(this); - value_ = value; - tree->model()->rowChanged(this); - return true; - } - return false; -} - -void PropertyRowBool::serializeValue(Serialization::IArchive& ar) -{ - ar(value_, "value", "Value"); -} - -int PropertyRowBool::widgetSizeMin(const QPropertyTree* tree) const -{ - return aznumeric_cast(tree->_defaultRowHeight() * 0.9f); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowBool.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowBool.h deleted file mode 100644 index 0900cd09e6..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowBool.h +++ /dev/null @@ -1,50 +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. -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWBOOL_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWBOOL_H -#pragma once - -#include "PropertyRow.h" -#include "Unicode.h" - -class PropertyRowBool - : public PropertyRow -{ -public: - PropertyRowBool(); - bool assignToPrimitive(void* val, size_t size) const override; - bool assignToByPointer(void* instance, const Serialization::TypeID& type) const; - void setValue(bool value, const void* handle, [[maybe_unused]] const Serialization::TypeID& typeId) { value_ = value; serializer_.setPointer((void*)handle); serializer_.setType(Serialization::TypeID::get()); } - - void redraw(const PropertyDrawContext& context); - bool isLeaf() const{ return true; } - bool isStatic() const{ return false; } - - bool onActivate(const PropertyActivationEvent& e); - DragCheckBegin onMouseDragCheckBegin() override; - bool onMouseDragCheck(QPropertyTree* tree, bool value) override; - wstring valueAsWString() const{ return value_ ? L"true" : L"false"; } - string valueAsString() const{ return value_ ? "true" : "false"; } - WidgetPlacement widgetPlacement() const{ return WIDGET_ICON; } - void serializeValue(Serialization::IArchive& ar); - int widgetSizeMin(const QPropertyTree* tree) const override; - bool processesKey(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; -protected: - bool value_; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWBOOL_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColor.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColor.cpp deleted file mode 100644 index f83dd6713e..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColor.cpp +++ /dev/null @@ -1,241 +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. -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "PropertyRowColor.h" -#include "Serialization/ClassFactory.h" -#include -#include -#include -#include - -#include -#include - -using Serialization::Vec3AsColor; -typedef SerializableColor_tpl SerializableColorB; -typedef SerializableColor_tpl SerializableColorF; - -QColor ToQColor(const ColorB& v) -{ - return QColor(v.r, v.g, v.b, v.a); -} - -void FromQColor(SerializableColorB& vColor, QColor color) -{ - vColor.r = color.red(); - vColor.g = color.green(); - vColor.b = color.blue(); - vColor.a = color.alpha(); -} - - -QColor ToQColor(const Vec3AsColor& v) -{ - return QColor(int(v.v.x * 255.0f), int(v.v.y * 255.0f), int(v.v.z * 255.0f)); -} - -void FromQColor(Vec3AsColor& vColor, QColor color) -{ - vColor.v.x = color.red() / 255.0f; - vColor.v.y = color.green() / 255.0f; - vColor.v.z = color.blue() / 255.0f; -} - -QColor ToQColor(const SerializableColorF& v) -{ - return QColor::fromRgbF(v.r, v.g, v.b, v.a); -} - -void FromQColor(SerializableColorF& vColor, QColor color) -{ - vColor.r = aznumeric_cast(color.redF()); - vColor.g = aznumeric_cast(color.greenF()); - vColor.b = aznumeric_cast(color.blueF()); - vColor.a = aznumeric_cast(color.alphaF()); -} - - -template -bool PropertyRowColor::pickColor(QPropertyTree* tree) -{ - const AZ::Color initialColor = AzQtComponents::fromQColor(color_); - const AZ::Color color = AzQtComponents::ColorPicker::getColor(AzQtComponents::ColorPicker::Configuration::RGB, initialColor, QObject::tr("Select Color")); - - if (color != initialColor) - { - tree->model()->rowAboutToBeChanged(this); - color_.setRed(color.GetR8()); - color_.setGreen(color.GetG8()); - color_.setBlue(color.GetB8()); - colorChanged_ = true; - tree->model()->rowChanged(this); - return true; - } - - return false; -} - -template -bool PropertyRowColor::onActivate(const PropertyActivationEvent& e) -{ - return pickColor(e.tree); -} - -template -void PropertyRowColor::setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] IArchive& ar) -{ - color_ = ToQColor(*(ColorClass*)ser.pointer()); - colorChanged_ = false; -} - -template -bool PropertyRowColor::assignTo(const Serialization::SStruct& ser) const -{ - FromQColor(*((ColorClass*)ser.pointer()), color_); - return true; -} - -template -string PropertyRowColor::valueAsString() const -{ - char buf[64]; - sprintf_s(buf, "%d %d %d", (int)color_.red(), (int)color_.green(), (int)color_.blue()); - return string(buf); -} - -template -bool PropertyRowColor::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - Serialization::SharedPtr selfPointer(this); - ColorMenuHandler* handler = new ColorMenuHandler(tree, this); - menu.addAction("Pick Color", handler, SLOT(onMenuPickColor())); - tree->addMenuHandler(handler); - return true; -} - -template -void PropertyRowColor::redraw(const PropertyDrawContext& context) -{ - static QImage checkboardPattern; - if (checkboardPattern.isNull()) - { - int size = 12; - static vector pixels(size * size); - for (int i = 0; i < pixels.size(); ++i) - { - pixels[i] = ((i / size) / (size / 2) + (i % size) / (size / 2)) % 2 ? 0xffffffff : 0x000000ff; - } - checkboardPattern = QImage((unsigned char*)pixels.data(), size, size, size * 4, QImage::Format_RGBA8888); - } - - QRect r = context.widgetRect.adjusted(0, 0, 0, -1); - - context.painter->save(); - context.painter->setPen(QPen(Qt::NoPen)); - context.painter->setRenderHint(QPainter::Antialiasing, true); - context.painter->setBrush(context.tree->palette().color(QPalette::Dark)); - context.painter->setPen(Qt::NoPen); - context.painter->drawRoundedRect(r, 2, 2); - r = r.adjusted(1, 1, -1, -1); - QRect cr = r.adjusted(0, 0, -r.width() / 2, 0); - context.painter->setBrushOrigin(cr.topRight() + QPoint(1, 0)); - context.painter->setBrush(QBrush(checkboardPattern)); - - context.painter->setRenderHint(QPainter::Antialiasing, false); - context.painter->drawRoundedRect(r, 2, 2); - - context.painter->setPen(QPen(Qt::NoPen)); - context.painter->setClipRect(cr); - context.painter->setBrush(QBrush(color_)); - context.painter->drawRoundedRect(r, 2, 2); - - cr = r.adjusted(r.width() / 2, 0, 0, 0); - context.painter->setClipRect(cr); - context.painter->setBrush(QBrush(QColor(color_.red(), color_.green(), color_.blue(), 255))); - context.painter->drawRoundedRect(r, 2, 2); - context.painter->restore(); -} - -template -void PropertyRowColor::closeNonLeaf(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) -{ - color_ = ToQColor(*(ColorClass*)ser.pointer()); -} - -static int componentFromRowValue(const char* str, ColorB*) -{ - return clamp_tpl(atoi(str), 0, 255); -} - -static int componentFromRowValue(const char* str, ColorF*) -{ - return clamp_tpl(int(atof(str) * 255.0f + 0.5f), 0, 255); -} - -static int componentFromRowValue(const char* str, Vec3AsColor*) -{ - return clamp_tpl(int(atof(str) * 255.0f + 0.5f), 0, 255); -} - -template -void PropertyRowColor::handleChildrenChange() -{ - // generally is not needed unless we are using callbacks - PropertyRow* rows[4] = { - childByIndex(0), - childByIndex(1), - childByIndex(2), - childByIndex(3) - }; - - if (rows[0]) - { - color_.setRed(componentFromRowValue(rows[0]->valueAsString().c_str(), (ColorClass*)0)); - } - if (rows[1]) - { - color_.setGreen(componentFromRowValue(rows[1]->valueAsString().c_str(), (ColorClass*)0)); - } - if (rows[2]) - { - color_.setBlue(componentFromRowValue(rows[2]->valueAsString().c_str(), (ColorClass*)0)); - } - if (rows[3]) - { - color_.setAlpha(componentFromRowValue(rows[3]->valueAsString().c_str(), (ColorClass*)0)); - } -} - - -ColorMenuHandler::ColorMenuHandler(QPropertyTree* tree, IPropertyRowColor* propertyRowColor) - : propertyRowColor(propertyRowColor) - , tree(tree) -{ -} - -void ColorMenuHandler::onMenuPickColor() -{ - propertyRowColor->pickColor(tree); -} - -typedef PropertyRowColor PropertyRowColorB; -typedef PropertyRowColor PropertyRowVec3AsColor; -typedef PropertyRowColor PropertyRowColorF; - -REGISTER_PROPERTY_ROW(SerializableColorB, PropertyRowColorB); -REGISTER_PROPERTY_ROW(Vec3AsColor, PropertyRowVec3AsColor); -REGISTER_PROPERTY_ROW(SerializableColorF, PropertyRowColorF); - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColor.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColor.h deleted file mode 100644 index 9859539b46..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColor.h +++ /dev/null @@ -1,75 +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. -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyDrawContext.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include -#endif - -struct IPropertyRowColor -{ - virtual bool pickColor(QPropertyTree* tree) = 0; -}; - -template -class PropertyRowColor - : public PropertyRow - , public IPropertyRowColor -{ -public: - PropertyRowColor() - : colorChanged_(false) {} - - bool isLeaf() const override { return colorChanged_; } - bool isStatic() const override { return false; } - WidgetPlacement widgetPlacement() const{ return WIDGET_AFTER_PULLED; } - int widgetSizeMin(const QPropertyTree* tree) const { return userWidgetSize() >= 0 ? userWidgetSize() : tree->_defaultRowHeight()* 2 - 4; } - void handleChildrenChange() override; - - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - bool assignTo(const Serialization::SStruct& ser) const override; - void closeNonLeaf(const Serialization::SStruct& ser, Serialization::IArchive& ar); - - bool onActivate(const PropertyActivationEvent& ev) override; - - string valueAsString() const; - void redraw(const PropertyDrawContext& context); - - bool onContextMenu(QMenu& menu, QPropertyTree* tree); - - bool pickColor(QPropertyTree* tree) override; - -private: - QColor color_; - bool colorChanged_; -}; - -struct ColorMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - QPropertyTree * tree; - IPropertyRowColor* propertyRowColor; - - ColorMenuHandler(QPropertyTree* tree, IPropertyRowColor* propertyRowColor); - ~ColorMenuHandler(){}; - -public slots: - void onMenuPickColor(); -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColorPicker.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColorPicker.cpp deleted file mode 100644 index 24650d9b89..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColorPicker.cpp +++ /dev/null @@ -1,158 +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 "EditorCommon_precompiled.h" -#include "PropertyRowColorPicker.h" -#include "Serialization/ClassFactory.h" -#include -#include -#include -#include -#include - -#include -#include - -bool PropertyRowColorPicker::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason == e.REASON_RELEASE) - { - return false; - } - - // ColorF -> QColor. - AZ::Color initialColor; - initialColor.SetR(color_.r); - initialColor.SetG(color_.g); - initialColor.SetB(color_.b); - initialColor.SetA(color_.a); - - const AZ::Color colorFromDialog = AzQtComponents::ColorPicker::getColor(AzQtComponents::ColorPicker::Configuration::RGBA, - initialColor, - QObject::tr("Select Color")); - - if (initialColor == colorFromDialog) - { - // The user cancelled the dialog box. - // Nothing more to do. - return false; - } - - // QColor -> ColorF. - ColorF color(colorFromDialog.GetR(), - colorFromDialog.GetG(), - colorFromDialog.GetB(), - colorFromDialog.GetA()); - - e.tree->model()->rowAboutToBeChanged(this); - color_ = color; - e.tree->model()->rowChanged(this); - - return true; -} -void PropertyRowColorPicker::setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) -{ - ColorPicker* value = (ColorPicker*)ser.pointer(); - color_ = *value->color; -} - -bool PropertyRowColorPicker::assignTo(const Serialization::SStruct& ser) const -{ - ((ColorPicker*)ser.pointer())->SetColor(&color_); - - return true; -} - -void PropertyRowColorPicker::serializeValue(Serialization::IArchive& ar) -{ - ar(color_, "color"); -} - -const QIcon& PropertyRowColorPicker::buttonIcon([[maybe_unused]] const QPropertyTree* tree, [[maybe_unused]] int index) const -{ - // Color-chip. - - QColor color((int)(color_.r * 255.0f), - (int)(color_.g * 255.0f), - (int)(color_.b * 255.0f)); - QPen pen(color); - QBrush brush(color); - - QPixmap pixmap(16, 16); - pixmap.fill(Qt::transparent); - - QPainter painter(&pixmap); - painter.setBrush(brush); - painter.setPen(pen); - painter.drawEllipse(0, 0, 15, 15); - - static QIcon icon; - icon.addPixmap(pixmap); - return icon; -} - -string PropertyRowColorPicker::valueAsString() const -{ - int r = (int)(255.0f * color_.r); - int g = (int)(255.0f * color_.g); - int b = (int)(255.0f * color_.b); - int a = (int)(255.0f * color_.a); - string value; - value.Format("#%02x%02x%02x%02x", r, g, b, a); - return value; -} - -void PropertyRowColorPicker::clear() -{ - color_ = Col_White; -} - -bool PropertyRowColorPicker::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - QAction* action = menu.addAction("Clear"); - QObject::connect(action, - &QAction::triggered, - tree, - [ this, tree ] - { - tree->model()->rowAboutToBeChanged(this); - clear(); - tree->model()->rowChanged(this); - }); - return true; -} - -bool PropertyRowColorPicker::processesKey(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (QKeySequence(ev->key()) == QKeySequence(Qt::Key_Delete)) - { - return true; - } - - return PropertyRowField::processesKey(tree, ev); -} - -bool PropertyRowColorPicker::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - tree->model()->rowAboutToBeChanged(this); - clear(); - tree->model()->rowChanged(this); - return true; - } - return PropertyRowField::onKeyDown(tree, ev); -} - -REGISTER_PROPERTY_ROW(ColorPicker, PropertyRowColorPicker); -DECLARE_SEGMENT(PropertyRowColorPicker) - diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColorPicker.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColorPicker.h deleted file mode 100644 index 90fb049a04..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColorPicker.h +++ /dev/null @@ -1,56 +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_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWCOLORPICKER_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWCOLORPICKER_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyDrawContext.h" -#include "PropertyRowField.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Serialization.h" -#include -#include -#include -#endif - -using Serialization::ColorPicker; - -class PropertyRowColorPicker - : public PropertyRowField -{ -public: - void clear(); - - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - bool assignTo(const Serialization::SStruct& ser) const override; - bool onActivate(const PropertyActivationEvent& e) override; - - int buttonCount() const override { return 1; } - virtual const QIcon& buttonIcon(const QPropertyTree* tree, int index) const override; - string valueAsString() const override; - void serializeValue(Serialization::IArchive& ar); - - bool onContextMenu(QMenu& menu, QPropertyTree* tree); - - bool processesKey(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; - -private: - ColorF color_; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWCOLORPICKER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowContainer.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowContainer.cpp deleted file mode 100644 index c67c7fbd05..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowContainer.cpp +++ /dev/null @@ -1,439 +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 "EditorCommon_precompiled.h" -#include "PropertyRowContainer.h" -#include "PropertyRowPointer.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "PropertyDrawContext.h" -#include "Serialization.h" -#include "PropertyRowPointer.h" - -#include -#include - -// --------------------------------------------------------------------------- - -ContainerMenuHandler::ContainerMenuHandler(QPropertyTree* tree, PropertyRowContainer* container) - : element() - , container(container) - , tree(tree) - , pointerIndex(-1) -{ -} - - - -// --------------------------------------------------------------------------- -SERIALIZATION_CLASS_NAME(PropertyRow, PropertyRowContainer, "PropertyRowContainer", "Container"); - -PropertyRowContainer::PropertyRowContainer() - : fixedSize_(false) - , elementTypeName_("") - , inlined_(false) -{ - buttonLabel_[0] = '\0'; -} - -struct ClassMenuItemAdderRowContainer - : ClassMenuItemAdder -{ - ClassMenuItemAdderRowContainer(PropertyRowContainer* row, QPropertyTree* tree, bool insert = false) - : row_(row) - , tree_(tree) - , insert_(insert) {} - - void addAction(QMenu& menu, const char* text, int index) override - { - ContainerMenuHandler* handler = row_->createMenuHandler(tree_, row_); - tree_->addMenuHandler(handler); - handler->pointerIndex = index; - - QAction* action = menu.addAction(text); - QObject::connect(action, SIGNAL(triggered()), handler, SLOT(onMenuAppendPointerByIndex())); - } -protected: - PropertyRowContainer* row_; - QPropertyTree* tree_; - bool insert_; -}; - -void PropertyRowContainer::redraw(const PropertyDrawContext& context) -{ - QRect widgetRect = context.widgetRect; - if (widgetRect.width() == 0 || inlined_) - { - return; - } - QRect rt = widgetRect; - rt.adjust(0, 1, -1, -1); - QColor brushColor = context.tree->palette().button().color(); - QLinearGradient gradient(rt.left(), rt.top(), rt.left(), rt.bottom()); - gradient.setColorAt(0.0f, brushColor); - gradient.setColorAt(0.6f, brushColor); - gradient.setColorAt(1.0f, context.tree->palette().color(QPalette::Shadow)); - QBrush brush(gradient); - - const wchar_t* text = multiValue() ? L"..." : buttonLabel_; - int buttonFlags = BUTTON_CENTER | BUTTON_POPUP_ARROW; - if (userReadOnly()) - { - buttonFlags |= BUTTON_DISABLED; - } - if (context.m_pressed) - { - buttonFlags |= BUTTON_PRESSED; - } - context.drawButton(rt, text, buttonFlags, &context.tree->font()); -} - - -bool PropertyRowContainer::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason == e.REASON_RELEASE) - { - return false; - } - if (userReadOnly()) - { - return false; - } - if (inlined_) - { - return false; - } - QMenu menu; - generateMenu(menu, e.tree, true); - e.tree->_setPressedRow(this); - menu.exec(e.tree->_toScreen(QPoint(widgetPos_, pos_.y() + e.tree->_defaultRowHeight()))); - e.tree->_setPressedRow(0); - return true; -} - -ContainerMenuHandler* PropertyRowContainer::createMenuHandler(QPropertyTree* tree, PropertyRowContainer* container) -{ - return new ContainerMenuHandler(tree, container); -} - -void PropertyRowContainer::generateMenu(QMenu& menu, QPropertyTree* tree, bool addActions) -{ - ContainerMenuHandler* handler = createMenuHandler(tree, this); - tree->addMenuHandler(handler); - - if (fixedSize_) - { - if (!inlined_) - { - menu.addAction("[ Fixed Size Container ]")->setEnabled(false); - } - } - else if (userReadOnly()) - { - menu.addAction("[ Read Only Container ]")->setEnabled(false); - } - else - { - if (addActions) - { - PropertyRow* row = defaultRow(tree->model()); - if (row && row->isPointer()) - { - QMenu* createItem = menu.addMenu("Add"); - menu.addSeparator(); - - PropertyRowPointer* pointerRow = static_cast(row); - ClassMenuItemAdderRowContainer(this, tree).generateMenu(*createItem, tree->model()->typeStringList(pointerRow->baseType())); - } - else - { - menu.addAction("Insert", handler, SLOT(onMenuAddElement())); - menu.addAction("Add", handler, SLOT(onMenuAppendElement()), Qt::Key_Insert); - } - } - - if (!menu.isEmpty()) - { - menu.addSeparator(); - } - - QAction* removeAll = menu.addAction(pulledUp() ? "Remove Children" : "Remove All"); - removeAll->setShortcut(QKeySequence("Shift+Delete")); - removeAll->setEnabled(!userReadOnly()); - QObject::connect(removeAll, SIGNAL(triggered()), handler, SLOT(onMenuRemoveAll())); - } -} - -bool PropertyRowContainer::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - if (!menu.isEmpty()) - { - menu.addSeparator(); - } - - generateMenu(menu, tree, true); - - if (pulledUp()) - { - return !menu.isEmpty(); - } - - return PropertyRow::onContextMenu(menu, tree); -} - - -void ContainerMenuHandler::onMenuRemoveAll() -{ - tree->model()->rowAboutToBeChanged(container); - container->clear(); - tree->model()->rowChanged(container); -} - -PropertyRow* PropertyRowContainer::defaultRow(PropertyTreeModel* model) -{ - PropertyRow* defaultType = model->defaultType(elementTypeName_); - //YASLI_ASSERT(defaultType); - //YASLI_ASSERT(defaultType->numRef() == 1); - return defaultType; -} - -const PropertyRow* PropertyRowContainer::defaultRow(const PropertyTreeModel* model) const -{ - const PropertyRow* defaultType = model->defaultType(elementTypeName_); - return defaultType; -} - -void ContainerMenuHandler::onMenuAddElement() -{ - container->addElement(tree, false); -} - -void ContainerMenuHandler::onMenuAppendElement() -{ - container->addElement(tree, true); -} - -PropertyRow* PropertyRowContainer::addElement(QPropertyTree* tree, bool append) -{ - tree->model()->rowAboutToBeChanged(this); - PropertyRow* defaultType = defaultRow(tree->model()); - YASLI_ESCAPE(defaultType != 0, return 0); - SharedPtr clonedRow = defaultType->clone(tree->model()->constStrings()); - if (count() == 0) - { - tree->expandRow(this); - } - if (append) - { - add(clonedRow); - } - else - { - addBefore(clonedRow, 0); - } - clonedRow->setHideChildren(tree->outlineMode()); - clonedRow->setLabelChanged(); - clonedRow->setLabelChangedToChildren(); - setMultiValue(false); - if (expanded()) - { - tree->model()->selectRow(clonedRow, true); - } - tree->expandRow(clonedRow); - TreePath path = tree->model()->pathFromRow(clonedRow); - tree->model()->rowChanged(clonedRow); - clonedRow = tree->model()->rowFromPath(path); - tree->update(); - clonedRow = tree->model()->rowFromPath(path); - if (clonedRow) - { - PropertyTreeModel::Selection sel; - sel.push_back(path); - tree->model()->setSelection(sel); - if (clonedRow->activateOnAdd()) - { - PropertyActivationEvent e; - e.tree = tree; - e.reason = e.REASON_NEW_ELEMENT; - clonedRow->onActivate(e); - } - } - return clonedRow; -} - - -void ContainerMenuHandler::onMenuAppendPointerByIndex() -{ - PropertyRow* defaultType = container->defaultRow(tree->model()); - PropertyRowPointer* defaultTypePointer = static_cast(defaultType); - SharedPtr clonedRow = defaultType->clone(tree->model()->constStrings()); - if (container->count() == 0) - { - tree->expandRow(container); - } - container->add(clonedRow); - clonedRow->setLabelChanged(); - clonedRow->setLabelChangedToChildren(); - clonedRow->setHideChildren(tree->outlineMode()); - container->setMultiValue(false); - PropertyRowPointer* clonedRowPointer = static_cast(clonedRow.get()); - clonedRowPointer->setDerivedType(defaultTypePointer->derivedTypeName(), defaultTypePointer->factory()); - clonedRowPointer->setBaseType(defaultTypePointer->baseType()); - clonedRowPointer->setFactory(defaultTypePointer->factory()); - if (container->expanded()) - { - tree->model()->selectRow(clonedRow, true); - } - tree->expandRow(clonedRowPointer); - PropertyTreeModel::Selection sel = tree->model()->selection(); - - CreatePointerMenuHandler handler; - handler.tree = tree; - handler.row = clonedRowPointer; - handler.index = pointerIndex; - handler.onMenuCreateByIndex(); - tree->model()->setSelection(sel); - tree->update(); -} - -void ContainerMenuHandler::onMenuChildInsertBefore() -{ - tree->model()->rowAboutToBeChanged(container); - PropertyRow* defaultType = tree->model()->defaultType(container->elementTypeName()); - if (!defaultType) - { - return; - } - SharedPtr clonedRow = defaultType->clone(tree->model()->constStrings()); - clonedRow->setHideChildren(tree->outlineMode()); - element->setSelected(false); - container->addBefore(clonedRow, element); - container->setMultiValue(false); - tree->model()->selectRow(clonedRow, true); - PropertyTreeModel::Selection sel = tree->model()->selection(); - tree->model()->rowChanged(clonedRow); - tree->model()->setSelection(sel); - tree->update(); - clonedRow = tree->selectedRow(); - if (clonedRow->activateOnAdd()) - { - PropertyActivationEvent e; - e.tree = tree; - e.reason = PropertyActivationEvent::REASON_NEW_ELEMENT; - clonedRow->onActivate(e); - } -} - -void ContainerMenuHandler::onMenuChildRemove() -{ - tree->model()->rowAboutToBeChanged(container); - container->erase(element); - container->setMultiValue(false); - tree->model()->rowChanged(container); -} - - -void PropertyRowContainer::labelChanged() -{ - swprintf(buttonLabel_, sizeof(buttonLabel_) / sizeof(buttonLabel_[0]), L"%zi", count()); -} - -void PropertyRowContainer::serializeValue(IArchive& ar) -{ - ar(ConstStringWrapper(constStrings_, elementTypeName_), "elementTypeName", "ElementTypeName"); - ar(fixedSize_, "fixedSize", "fixedSize"); -} - -string PropertyRowContainer::valueAsString() const -{ - char buf[32] = { 0 }; - sprintf_s(buf, "%d", (int)children_.size()); - return string(buf); -} - -const char* PropertyRowContainer::typeNameForFilter(QPropertyTree* tree) const -{ - const PropertyRow* defaultType = defaultRow(tree->model()); - if (defaultType) - { - return defaultType->typeNameForFilter(tree); - } - else - { - return elementTypeName_; - } -} - -bool PropertyRowContainer::processesKeyContainer([[maybe_unused]] QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete && ev->modifiers() == Qt::SHIFT) - { - return true; - } - - if (ev->key() == Qt::Key_Insert && ev->modifiers() == Qt::NoModifier) - { - return true; - } - - return false; -} - -bool PropertyRowContainer::processesKey(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (processesKeyContainer(tree, ev)) - { - return true; - } - - return PropertyRow::processesKey(tree, ev); -} - -bool PropertyRowContainer::onKeyDownContainer(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (userReadOnly()) - { - return false; - } - - std::unique_ptr handler(createMenuHandler(tree, this)); - if (ev->key() == Qt::Key_Delete && ev->modifiers() == Qt::SHIFT) - { - handler->onMenuRemoveAll(); - return true; - } - - if (ev->key() == Qt::Key_Insert && ev->modifiers() == Qt::NoModifier) - { - handler->onMenuAppendElement(); - return true; - } - - return false; -} - -bool PropertyRowContainer::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (onKeyDownContainer(tree, ev)) - { - return true; - } - return PropertyRow::onKeyDown(tree, ev); -} - -int PropertyRowContainer::widgetSizeMin(const QPropertyTree* tree) const -{ - return inlined_ ? 0 : (userWidgetSize() >= 0 ? userWidgetSize() : aznumeric_cast(tree->_defaultRowHeight() * 1.7f)); -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowContainer.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowContainer.h deleted file mode 100644 index d4e8d2f6d3..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowContainer.h +++ /dev/null @@ -1,96 +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_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWCONTAINER_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWCONTAINER_H -#pragma once -#if !defined(Q_MOC_RUN) -#include "PropertyRow.h" -#endif - - -class EDITOR_COMMON_API PropertyRowContainer; -struct EDITOR_COMMON_API ContainerMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - - QPropertyTree * tree; - PropertyRowContainer* container; - PropertyRow* element; - int pointerIndex; - - ContainerMenuHandler(QPropertyTree* tree, PropertyRowContainer* container); - -public slots: - virtual void onMenuAddElement(); - virtual void onMenuAppendElement(); - virtual void onMenuAppendPointerByIndex(); - virtual void onMenuRemoveAll(); - virtual void onMenuChildInsertBefore(); - virtual void onMenuChildRemove(); -}; - -class EDITOR_COMMON_API PropertyRowContainer - : public PropertyRow -{ -public: - PropertyRowContainer(); - bool isContainer() const{ return true; } - bool onActivate(const PropertyActivationEvent& e); - bool onContextMenu(QMenu& item, QPropertyTree* tree); - virtual ContainerMenuHandler* createMenuHandler(QPropertyTree* tree, PropertyRowContainer* container) override; - void redraw(const PropertyDrawContext& context); - bool processesKeyContainer(QPropertyTree* tree, const QKeyEvent* ev); - bool processesKey(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onKeyDownContainer(QPropertyTree* tree, const QKeyEvent* key); - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* key) override; - - void labelChanged() override; - bool isStatic() const{ return false; } - bool isSelectable() const{ return userWidgetSize() == 0 ? false : true; } - PropertyRow* addElement(QPropertyTree* tree, bool append); - void setInlined(bool inlined) { inlined_ = inlined; } - bool isInlined() const{ return inlined_; } - - PropertyRow* defaultRow(PropertyTreeModel* model); - const PropertyRow* defaultRow(const PropertyTreeModel* model) const; - void serializeValue(Serialization::IArchive& ar); - - const char* elementTypeName() const{ return elementTypeName_; } - using PropertyRow::setValueAndContext; - virtual void setValueAndContext(const Serialization::IContainer& value, [[maybe_unused]] Serialization::IArchive& ar) - { - fixedSize_ = value.isFixedSize(); - elementTypeName_ = value.elementType().name(); - serializer_.setPointer(value.pointer()); - serializer_.setType(value.containerType()); - } - const char* typeNameForFilter(QPropertyTree* tree) const override; - string valueAsString() const; - // C-array is an example of fixed size container - bool isFixedSize() const{ return fixedSize_; } - WidgetPlacement widgetPlacement() const override { return inlined_ ? WIDGET_NONE : WIDGET_AFTER_NAME; } - int widgetSizeMin(const QPropertyTree* tree) const override; - -protected: - virtual void generateMenu(QMenu& menu, QPropertyTree* tree, bool addActions); - - const char* elementTypeName_; - wchar_t buttonLabel_[8]; - bool fixedSize_; - bool inlined_; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWCONTAINER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowField.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowField.cpp deleted file mode 100644 index b91c4fb9b3..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowField.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "PropertyRowField.h" -#include "PropertyDrawContext.h" -#include "QPropertyTree.h" -#include "QPropertyTreeStyle.h" -#include - -enum { BUTTON_SIZE = 16 }; - -QRect PropertyRowField::fieldRect(const QPropertyTree* tree) const -{ - QRect fieldRect = widgetRect(tree); - fieldRect.setRight(fieldRect.right() - buttonCount() * BUTTON_SIZE); - return fieldRect; -} - -bool PropertyRowField::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason == e.REASON_PRESS) { - int buttonCount = this->buttonCount(); - QRect buttonsRect = widgetRect(e.tree); - buttonsRect.setLeft(buttonsRect.right() - buttonCount * BUTTON_SIZE); - - if (buttonsRect.contains(e.clickPoint)) { - int buttonIndex = buttonCount - (e.clickPoint.x() - buttonsRect.x()) / BUTTON_SIZE - 1; - if (buttonIndex >= 0 && buttonIndex < buttonCount) - { - if (onActivateButton(buttonIndex, e)) - return true; - } - } - } - - return PropertyRow::onActivate(e); -} - -void PropertyRowField::redraw(const PropertyDrawContext& context) -{ - int buttonCount = this->buttonCount(); - int offset = 0; - for (int i = 0; i < buttonCount; ++i) { - const QIcon& icon = buttonIcon(context.tree, i); - QRect iconRect(context.widgetRect.right() - offset - BUTTON_SIZE, context.widgetRect.top(), BUTTON_SIZE, context.widgetRect.height()); - icon.paint(context.painter, iconRect, Qt::AlignCenter, userReadOnly() ? QIcon::Disabled : QIcon::Normal); - offset += BUTTON_SIZE; - } - - int iconSpace = offset ? offset + 2 : 0; - if(multiValue()) - context.drawEntry(L" ... ", false, true, iconSpace); - else if(userReadOnly()) - context.drawValueText(pulledSelected(), valueAsWString().c_str()); - else - context.drawEntry(valueAsWString().c_str(), usePathEllipsis(), false, iconSpace); - -} - -const QIcon& PropertyRowField::buttonIcon([[maybe_unused]] const QPropertyTree* tree, [[maybe_unused]] int index) const -{ - static QIcon defaultIcon; - return defaultIcon; -} - -int PropertyRowField::widgetSizeMin(const QPropertyTree* tree) const -{ - if (userWidgetSize() >= 0) - return userWidgetSize(); - - if (userWidgetToContent_) - return widthCache_.getOrUpdate(tree, this, 0); - else - return 40; -} - diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowField.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowField.h deleted file mode 100644 index a512fd330a..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowField.h +++ /dev/null @@ -1,39 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWFIELD_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWFIELD_H -#pragma once - -#include "PropertyRow.h" -class QIcon; - -class PropertyRowField : public PropertyRow -{ -public: - WidgetPlacement widgetPlacement() const override{ return WIDGET_VALUE; } - int widgetSizeMin(const QPropertyTree* tree) const override; - - virtual int buttonCount() const{ return 0; } - virtual const QIcon& buttonIcon(const QPropertyTree* tree, int index) const; - virtual bool usePathEllipsis() const { return false; } - virtual bool onActivateButton([[maybe_unused]] int buttonIndex, [[maybe_unused]] const PropertyActivationEvent& e) { return false; } - - void redraw(const PropertyDrawContext& context) override; - bool onActivate(const PropertyActivationEvent& e) override; -protected: - QRect fieldRect(const QPropertyTree* tree) const; - void drawButtons(int* offset); - - mutable RowWidthCache widthCache_; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWFIELD_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowIconXPM.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowIconXPM.cpp deleted file mode 100644 index 1227ec20d7..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowIconXPM.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/** - * yasli - Serialization Library. - * Copyright (C) 2007-2013 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "Serialization/ClassFactory.h" - -#include "PropertyDrawContext.h" -#include "PropertyRowImpl.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Serialization.h" -#include "Color.h" -#include "Serialization/Decorators/IconXPM.h" -using Serialization::IconXPM; -using Serialization::IconXPMToggle; - -class PropertyRowIconXPM : public PropertyRow{ -public: - void redraw(const PropertyDrawContext& context) - { - QRect rect = context.widgetRect; - context.drawIcon(rect, icon_); - } - - bool isLeaf() const{ return true; } - bool isStatic() const{ return false; } - bool isSelectable() const{ return false; } - - bool onActivate([[maybe_unused]] const PropertyActivationEvent& e) - { - return false; - } - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override { - YASLI_ESCAPE(ser.size() == sizeof(IconXPM), return); - icon_ = *(IconXPM*)(ser.pointer()); - } - wstring valueAsWString() const{ return L""; } - WidgetPlacement widgetPlacement() const{ return WIDGET_ICON; } - void serializeValue([[maybe_unused]] Serialization::IArchive& ar) {} - int widgetSizeMin(const QPropertyTree* tree) const override{ return tree->_defaultRowHeight(); } - int height() const{ return 16; } -protected: - IconXPM icon_; -}; - -class PropertyRowIconToggle : public PropertyRow{ -public: - void redraw(const PropertyDrawContext& context) override - { - IconXPM& icon = value_ ? iconTrue_ : iconFalse_; - context.drawIcon(context.widgetRect, icon); - } - - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override { - YASLI_ESCAPE(ser.size() == sizeof(IconXPMToggle), return); - const IconXPMToggle* icon = (IconXPMToggle*)(ser.pointer()); - iconTrue_ = icon->iconTrue_; - iconFalse_ = icon->iconFalse_; - value_ = icon->value_; - } - - bool assignTo(const Serialization::SStruct& ser) const override - { - IconXPMToggle* toggle = (IconXPMToggle*)ser.pointer(); - toggle->value_ = value_; - return true; - } - - bool isLeaf() const override{ return true; } - bool isStatic() const override{ return false; } - bool isSelectable() const override{ return true; } - bool onActivate(const PropertyActivationEvent& e) - { - if (e.reason != e.REASON_RELEASE) - { - e.tree->model()->rowAboutToBeChanged(this); - value_ = !value_; - e.tree->model()->rowChanged(this); - return true; - } - return false; - } - DragCheckBegin onMouseDragCheckBegin() override - { - if (userReadOnly()) - return DRAG_CHECK_IGNORE; - return value_ ? DRAG_CHECK_UNSET : DRAG_CHECK_SET; - } - bool onMouseDragCheck(QPropertyTree* tree, bool value) override - { - if (value_ != value) { - tree->model()->rowAboutToBeChanged(this); - value_ = value; - tree->model()->rowChanged(this); - return true; - } - return false; - } - wstring valueAsWString() const{ return value_ ? L"true" : L"false"; } - WidgetPlacement widgetPlacement() const{ return WIDGET_ICON; } - - int widgetSizeMin(const QPropertyTree* tree) const{ return tree->_defaultRowHeight(); } - int height() const{ return 16; } - - IconXPM iconTrue_; - IconXPM iconFalse_; - bool value_; -}; - -REGISTER_PROPERTY_ROW(IconXPM, PropertyRowIconXPM); -REGISTER_PROPERTY_ROW(IconXPMToggle, PropertyRowIconToggle); -DECLARE_SEGMENT(PropertyRowIconXPM) diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowImpl.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowImpl.h deleted file mode 100644 index 61cf50c9ad..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowImpl.h +++ /dev/null @@ -1,48 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWIMPL_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWIMPL_H -#pragma once - -#include "Serialization/STL.h" -#include "PropertyRowField.h" -#include "Serialization.h" - -template -class PropertyRowImpl; - -template -class PropertyRowImpl : public PropertyRowField{ -public: - bool assignTo(const Serialization::SStruct& ser) const override { - *reinterpret_cast(ser.pointer()) = value(); - return true; - } - bool isLeaf() const override{ return true; } - bool isStatic() const override{ return false; } - void setValue(const Type& value) { value_ = value; } - Type& value() { return value_; } - const Type& value() const{ return value_; } - - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override { - YASLI_ESCAPE(ser.size() == sizeof(Type), return); - value_ = *(Type*)(ser.pointer()); - } - - void serializeValue(Serialization::IArchive& ar) override{ - ar(value_, "value", "Value"); - } -protected: - Type value_; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWIMPL_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowLocalFrame.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowLocalFrame.cpp deleted file mode 100644 index 6d318aecde..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowLocalFrame.cpp +++ /dev/null @@ -1,152 +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 "EditorCommon_precompiled.h" -#include "PropertyRowLocalFrame.h" -#include -#include -#include -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include -#include -#include "Serialization/ClassFactory.h" -#include "PropertyDrawContext.h" -#include "Serialization.h" -#include - -using Serialization::LocalPosition; - -void LocalFrameMenuHandler::onMenuReset() -{ - self->reset(tree); -} - -PropertyRowLocalFrameBase::PropertyRowLocalFrameBase() - : m_sink(0) - , m_gizmoIndex(-1) - , m_handle(0) - , m_reset(false) -{ -} - -PropertyRowLocalFrameBase::~PropertyRowLocalFrameBase() -{ - m_sink = 0; -} - -bool PropertyRowLocalFrameBase::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason == e.REASON_RELEASE) - { - return false; - } - return false; -} - -string PropertyRowLocalFrameBase::valueAsString() const -{ - return string(); -} - -bool PropertyRowLocalFrameBase::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - Serialization::SharedPtr selfPointer(this); - - LocalFrameMenuHandler* handler = new LocalFrameMenuHandler(tree, this); - - menu.addAction("Reset", handler, SLOT(onMenuReset())); - - tree->addMenuHandler(handler); - return true; -} - -void PropertyRowLocalFrameBase::reset(QPropertyTree* tree) -{ - tree->model()->rowAboutToBeChanged(this); - m_reset = true; - tree->model()->rowChanged(this); -} - -void PropertyRowLocalFrameBase::redraw(const PropertyDrawContext& context) -{ - static QIcon gizmo("Icons/animation/gizmo_location.png"); - gizmo.paint(context.painter, context.widgetRect.adjusted(1, 1, 1, 1), Qt::AlignRight); -} - -static void ResetTransform(Serialization::LocalPosition* l) { *l->value = ZERO; } -static void ResetTransform(Serialization::LocalOrientation* l) { *l->value = IDENTITY; } -static void ResetTransform(Serialization::LocalFrame* l) { *l->position = ZERO; *l->rotation = IDENTITY; } - -template -class PropertyRowLocalFrameImpl - : public PropertyRowLocalFrameBase -{ -public: - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override - { - serializer_ = ser; - - TLocal* value = (TLocal*)ser.pointer(); - m_handle = value->handle; - m_reset = false; - - if (label() && label()[0]) - { - m_sink = ar.FindContext(); - if (m_sink) - { - m_gizmoIndex = m_sink->Write(*value, m_gizmoFlags, m_handle); - } - } - } - - void closeNonLeaf(const Serialization::SStruct& ser, Serialization::IArchive& ar) override - { - if (label() && label()[0] && ar.IsInput()) - { - TLocal& value = *((TLocal*)ser.pointer()); - if (m_sink) - { - if (m_sink->CurrentGizmoIndex() == m_gizmoIndex) - { - m_sink->Read(&value, &m_gizmoFlags, m_handle); - } - else - { - m_sink->SkipRead(); - } - } - } - } - - bool assignTo(const Serialization::SStruct& ser) const - { - if (m_reset) - { - TLocal& value = *((TLocal*)ser.pointer()); - ResetTransform(&value); - } - return false; - } -}; - -typedef PropertyRowLocalFrameImpl PropertyRowLocalPosition; -typedef PropertyRowLocalFrameImpl PropertyRowLocalOrientation; -typedef PropertyRowLocalFrameImpl PropertyRowLocalFrame; - -REGISTER_PROPERTY_ROW(Serialization::LocalPosition, PropertyRowLocalPosition); -REGISTER_PROPERTY_ROW(Serialization::LocalOrientation, PropertyRowLocalOrientation); -REGISTER_PROPERTY_ROW(Serialization::LocalFrame, PropertyRowLocalFrame); - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowLocalFrame.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowLocalFrame.h deleted file mode 100644 index 44b0597542..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowLocalFrame.h +++ /dev/null @@ -1,70 +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_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWLOCALFRAME_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWLOCALFRAME_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "Serialization/Decorators/IGizmoSink.h" -#include "PropertyRowField.h" -#include "QPropertyTree.h" -#endif - -struct IGizmoSink; - -class PropertyRowLocalFrameBase - : public PropertyRow -{ -public: - PropertyRowLocalFrameBase(); - ~PropertyRowLocalFrameBase(); - - bool isLeaf() const override { return m_reset; } - bool isStatic() const override { return false; } - - bool onActivate(const PropertyActivationEvent& e) override; - - WidgetPlacement widgetPlacement() const override { return WIDGET_AFTER_PULLED; } - int widgetSizeMin(const QPropertyTree* tree) const override { return tree->_defaultRowHeight(); } - - string valueAsString() const override; - bool onContextMenu(QMenu& menu, QPropertyTree* tree) override; - const void* searchHandle() const override { return m_handle; } - void redraw(const PropertyDrawContext& context) override; - - void reset(QPropertyTree* tree); -protected: - Serialization::IGizmoSink* m_sink; - const void* m_handle; - int m_gizmoIndex; - mutable Serialization::GizmoFlags m_gizmoFlags; - bool m_reset; -}; - -struct LocalFrameMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - QPropertyTree * tree; - PropertyRowLocalFrameBase* self; - - LocalFrameMenuHandler(QPropertyTree* tree, PropertyRowLocalFrameBase* self) - : tree(tree) - , self(self) {} -public slots: - void onMenuReset(); -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWLOCALFRAME_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumber.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumber.cpp deleted file mode 100644 index 3ba58a83aa..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumber.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Serialization.h" -#include "PropertyRowNumber.h" - -#define REGISTER_NUMBER_ROW(TypeName, postfix) \ - typedef PropertyRowNumber PropertyRow##postfix; \ - typedef Serialization::RangeDecorator RangeDecorator##postfix; \ - PropertyRow* TypeName##postfixFactory() { return new PropertyRow##postfix; }; \ - REGISTER_IN_FACTORY(PropertyRowFactory, Serialization::TypeID::get().name(), PropertyRow##postfix, TypeName##postfixFactory); \ - SERIALIZATION_CLASS_NAME(PropertyRow, PropertyRow##postfix, "PropertyRow" #postfix, #TypeName); - -REGISTER_NUMBER_ROW(float, Float) -REGISTER_NUMBER_ROW(double , Double) - -REGISTER_NUMBER_ROW(char, Char) -REGISTER_NUMBER_ROW(int8, Int8) -REGISTER_NUMBER_ROW(uint8, Uint8) - -REGISTER_NUMBER_ROW(int16, Int16) -REGISTER_NUMBER_ROW(int32, Int32) -REGISTER_NUMBER_ROW(int64, Int64) -REGISTER_NUMBER_ROW(uint16, Uint16) -REGISTER_NUMBER_ROW(uint32, Uint32) -REGISTER_NUMBER_ROW(uint64, Uint64) - -#undef REGISTER_NUMBER_ROW - -DECLARE_SEGMENT(PropertyRowNumber) - -// --------------------------------------------------------------------------- diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumber.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumber.h deleted file mode 100644 index 8658f5d878..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumber.h +++ /dev/null @@ -1,237 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWNUMBER_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWNUMBER_H -#pragma once - - -#include "QPropertyTree.h" -#include "Serialization/MemoryWriter.h" -#include "Serialization/Decorators/Range.h" -#include "PropertyRowNumberField.h" - -#include -#include -#include - -template -string numberAsString(T value) -{ - Serialization::MemoryWriter buf; - buf << value; - return buf.c_str(); -} - -inline long long stringToSignedInteger(const char* str) -{ - long long value; -#ifdef _MSC_VER - value = _atoi64(str); -#else - char* endptr = (char*)str; - value = strtoll(str, &endptr, 10); -#endif - return value; -} - -inline unsigned long long stringToUnsignedInteger(const char* str) -{ - unsigned long long value; - if (*str == '-') { - value = 0; - } - else { -#ifdef _MSC_VER - char* endptr = (char*)str; - value = _strtoui64(str, &endptr, 10); -#else - char* endptr = (char*)str; - value = strtoull(str, &endptr, 10); -#endif - } - return value; -} - -template -Output clamp(Input value, Output min, Output max) -{ - if (value < Input(min)) - return min; - if (value > Input(max)) - return max; - return Output(value); -} - -template void clampToType(Out* out, In value) { *out = clamp(value, std::numeric_limits::lowest(), std::numeric_limits::max()); } - -inline void clampedNumberFromString(char* value, const char* str) { clampToType(value, stringToSignedInteger(str)); } -inline void clampedNumberFromString(signed char* value, const char* str) { clampToType(value, stringToSignedInteger(str)); } -inline void clampedNumberFromString(short* value, const char* str) { clampToType(value, stringToSignedInteger(str)); } -inline void clampedNumberFromString(int* value, const char* str) { clampToType(value, stringToSignedInteger(str)); } -inline void clampedNumberFromString(long* value, const char* str) { clampToType(value, stringToSignedInteger(str)); } -inline void clampedNumberFromString(long long* value, const char* str) { clampToType(value, stringToSignedInteger(str)); } -inline void clampedNumberFromString(unsigned char* value, const char* str) { clampToType(value, stringToUnsignedInteger(str)); } -inline void clampedNumberFromString(unsigned short* value, const char* str) { clampToType(value, stringToUnsignedInteger(str)); } -inline void clampedNumberFromString(unsigned int* value, const char* str) { clampToType(value, stringToUnsignedInteger(str)); } -inline void clampedNumberFromString(unsigned long* value, const char* str) { clampToType(value, stringToUnsignedInteger(str)); } -inline void clampedNumberFromString(unsigned long long* value, const char* str) { clampToType(value, stringToUnsignedInteger(str)); } -inline void clampedNumberFromString(float* value, const char* str) -{ - double v = atof(str); - if (v > FLT_MAX) - v = FLT_MAX; - if (v < -FLT_MAX) - v = -FLT_MAX; - *value = float(v); -} - -inline void clampedNumberFromString(double* value, const char* str) -{ - *value = atof(str); -} - - -template -class PropertyRowNumber : public PropertyRowNumberField{ -public: - PropertyRowNumber() - { - softMin_ = std::numeric_limits::lowest(); - softMax_ = std::numeric_limits::max(); - hardMin_ = std::numeric_limits::lowest(); - hardMax_ = std::numeric_limits::max(); - } - - void setValue(Type value, const void* handle, const Serialization::TypeID& type) - { - value_ = value; - serializer_.setPointer((void*)handle); - serializer_.setType(type); - } - bool setValueFromString(const char* str) override{ - Type value = value_; - clampedNumberFromString(&value_, str); - return value_ != value; - } - string valueAsString() const override - { - return numberAsString(Type(value_)); - } - - bool assignToPrimitive(void* object, [[maybe_unused]] size_t size) const override - { - *reinterpret_cast(object) = value_; - return true; - } - - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override - { - Serialization::RangeDecorator* range = (Serialization::RangeDecorator*)ser.pointer(); - serializer_.setPointer((void*)range->value); - serializer_.setType(Serialization::TypeID::get()); - value_ = *range->value; - softMin_ = range->softMin; - softMax_ = range->softMax; - hardMin_ = range->hardMin; - hardMax_ = range->hardMax; - } - - bool assignTo(const Serialization::SStruct& ser) const override - { - if (ser.type() == Serialization::TypeID::get>()) { - Serialization::RangeDecorator* range = (Serialization::RangeDecorator*)ser.pointer(); - *range->value = value_; - } - else if (ser.type() == Serialization::TypeID::get()) { - *(Type*)ser.pointer() = value_; - } - return true; - } - - void serializeValue(Serialization::IArchive& ar) - { - ar(value_, "value", "Value"); - ar(softMin_, "softMin", "SoftMin"); - ar(softMax_, "softMax", "SoftMax"); - ar(hardMin_, "hardMin", "HardMin"); - ar(hardMax_, "hardMax", "HardMax"); - } - - void startIncrement() override - { - incrementStartValue_ = value_; - } - - void endIncrement(QPropertyTree* tree) override - { - if (value_ != incrementStartValue_) { - Type value = value_; - value_ = incrementStartValue_; - value_ = value; - tree->model()->rowChanged(this, true); - } - } - - void incrementLog(float screenFraction, float valueFieldFraction) - { - bool bothSoftLimitsSet = (std::numeric_limits::lowest() == 0 || softMin_ != std::numeric_limits::lowest()) && softMax_ != std::numeric_limits::max(); - - if (bothSoftLimitsSet) - { - Type softRange = softMax_ - softMin_; - double newValue = incrementStartValue_ + softRange * valueFieldFraction; - value_ = clamp(newValue, hardMin_, hardMax_); - } - else - { - double screenFractionMultiplier = 1000.0; - if (Serialization::TypeID::get() == Serialization::TypeID::get() || - Serialization::TypeID::get() == Serialization::TypeID::get()) - screenFractionMultiplier = 10.0; - - double startPower = log10(fabs(double(incrementStartValue_)) + 1.0) - 3.0; - double power = startPower + fabs(screenFraction) * 10.0f; - double delta = pow(10.0, power) - pow(10.0, startPower) + screenFractionMultiplier * fabs(screenFraction); - double newValue; - if (screenFraction > 0.0f) - newValue = double(incrementStartValue_) + delta; - else - newValue = double(incrementStartValue_) - delta; -#ifdef _MSC_VER - if (_isnan(newValue)) { -#else - if (isnan(newValue)) { -#endif - if (screenFraction > 0.0f) - newValue = DBL_MAX; - else - newValue = -DBL_MAX; - } - value_ = clamp(newValue, hardMin_, hardMax_); - } - } - - double sliderPosition() const override - { - if ((softMin_ == std::numeric_limits::lowest() && softMax_ == std::numeric_limits::max() && softMax_ != Type(255)) || (softMin_ >= softMax_)) - return 0.0; - return clamp(double(value_ - softMin_) / (softMax_ - softMin_), 0.0, 1.0); - } -protected: - Type incrementStartValue_; - Type value_; - Type softMin_; - Type softMax_; - Type hardMin_; - Type hardMax_; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWNUMBER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumberField.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumberField.cpp deleted file mode 100644 index 94b30fb2ab..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumberField.cpp +++ /dev/null @@ -1,287 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "QPropertyTree.h" -#include "QPropertyTreeStyle.h" -#include "PropertyTreeModel.h" -#include "PropertyRowNumberField.h" -#include "PropertyDrawContext.h" -#include "MathUtils.h" -#include -#include -#include -#include -#include - -PropertyRowNumberField::PropertyRowNumberField() - : pressed_(false) - , dragStarted_(false) -{ -} - -PropertyRowWidget* PropertyRowNumberField::createWidget(QPropertyTree* tree) -{ - return new PropertyRowWidgetNumber(tree->model(), this, tree); -} - -QColor interpolateColor(const QColor& a, const QColor& b, float k); - -void PropertyRowNumberField::redraw(const PropertyDrawContext& context) -{ - if (multiValue()) - context.drawEntry(L" ... ", false, true, 0); - else if (userReadOnly()) - context.drawValueText(pulledSelected(), valueAsWString().c_str()); - else - { - QPainter* painter = context.painter; - const QPropertyTree* tree = context.tree; - - QRect rt = context.widgetRect; - rt.adjust(0, 0, 0, -1); - -#if (QT_VERSION < QT_VERSION_CHECK(5, 11, 0)) - QStyleOptionFrameV2 option; - option.features = QStyleOptionFrameV2::None; -#else - QStyleOptionFrame option; - option.features = QStyleOptionFrame::None; -#endif - - option.state = QStyle::State_Sunken; - - // We require a widget to use as context, so that the style sheet can work. - QLineEdit widgetForContext; - option.lineWidth = tree->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &option, &widgetForContext); - - option.midLineWidth = 0; - - if (context.captured) { - option.state |= QStyle::State_HasFocus; - option.state |= QStyle::State_Active; - option.state |= QStyle::State_MouseOver; - } - else if (!userReadOnly()) { - option.state |= QStyle::State_Enabled; - } - option.rect = rt; // option.rect is the rectangle to be drawn on. - option.palette = tree->palette(); - option.fontMetrics = tree->fontMetrics(); - QRect textRect = tree->style()->subElementRect(QStyle::SE_LineEditContents, &option, &widgetForContext); - if (!textRect.isValid()) { - textRect = rt; - textRect.adjust(3, 1, -3, -2); - } - else { - textRect.adjust(2, 1, -2, -1); - } - - - widgetForContext.ensurePolished(); - option.palette = widgetForContext.palette(); - - painter->setPen(QPen(widgetForContext.palette().color(QPalette::WindowText))); - painter->setBrush(QBrush(widgetForContext.palette().color(QPalette::Base))); - tree->style()->drawPrimitive(QStyle::PE_PanelLineEdit, &option, painter, &widgetForContext); - - double sliderPos = sliderPosition(); - if (sliderPos != 0.0) - { - QRect r = textRect.adjusted(-2, -1, 2, 1); - QRect sliderOverlayRect(r.left(), r.top(), int(r.width() * sliderPos), r.height()); - QColor sliderOverlayColor = interpolateColor(tree->palette().color(QPalette::Window), tree->palette().color(QPalette::Highlight), tree->treeStyle().sliderSaturation); - sliderOverlayColor.setAlpha(192); - painter->setBrush(QBrush(sliderOverlayColor)); - painter->setPen(Qt::NoPen); - painter->drawRoundedRect(sliderOverlayRect, 1, 1); - - if (pressed_) { - painter->setPen(QColor(255, 255, 255)); - painter->setBrush(QBrush(QColor(255, 255, 255))); - painter->drawLine(sliderOverlayRect.right(), sliderOverlayRect.top(), sliderOverlayRect.right(), sliderOverlayRect.bottom()); - painter->setRenderHint(QPainter::Antialiasing, true); - painter->translate(0.5f, 0.5f); - int r2 = sliderOverlayRect.right(); - int t = sliderOverlayRect.top(); - int h = sliderOverlayRect.height(); - QPoint points[3] = { - QPoint(r2 - 1 - h / 8 - h / 3, t + h / 2), - QPoint(r2 - 1 - h / 8, t + h * 1 / 4), - QPoint(r2 - 1 - h / 8, t + h * 3 / 4) - }; - QPoint pointsR[3] = { - QPoint(r2 + 1 + h / 8 + h / 3, t + h / 2), - QPoint(r2 + 1 + h / 8, t + h * 1 / 4), - QPoint(r2 + 1 + h / 8, t + h * 3 / 4) - }; - painter->drawPolygon(points, 3); - painter->drawPolygon(pointsR, 3); - painter->setRenderHint(QPainter::Antialiasing, false); - painter->translate(-0.5f, -0.5f); - } - } - - painter->setPen(QPen(widgetForContext.palette().color(QPalette::WindowText))); - painter->setBrush(QBrush(widgetForContext.palette().color(QPalette::Base))); - painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, QString(valueAsString().c_str())); - - - } -} - -QCursor createSliderHoverCursor() -{ - QCursor arrow(Qt::ArrowCursor); - QPoint hotSpot = arrow.hotSpot(); - static QImage image = arrow.pixmap().toImage(); - if (image.isNull()) - return QCursor(Qt::SizeHorCursor); - - int w = image.width(); - int h = image.height(); - QImage empty(w * 2, h, QImage::Format_ARGB32); - empty.fill(Qt::transparent); - QPixmap pixmap = QPixmap::fromImage(empty); - if (pixmap.isNull()) - return QCursor(Qt::SizeHorCursor); - QPainter p(&pixmap); - p.drawImage(image.width() / 2, 0, image); - p.setRenderHint(QPainter::Antialiasing, true); - - QPoint points[3] = { - QPoint(w / 2 - w * 2 / 8, h / 2), - QPoint(w / 2 - w / 8, h * 3 / 8), - QPoint(w / 2 - w / 8, h * 5 / 8) - }; - QPoint pointsR[3] = { - QPoint(w, h * 3 / 8), - QPoint(w, h * 5 / 8), - QPoint(w + w / 8, h / 2), - }; - p.setBrush(QBrush(QColor(255, 255, 255))); - p.setPen(QPen(QColor(0, 0, 0))); - p.drawPolygon(points, 3); - p.drawPolygon(pointsR, 3); - return QCursor(pixmap, image.width() / 2 + hotSpot.x(), hotSpot.y()); -} - - -void PropertyRowNumberField::onMouseDrag(const PropertyDragEvent& e) -{ - if (!dragStarted_) { - e.tree->model()->rowAboutToBeChanged(this); - dragStarted_ = true; - } - QSize screenSize = QApplication::desktop()->screenGeometry(e.tree).size(); - float relativeDelta = float(e.totalDelta.x()) / screenSize.width(); - int fieldRectWidth = widgetRect(e.tree).width(); - if (fieldRectWidth < 16) - fieldRectWidth = aznumeric_cast(e.tree->treeSize().x() * e.tree->valueColumnWidth()); - float valueFieldFraction = fieldRectWidth < FLT_EPSILON ? 0 : float(e.totalDelta.x()) / fieldRectWidth; - incrementLog(relativeDelta, valueFieldFraction); - setMultiValue(false); -} - -bool PropertyRowNumberField::getHoverInfo(PropertyHoverInfo* hit, const QPoint& cursorPos, const QPropertyTree* tree) const -{ - if (pressed_ && !userReadOnly()) - hit->cursor = QCursor(Qt::BlankCursor); - else if (widgetRect(tree).contains(cursorPos) && !userReadOnly()) - hit->cursor = QCursor(createSliderHoverCursor()); - hit->toolTip = tooltip_; - return true; -} - -void PropertyRowNumberField::onMouseStill(const PropertyDragEvent& e) -{ - e.tree->model()->callRowCallback(this); - e.tree->apply(true); -} - -bool PropertyRowNumberField::onMouseDown(QPropertyTree* tree, QPoint point, bool& changed) -{ - changed = false; - if (widgetRect(tree).contains(point) && !userReadOnly()) { - startIncrement(); - pressed_ = true; - return true; - } - return false; -} - -void PropertyRowNumberField::onMouseUp(QPropertyTree* tree, [[maybe_unused]] QPoint point) -{ - tree->unsetCursor(); - pressed_ = false; - dragStarted_ = false; - - // endIncrement() can cause PropertyRow to be destroy, - // so no "this" members should be accessed after the call. - endIncrement(tree); -} - -bool PropertyRowNumberField::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason == e.REASON_RELEASE || e.reason == e.REASON_DOUBLECLICK) - return e.tree->spawnWidget(this, false); - return false; -} - -int PropertyRowNumberField::widgetSizeMin(const QPropertyTree* tree) const -{ - if (userWidgetSize() >= 0) - return userWidgetSize(); - - if (userWidgetToContent()) - return widthCache_.getOrUpdate(tree, this, 0); - else - return 40; -} - -// --------------------------------------------------------------------------- - -PropertyRowWidgetNumber::PropertyRowWidgetNumber([[maybe_unused]] PropertyTreeModel* model, PropertyRowNumberField* row, QPropertyTree* tree) - : PropertyRowWidget(row, tree) - , row_(row) - , entry_(new QLineEdit()) - , tree_(tree) -{ - entry_->setText(row_->valueAsString().c_str()); - connect(entry_, SIGNAL(editingFinished()), this, SLOT(onEditingFinished())); - connect(entry_, &QLineEdit::textChanged, this, [this, tree] { - QFontMetrics fm(entry_->font()); - int contentWidth = min((int)fm.horizontalAdvance(entry_->text()) + 8, tree->width() - entry_->x()); - if (contentWidth > entry_->width()) - entry_->resize(contentWidth, entry_->height()); - }); - - entry_->selectAll(); -} - - -void PropertyRowWidgetNumber::onEditingFinished() -{ - tree_->model()->rowAboutToBeChanged(row()); - string str = entry_->text().toLocal8Bit().data(); - if (row_->setValueFromString(str.c_str()) || row_->multiValue()) - tree_->model()->rowChanged(row()); - else - tree_->_cancelWidget(); -} - -void PropertyRowWidgetNumber::commit() -{ - if (entry_) - onEditingFinished(); -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumberField.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumberField.h deleted file mode 100644 index 888fb204fe..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumberField.h +++ /dev/null @@ -1,75 +0,0 @@ -// Modifications copyright Amazon.com, Inc. or its affiliates. -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWNUMBERFIELD_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWNUMBERFIELD_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyRow.h" -#include -#endif - -class PropertyRowNumberField; -class PropertyRowWidgetNumber : public PropertyRowWidget -{ - Q_OBJECT -public: - PropertyRowWidgetNumber(PropertyTreeModel* mode, PropertyRowNumberField* numberField, QPropertyTree* tree); - ~PropertyRowWidgetNumber(){ - if (entry_) - entry_->setParent(0); - entry_->deleteLater(); - entry_ = 0; - } - - void commit(); - QWidget* actualWidget() { return entry_; } -public slots: - void onEditingFinished(); -protected: - QLineEdit* entry_; - PropertyRowNumberField* row_; - QPropertyTree* tree_; -}; - -// --------------------------------------------------------------------------- - -class PropertyRowNumberField : public PropertyRow -{ -public: - PropertyRowNumberField(); - WidgetPlacement widgetPlacement() const override{ return WIDGET_VALUE; } - int widgetSizeMin(const QPropertyTree* tree) const override; - - PropertyRowWidget* createWidget(QPropertyTree* tree) override; - bool isLeaf() const override{ return true; } - bool isStatic() const override{ return false; } - bool inlineInShortArrays() const override{ return true; } - void redraw(const PropertyDrawContext& context) override; - bool onActivate(const PropertyActivationEvent& e) override; - bool onMouseDown(QPropertyTree* tree, QPoint point, bool& changed) override; - void onMouseUp(QPropertyTree* tree, QPoint point) override; - void onMouseDrag(const PropertyDragEvent& e) override; - void onMouseStill(const PropertyDragEvent& e) override; - bool getHoverInfo(PropertyHoverInfo* hit, const QPoint& cursorPos, const QPropertyTree* tree) const; - - virtual void startIncrement() = 0; - virtual void endIncrement(QPropertyTree* tree) = 0; - virtual void incrementLog(float screenFraction, float valueFieldFraction) = 0; - virtual bool setValueFromString(const char* str) = 0; - virtual double sliderPosition() const = 0; - - mutable RowWidthCache widthCache_; - bool pressed_ : 1; - bool dragStarted_ : 1; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWNUMBERFIELD_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowObject.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowObject.cpp deleted file mode 100644 index 35ffd659f2..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowObject.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 "EditorCommon_precompiled.h" -#include "PropertyRowObject.h" -#include "PropertyTreeModel.h" - -PropertyRowObject::PropertyRowObject() - : model_(0) -{ -} - -bool PropertyRowObject::assignTo(Serialization::Object* obj) -{ - if (object_.type() == obj->type()) - { - *obj = object_; - return true; - } - return false; -} - -PropertyRowObject::~PropertyRowObject() -{ - object_ = Serialization::Object(); -} - -void PropertyRowObject::Serialize(Serialization::IArchive& ar) -{ - PropertyRow::Serialize(ar); -} - diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowObject.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowObject.h deleted file mode 100644 index 8f6f44cc00..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowObject.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWOBJECT_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWOBJECT_H -#pragma once -#include "PropertyRow.h" -#include "Serialization/MemoryWriter.h" -#include "Serialization/Pointers.h" -#include "Serialization/Object.h" - -namespace Serialization { - class IArchive; - struct SStruct; - class MemoryWriter; -}; - -class PropertyRowObject - : public PropertyRow -{ -public: - PropertyRowObject(); - ~PropertyRowObject(); - - using PropertyRow::setValueAndContext; - using PropertyRow::assignTo; - - void setValueAndContext(const Serialization::Object& obj, [[maybe_unused]] Serialization::IArchive& ar) { object_ = obj; } - void setModel(PropertyTreeModel* model) { model_ = model; } - bool isObject() const override { return true; } - bool assignTo(Serialization::Object* obj); - void Serialize(Serialization::IArchive& ar); - const Serialization::Object& object() const{ return object_; } -protected: - - Serialization::Object object_; - PropertyTreeModel* model_; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWOBJECT_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowOutputFilePath.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowOutputFilePath.cpp deleted file mode 100644 index 545ba4a02d..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowOutputFilePath.cpp +++ /dev/null @@ -1,205 +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 "EditorCommon_precompiled.h" -#include "PropertyRowOutputFilePath.h" -#include "Serialization/ClassFactory.h" -#include -#ifndef SERIALIZATION_STANDALONE -#include -#include // for Getting game folder -#endif -#include -#include -#include -#include - -OutputFilePathMenuHandler::OutputFilePathMenuHandler(QPropertyTree* tree, PropertyRowOutputFilePath* self) - : self(self) - , tree(tree) -{ -} - - -void OutputFilePathMenuHandler::onMenuClear() -{ - tree->model()->rowAboutToBeChanged(self); - self->clear(); - tree->model()->rowChanged(self); -} - -QString convertMFCToQtFileFilter(QString* defaultSuffix, const char* mfcFilter) -{ - // convert filter from "All Files|*.*|Text files|*.txt||" - // format into "All files (*.*);;Text Files (*.txt)" - QString filterMFC = QString::fromLocal8Bit(mfcFilter); - QStringList filterItems = filterMFC.split("|"); - - if (defaultSuffix && filterItems.size() > 1) - { - QString extensions = filterItems[1]; - QRegExp re("\\*\\.(\\w*)"); - if (extensions.indexOf(re) >= 0) - { - *defaultSuffix = re.cap(1); - } - } - - QString filter; - for (int i = 0; i < int(filterItems.size()) / 2; ++i) - { - int bracketPos = filterItems[i].indexOf('('); - QString desc = bracketPos >= 0 ? filterItems[i].left(bracketPos) : filterItems[i]; - int extIndex = i * 2 + 1; - if (extIndex >= filterItems.size()) - { - break; - } - if (!filter.isEmpty()) - { - filter += ";;"; - } - filter += desc; - filter += " ("; - filter += filterItems[extIndex]; - filter += ")"; - } - - return filter; -} - -bool PropertyRowOutputFilePath::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason == e.REASON_RELEASE) - { - return false; - } -#ifndef SERIALIZATION_STANDALONE - if (!GetIEditor()) - { - return true; - } -#endif - - QString title; - if (labelUndecorated()) - { - title = QString("Choose file for '") + labelUndecorated() + "'"; - } - else - { - title = "Choose file"; - } - -#ifdef SERIALIZATION_STANDALONE - QString gameFolder; -#else - QString gameFolder = QString::fromLocal8Bit(Path::GetEditingGameDataFolder().c_str()); -#endif - QDir gameFolderDir(QDir::fromNativeSeparators(gameFolder)); - QString defaultSuffix; - QString filter = convertMFCToQtFileFilter(&defaultSuffix, filter_.c_str()); - QString existingFile = QString::fromLocal8Bit(path_.c_str()); - - QString existingFilePath = (existingFile.isEmpty() || QDir::isAbsolutePath(existingFile)) ? existingFile : gameFolderDir.absoluteFilePath(existingFile); - QString startFolder = QString::fromLocal8Bit(startFolder_.c_str()); - - // Not using QFileDialog().exec() as it implements custom file dialog that - // freezes for couple of seconds when being open. Scannign network drives? - QString result = QFileDialog::getSaveFileName(e.tree, title, existingFilePath.isEmpty() ? (gameFolder + "/" + startFolder) : existingFilePath, filter); - if (!result.isEmpty()) - { - e.tree->model()->rowAboutToBeChanged(this); - QString relativeFilename = gameFolderDir.relativeFilePath(result); - path_ = relativeFilename.toLocal8Bit().data(); - e.tree->model()->rowChanged(this); - } - return true; -} -void PropertyRowOutputFilePath::setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) -{ - OutputFilePath* value = (OutputFilePath*)ser.pointer(); - path_ = value->m_path->c_str(); - filter_ = value->filter.c_str(); - startFolder_ = value->startFolder.c_str(); - handle_ = value->m_path; -} - -bool PropertyRowOutputFilePath::assignTo(const Serialization::SStruct& ser) const -{ - ((OutputFilePath*)ser.pointer())->SetPath(path_.c_str()); - return true; -} - -const QIcon& PropertyRowOutputFilePath::buttonIcon(const QPropertyTree* tree, [[maybe_unused]] int index) const -{ - #include "file_save.xpm" - static QIcon fileOpenIcon = QIcon(QPixmap::fromImage(*tree->_iconCache()->getImageForIcon(Serialization::IconXPM(file_save_xpm)))); - return fileOpenIcon; -} - -string PropertyRowOutputFilePath::valueAsString() const -{ - return path_; -} - - -void PropertyRowOutputFilePath::clear() -{ - path_.clear(); -} - -bool PropertyRowOutputFilePath::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - QAction* action = menu.addAction("Clear"); - Serialization::SharedPtr selfPointer(this); - - OutputFilePathMenuHandler* handler = new OutputFilePathMenuHandler(tree, this); - QObject::connect(action, SIGNAL(triggered()), handler, SLOT(onMenuClear())); - tree->addMenuHandler(handler); - return true; -} - -void PropertyRowOutputFilePath::serializeValue(Serialization::IArchive& ar) -{ - ar(path_, "path"); - ar(filter_, "filter"); - ar(startFolder_, "startFolder"); -} - -bool PropertyRowOutputFilePath::processesKey(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - return true; - } - - return PropertyRowField::processesKey(tree, ev); -} - -bool PropertyRowOutputFilePath::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - tree->model()->rowAboutToBeChanged(this); - clear(); - tree->model()->rowChanged(this); - return true; - } - return PropertyRowField::onKeyDown(tree, ev); -} - -REGISTER_PROPERTY_ROW(OutputFilePath, PropertyRowOutputFilePath); -DECLARE_SEGMENT(PropertyRowOutputFilePath) - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowOutputFilePath.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowOutputFilePath.h deleted file mode 100644 index d9f4cb1489..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowOutputFilePath.h +++ /dev/null @@ -1,74 +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_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWOUTPUTFILEPATH_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWOUTPUTFILEPATH_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyDrawContext.h" -#include "PropertyRowField.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Serialization.h" -#include -#include -#endif - -using Serialization::OutputFilePath; - -class PropertyRowOutputFilePath - : public PropertyRowField -{ -public: - void clear(); - - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - - bool onActivate(const PropertyActivationEvent& e) override; - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - bool assignTo(const Serialization::SStruct& ser) const override; - string valueAsString() const; - void serializeValue(Serialization::IArchive& ar); - bool onContextMenu(QMenu& menu, QPropertyTree* tree); - const void* searchHandle() const { return handle_; } - - int buttonCount() const override { return 1; } - virtual const QIcon& buttonIcon(const QPropertyTree* tree, int index) const override; - virtual bool usePathEllipsis() const override { return true; } - - bool processesKey(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; - -private: - string path_; - string filter_; - string startFolder_; - const void* handle_; -}; - -struct OutputFilePathMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - QPropertyTree * tree; - PropertyRowOutputFilePath* self; - - OutputFilePathMenuHandler(QPropertyTree* tree, PropertyRowOutputFilePath* container); -public slots: - void onMenuClear(); -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWOUTPUTFILEPATH_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowPointer.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowPointer.cpp deleted file mode 100644 index d11897b043..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowPointer.cpp +++ /dev/null @@ -1,346 +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 "EditorCommon_precompiled.h" -#include "PropertyRowPointer.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "PropertyDrawContext.h" -#include "Serialization.h" -#include "Unicode.h" -#include - - -// --------------------------------------------------------------------------- - -void ClassMenuItemAdder::generateMenu(QMenu& createItem, const StringList& comboStrings) -{ - StringList::const_iterator it; - int index = 0; - for (it = comboStrings.begin(); it != comboStrings.end(); ++it) - { - StringList path; - splitStringList(&path, it->c_str(), '\\'); - QMenu* item = &createItem; - //createItem.addMenu( - for (int level2 = 0; level2 < int(path.size()); ++level2) - { - const char* leaf = path[level2].c_str(); - if (level2 == path.size() - 1) - { - addAction(*item, leaf, index++); - } - else - { - if (QMenu* menu = item->findChild(leaf)) - { - item = menu; - } - else - { - item = addMenu(*item, leaf); //&item->add(leaf); - } - } - } - } -} - -void ClassMenuItemAdder::addAction(QMenu& menu, const char* text, [[maybe_unused]] int index) -{ - menu.addAction(text)->setEnabled(false); -} - -QMenu* ClassMenuItemAdder::addMenu(QMenu& menu, const char* text) -{ - QMenu* result = menu.addMenu(text); - result->setObjectName(text); - return result; -} - - -// --------------------------------------------------------------------------- - -SERIALIZATION_CLASS_NAME(PropertyRow, PropertyRowPointer, "PropertyRowPointer", "SharedPtr"); - -PropertyRowPointer::PropertyRowPointer() - : factory_(0) - , searchHandle_(0) - , colorOverride_(0, 0, 0, 0) -{ -} - -void PropertyRowPointer::setDerivedType(const char* typeName, Serialization::IClassFactory* factory) -{ - if (!factory) - { - derivedTypeName_.clear(); - return; - } - derivedTypeName_ = typeName; -} - -bool PropertyRowPointer::assignTo(Serialization::IPointer& ptr) -{ - if (derivedTypeName_ != ptr.registeredTypeName()) - { - ptr.create(derivedTypeName_.c_str()); - } - - return true; -} - - -void CreatePointerMenuHandler::onMenuCreateByIndex() -{ - tree->model()->rowAboutToBeChanged(row); - if (index < 0) // NULL value - { - row->setDerivedType("", 0); - row->clear(); - } - else - { - const PropertyDefaultDerivedTypeValue* defaultValue = tree->model()->defaultType(row->baseType(), index); - SharedPtr clonedDefault = defaultValue->root->clone(tree->model()->constStrings()); - if (defaultValue && defaultValue->root) - { - YASLI_ASSERT(defaultValue->root->refCount() == 1); - if (useDefaultValue) - { - row->clear(); - row->swapChildren(clonedDefault, 0); - } - row->setDerivedType(defaultValue->registeredName.c_str(), row->factory()); - row->setLabelChanged(); - row->setLabelChangedToChildren(); - tree->expandRow(row); - } - else - { - row->setDerivedType("", 0); - row->clear(); - } - } - tree->model()->rowChanged(row); -} - - -string PropertyRowPointer::valueAsString() const -{ - string result; - const Serialization::TypeDescription* desc = 0; - if (factory_) - { - desc = factory_->descriptionByRegisteredName(derivedTypeName_.c_str()); - } - if (desc) - { - result = desc->label(); - } - else - { - result = derivedTypeName_; - } - - return result; -} - -wstring PropertyRowPointer::generateLabel() const -{ - if (multiValue()) - { - return L"..."; - } - - wstring str; - if (!derivedTypeName_.empty()) - { - const char* textStart = derivedTypeName_.c_str(); - if (factory_) - { - const Serialization::TypeDescription* desc = factory_->descriptionByRegisteredName(derivedTypeName_.c_str()); - - if (desc) - { - textStart = desc->label(); - } - } - const char* p = textStart + strlen(textStart); - while (p > textStart) - { - if (*(p - 1) == '\\') - { - break; - } - --p; - } - str = toWideChar(p); - if (p != textStart) - { - str += L" ("; - str += toWideChar(string(textStart, p - 1).c_str()); - str += L")"; - } - } - else - { - if (factory_) - { - str = toWideChar(factory_->nullLabel() ? factory_->nullLabel() : "[ null ]"); - } - else - { - str = L"[ null ]"; - } - } - return str; -} - -void PropertyRowPointer::redraw(const PropertyDrawContext& context) -{ - QRect widgetRect = context.widgetRect; - QRect rt = widgetRect; - rt.adjust(-1, 0, 0, 1); - wstring str = generateLabel(); - const QFont* font = derivedTypeName_.empty() ? &context.tree->font() : &context.tree->_boldFont(); - int buttonFlags = BUTTON_POPUP_ARROW; - if (userReadOnly()) - { - buttonFlags |= BUTTON_DISABLED; - } - if (context.m_pressed) - { - buttonFlags |= BUTTON_PRESSED; - } - context.drawButton(rt, str.c_str(), buttonFlags, font, colorOverride_.a != 0 ? &colorOverride_ : 0); -} - -struct ClassMenuItemAdderRowPointer - : ClassMenuItemAdder -{ - ClassMenuItemAdderRowPointer(PropertyRowPointer* row, QPropertyTree* tree) - : row_(row) - , tree_(tree) {} - void addAction(QMenu& menu, const char* text, int index) - { - CreatePointerMenuHandler* handler = new CreatePointerMenuHandler; - tree_->addMenuHandler(handler); - handler->row = row_; - handler->tree = tree_; - handler->index = index; - handler->useDefaultValue = !tree_->immediateUpdate(); - - QAction* action = menu.addAction(text); - - QObject::connect(action, SIGNAL(triggered()), handler, SLOT(onMenuCreateByIndex())); - } -protected: - PropertyRowPointer* row_; - QPropertyTree* tree_; -}; - - -bool PropertyRowPointer::onActivate(QPropertyTree* tree, [[maybe_unused]] bool force) -{ - if (userReadOnly()) - { - return false; - } - QMenu menu; - ClassMenuItemAdderRowPointer(this, tree).generateMenu(menu, tree->model()->typeStringList(baseType())); - tree->_setPressedRow(this); - menu.exec(tree->_toScreen(QPoint(widgetPos_, pos_.y() + tree->_defaultRowHeight()))); - tree->_setPressedRow(0); - return true; -} - -bool PropertyRowPointer::onMouseDown(QPropertyTree* tree, QPoint point, bool& changed) -{ - if (widgetRect(tree).contains(point)) - { - if (onActivate(tree, false)) - { - changed = true; - } - } - return false; -} - -bool PropertyRowPointer::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - if (!menu.isEmpty()) - { - menu.addSeparator(); - } - if (!userReadOnly()) - { - QMenu* createItem = menu.addMenu("Set"); - ClassMenuItemAdderRowPointer(this, tree).generateMenu(*createItem, tree->model()->typeStringList(baseType())); - } - return PropertyRow::onContextMenu(menu, tree); -} - -void PropertyRowPointer::serializeValue(IArchive& ar) -{ - ar(derivedTypeName_, "derivedTypeName", "Derived Type Name"); -} - -int PropertyRowPointer::widgetSizeMin(const QPropertyTree* tree) const -{ - QFontMetrics fm(tree->_boldFont()); - QString str(fromWideChar(generateLabel().c_str()).c_str()); - return fm.horizontalAdvance(str) + 24; -} - -static Color parseColorString(const char* str) -{ - unsigned int color = 0; - if (azsscanf(str, "%x", &color) != 1) - { - return Color(0, 0, 0, 0); - } - Color result((color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff, 255); - return result; -} - -void PropertyRowPointer::setValueAndContext(const Serialization::IPointer& ptr, [[maybe_unused]] Serialization::IArchive& ar) -{ - baseType_ = ptr.baseType(); - factory_ = ptr.factory(); - serializer_ = ptr.serializer(); - pointerType_ = ptr.pointerType(); - searchHandle_ = ptr.handle(); - - const char* colorString = factory_->findAnnotation(ptr.registeredTypeName(), "color"); - if (colorString[0] != '\0') - { - colorOverride_ = parseColorString(colorString); - } - else - { - colorOverride_ = Color(0, 0, 0, 0); - } - - const Serialization::TypeDescription* desc = factory_->descriptionByRegisteredName(ptr.registeredTypeName()); - if (desc) - { - derivedTypeName_ = desc->name(); - } - else - { - derivedTypeName_.clear(); - } -} - -#include -// vim:ts=4 sw=4: diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowPointer.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowPointer.h deleted file mode 100644 index aae8cb875a..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowPointer.h +++ /dev/null @@ -1,95 +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_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWPOINTER_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWPOINTER_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "Color.h" -#include "Serialization/StringList.h" -using Serialization::StringList; - -#include "PropertyRow.h" -#endif - -class QPropertyTree; -class PropertyRowPointer; -struct CreatePointerMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - QPropertyTree * tree; - PropertyRowPointer* row; - int index; - bool useDefaultValue; -public slots: - void onMenuCreateByIndex(); -}; - -class QMenu; -struct ClassMenuItemAdder -{ - virtual void addAction(QMenu& menu, const char* text, int index); - virtual QMenu* addMenu(QMenu& menu, const char* text); - void generateMenu(QMenu& createItem, const StringList& comboStrings); -}; - -class PropertyRowPointer - : public PropertyRow -{ -public: - PropertyRowPointer(); - - bool assignTo(Serialization::IPointer& ptr); - void setValueAndContext(const Serialization::IPointer& ptr, Serialization::IArchive& ar); - using PropertyRow::assignTo; - using PropertyRow::setValueAndContext; - using PropertyRow::onActivate; - - Serialization::TypeID baseType() const{ return baseType_; } - void setBaseType(const Serialization::TypeID& baseType) { baseType_ = baseType; } - const char* derivedTypeName() const{ return derivedTypeName_.c_str(); } - void setDerivedType(const char* typeName, Serialization::IClassFactory* factory); - void setFactory(Serialization::IClassFactory* factory) { factory_ = factory; } - Serialization::IClassFactory* factory() const{ return factory_; } - bool onActivate(QPropertyTree* tree, bool force); - bool onMouseDown(QPropertyTree* tree, QPoint point, bool& changed); - bool onContextMenu(QMenu& root, QPropertyTree* tree); - bool isStatic() const{ return false; } - bool isPointer() const{ return true; } - int widgetSizeMin(const QPropertyTree* tree) const override; - wstring generateLabel() const; - string valueAsString() const; - const char* typeNameForFilter([[maybe_unused]] QPropertyTree* tree) const override { return baseType_.name(); } - void redraw(const PropertyDrawContext& context); - WidgetPlacement widgetPlacement() const{ return WIDGET_VALUE; } - void serializeValue(Serialization::IArchive& ar); - const void* searchHandle() const override { return searchHandle_; } - Serialization::TypeID typeId() const override { return pointerType_; } -protected: - - Serialization::TypeID baseType_; - string derivedTypeName_; - string derivedLabel_; - - // this member is available for instances deserialized from clipboard: - Serialization::IClassFactory* factory_; - const void* searchHandle_; - Serialization::TypeID pointerType_; - Color colorOverride_; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWPOINTER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFilePath.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFilePath.cpp deleted file mode 100644 index f766520662..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFilePath.cpp +++ /dev/null @@ -1,177 +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 "EditorCommon_precompiled.h" - -#include - -#include "PropertyRowResourceFilePath.h" -#include "Serialization/ClassFactory.h" -#include -#include -#include -#include -#include -#include // for getting game folder. - -#include -#include -#include - -ResourceFilePathMenuHandler::ResourceFilePathMenuHandler(QPropertyTree* tree, PropertyRowResourceFilePath* self) - : self(self) - , tree(tree) -{ -} - - -void ResourceFilePathMenuHandler::onMenuClear() -{ - tree->model()->rowAboutToBeChanged(self); - self->clear(); - tree->model()->rowChanged(self); -} - -// Get filename relative to the asset folder, -// whether it came from the project or from a gem -QString AssetRelativePathFromAbsolutePath(const QString& absPath) -{ - return Path::FullPathToGamePath(absPath); -} - -bool PropertyRowResourceFilePath::onActivate(const PropertyActivationEvent& e) -{ - using namespace AzToolsFramework::AssetBrowser; - - if (e.reason == e.REASON_RELEASE) - { - return false; - } - - AssetSelectionModel selection; - if (m_group) - { - selection = AssetSelectionModel::AssetGroupSelection(filter_); - } - else - { - selection = AssetSelectionModel::AssetTypeSelection(filter_); - } - - AzToolsFramework::EditorRequests::Bus::Broadcast(&AzToolsFramework::EditorRequests::BrowseForAssets, selection); - if (!selection.IsValid()) - { - return true; - } - - auto product = azrtti_cast(selection.GetResult()); - if (!product) - { - return true; - } - - AZStd::string relativeFilename = product->GetRelativePath(); - - if (flags_ & ResourceFilePath::STRIP_EXTENSION) - { - size_t ext = relativeFilename.rfind('.'); - if (ext != relativeFilename.npos) - { - relativeFilename.erase(ext, relativeFilename.length() - ext); - } - } - - e.tree->model()->rowAboutToBeChanged(this); - path_ = relativeFilename.c_str(); - e.tree->model()->rowChanged(this); - return true; -} -void PropertyRowResourceFilePath::setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) -{ - ResourceFilePath* value = (ResourceFilePath*)ser.pointer(); - filter_ = value->filter.c_str(); - path_ = value->m_path->c_str(); - flags_ = value->flags; - handle_ = value->m_path; - m_group = value->group; -} - -bool PropertyRowResourceFilePath::assignTo(const Serialization::SStruct& ser) const -{ - ((ResourceFilePath*)ser.pointer())->SetPath(path_.c_str()); - return true; -} - -void PropertyRowResourceFilePath::serializeValue(Serialization::IArchive& ar) -{ - ar(filter_, "filter"); - ar(path_, "path"); - ar(startFolder_, "startFolder"); - ar(m_group, "group"); -} - -const QIcon& PropertyRowResourceFilePath::buttonIcon(const QPropertyTree* tree, [[maybe_unused]] int index) const -{ - #include "file_open.xpm" - static QIcon fileOpenIcon = QIcon(QPixmap::fromImage(*tree->_iconCache()->getImageForIcon(Serialization::IconXPM(file_open_xpm)))); - return fileOpenIcon; -} - -string PropertyRowResourceFilePath::valueAsString() const -{ - return path_; -} - - -void PropertyRowResourceFilePath::clear() -{ - path_.clear(); -} - -bool PropertyRowResourceFilePath::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - QAction* action = menu.addAction("Clear"); - Serialization::SharedPtr selfPointer(this); - - ResourceFilePathMenuHandler* handler = new ResourceFilePathMenuHandler(tree, this); - QObject::connect(action, SIGNAL(triggered()), handler, SLOT(onMenuClear())); - tree->addMenuHandler(handler); - return true; -} - -bool PropertyRowResourceFilePath::processesKey(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - return true; - } - - return PropertyRowField::processesKey(tree, ev); -} - -bool PropertyRowResourceFilePath::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - tree->model()->rowAboutToBeChanged(this); - clear(); - tree->model()->rowChanged(this); - return true; - } - return PropertyRowField::onKeyDown(tree, ev); -} - -REGISTER_PROPERTY_ROW(ResourceFilePath, PropertyRowResourceFilePath); -DECLARE_SEGMENT(PropertyRowResourceFilePath) - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFilePath.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFilePath.h deleted file mode 100644 index 9a564a7bd9..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFilePath.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCEFILEPATH_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCEFILEPATH_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyDrawContext.h" -#include "PropertyRowField.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Serialization.h" -#include -#include -#include -#endif - -using Serialization::ResourceFilePath; - -class PropertyRowResourceFilePath - : public PropertyRowField -{ -public: - void clear(); - - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - bool assignTo(const Serialization::SStruct& ser) const override; - bool onActivate(const PropertyActivationEvent& e) override; - - int buttonCount() const override { return 1; } - virtual const QIcon& buttonIcon(const QPropertyTree* tree, int index) const override; - virtual bool usePathEllipsis() const override { return true; } - string valueAsString() const; - void serializeValue(Serialization::IArchive& ar); - const void* searchHandle() const override { return handle_; } - Serialization::TypeID typeId() const override { return Serialization::TypeID::get(); } - - bool onContextMenu(QMenu& menu, QPropertyTree* tree); - - bool processesKey(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; - -private: - string filter_; - string path_; - string startFolder_; - bool m_group; - int flags_; - const void* handle_; -}; - -struct ResourceFilePathMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - QPropertyTree * tree; - PropertyRowResourceFilePath* self; - - ResourceFilePathMenuHandler(QPropertyTree* tree, PropertyRowResourceFilePath* container); -public slots: - void onMenuClear(); -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCEFILEPATH_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFolderPath.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFolderPath.cpp deleted file mode 100644 index c67f9e4bc3..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFolderPath.cpp +++ /dev/null @@ -1,159 +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 "EditorCommon_precompiled.h" -#include -#include "PropertyRowResourceFolderPath.h" -#include "Serialization/ClassFactory.h" -#include -#include -#include -#include - -ResourceFolderPathMenuHandler::ResourceFolderPathMenuHandler(QPropertyTree* tree, PropertyRowResourceFolderPath* self) - : self(self) - , tree(tree) -{ -} - -void ResourceFolderPathMenuHandler::onMenuClear() -{ - tree->model()->rowAboutToBeChanged(self); - self->clear(); - tree->model()->rowChanged(self); -} - -bool PropertyRowResourceFolderPath::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason == e.REASON_RELEASE) - { - return false; - } - if (!GetIEditor()) - { - return true; - } - - if (userReadOnly()) - { - return false; - } - - QString title; - if (labelUndecorated() && labelUndecorated()[0] != '\0') - { - title = QString("Choose folder for '") + QString::fromLocal8Bit(labelUndecorated()) + "'"; - } - else - { - title = "Choose folder"; - } - - QString gameFolder = QString::fromLocal8Bit(Path::GetEditingGameDataFolder().c_str()); - QString startFolder = gameFolder + QDir::separator(); - - if (path_.empty() || !QDir().exists(startFolder)) - { - startFolder += QString::fromLocal8Bit(startFolder_.c_str()); - } - else - { - startFolder += QString::fromLocal8Bit(path_.c_str()); - } - - QString filename = QFileDialog::getExistingDirectory(e.tree, title, startFolder, QFileDialog::ShowDirsOnly); - if (filename.isEmpty()) - { - return true; - } - - e.tree->model()->rowAboutToBeChanged(this); - QString result = QDir(gameFolder).relativeFilePath(filename); - path_ = result.toLocal8Bit().data(); - e.tree->model()->rowChanged(this); - return true; -} -void PropertyRowResourceFolderPath::setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) -{ - ResourceFolderPath* value = (ResourceFolderPath*)(ser.pointer()); - path_ = value->m_path->c_str(); - startFolder_ = value->startFolder.c_str(); - handle_ = value->m_path; -} - -bool PropertyRowResourceFolderPath::assignTo(const Serialization::SStruct& ser) const -{ - ((ResourceFolderPath*)ser.pointer())->SetPath(path_.c_str()); - return true; -} - -const QIcon& PropertyRowResourceFolderPath::buttonIcon(const QPropertyTree* tree, [[maybe_unused]] int index) const -{ - #include "file_open.xpm" - static QIcon fileOpenIcon = QIcon(QPixmap::fromImage(*tree->_iconCache()->getImageForIcon(Serialization::IconXPM(file_open_xpm)))); - return fileOpenIcon; -} - -string PropertyRowResourceFolderPath::valueAsString() const -{ - return path_; -} - -void PropertyRowResourceFolderPath::clear() -{ - path_.clear(); -} - -void PropertyRowResourceFolderPath::serializeValue(Serialization::IArchive& ar) -{ - ar(path_, "path"); - ar(startFolder_, "startFolder"); -} - -bool PropertyRowResourceFolderPath::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - ResourceFolderPathMenuHandler* handler = new ResourceFolderPathMenuHandler(tree, this); - QAction* action = menu.addAction("Clear", handler, SLOT(onMenuClear())); - action->setEnabled(!userReadOnly()); - SharedPtr selfPointer(this); - - tree->addMenuHandler(handler); - return true; -} - -bool PropertyRowResourceFolderPath::processesKey(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - return true; - } - - return PropertyRowField::processesKey(tree, ev); -} - -bool PropertyRowResourceFolderPath::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - tree->model()->rowAboutToBeChanged(this); - clear(); - tree->model()->rowChanged(this); - return true; - } - return PropertyRowField::onKeyDown(tree, ev); -} - -REGISTER_PROPERTY_ROW(ResourceFolderPath, PropertyRowResourceFolderPath); -DECLARE_SEGMENT(PropertyRowResourceFolderPath) - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFolderPath.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFolderPath.h deleted file mode 100644 index ed58c148e7..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFolderPath.h +++ /dev/null @@ -1,76 +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_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCEFOLDERPATH_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCEFOLDERPATH_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyDrawContext.h" -#include "PropertyRowImpl.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Serialization.h" -#include -#include -#include -#include -#endif - -using Serialization::ResourceFolderPath; - -class PropertyRowResourceFolderPath - : public PropertyRowField -{ -public: - PropertyRowResourceFolderPath() - : handle_() {} - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - bool onActivate(const PropertyActivationEvent& e) override; - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - bool assignTo(const Serialization::SStruct& ser) const override; - string valueAsString() const; - bool onContextMenu(QMenu& menu, QPropertyTree* tree); - - int buttonCount() const override { return 1; } - virtual const QIcon& buttonIcon(const QPropertyTree* tree, int index) const override; - virtual bool usePathEllipsis() const override { return true; } - void serializeValue(Serialization::IArchive& ar) override; - const void* searchHandle() const override { return handle_; } - Serialization::TypeID typeId() const override { return Serialization::TypeID::get(); } - void clear(); - - bool processesKey(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; - -private: - string path_; - string startFolder_; - const void* handle_; -}; - -struct ResourceFolderPathMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - QPropertyTree * tree; - PropertyRowResourceFolderPath* self; - - ResourceFolderPathMenuHandler(QPropertyTree* tree, PropertyRowResourceFolderPath* container); -public slots: - void onMenuClear(); -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCEFOLDERPATH_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceSelector.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceSelector.cpp deleted file mode 100644 index 942691df04..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceSelector.cpp +++ /dev/null @@ -1,425 +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 "EditorCommon_precompiled.h" -#include "PropertyRowResourceSelector.h" -#include "Serialization/ClassFactory.h" -#include "Serialization/Decorators/Resources.h" -#include "Serialization/Decorators/INavigationProvider.h" -#include "Serialization/Decorators/IconXPM.h" -#include -#include "IEditor.h" -#include -#include -#include -#include -#include - -enum Button -{ - BUTTON_PICK, - BUTTON_CREATE -}; - -ResourceSelectorMenuHandler::ResourceSelectorMenuHandler(QPropertyTree* tree, PropertyRowResourceSelector* self) - : self(self) - , tree(tree) -{ -} - - -void ResourceSelectorMenuHandler::onMenuClear() -{ - tree->model()->rowAboutToBeChanged(self); - self->clear(); - tree->model()->rowChanged(self); -} - -void ResourceSelectorMenuHandler::onMenuPickResource() -{ - self->pickResource(tree); -} - -void ResourceSelectorMenuHandler::onMenuCreateFile() -{ - self->createFile(tree); -} - -void ResourceSelectorMenuHandler::onMenuJumpTo() -{ - self->jumpTo(tree); -} - -bool PropertyRowResourceSelector::onActivate(const PropertyActivationEvent& e) -{ - if (PropertyRowField::onActivate(e)) - { - return true; - } - - bool canSelect = !userReadOnly() && !multiValue() && provider_ && provider_->CanSelect(type_.c_str(), value_.c_str(), id_); - - if (!userReadOnly() && e.reason == e.REASON_DOUBLECLICK && provider_ && provider_->CanPickFile(type_.c_str(), id_)) - { - return pickResource(e.tree); - } - - if (canSelect) - { - jumpTo(e.tree); - return true; - } - else if (!userReadOnly()) - { - if (!provider_ && !userReadOnly()) - { - pickResource(e.tree); - } - } - return false; -} - -int PropertyRowResourceSelector::buttonCount() const -{ - if (!provider_) - { - return 1; - } - - int result = 0; - if (provider_->CanPickFile(type_.c_str(), id_)) - { - result = 1; - if (!multiValue() && value_.empty() && provider_->CanCreate(type_.c_str(), id_)) - { - result = 2; - } - } - return result; -} - -bool PropertyRowResourceSelector::onActivateButton(int button, const PropertyActivationEvent& e) -{ - if (userReadOnly()) - { - return false; - } - if (button == BUTTON_PICK) - { - return pickResource(e.tree); - } - else if (button == BUTTON_CREATE) - { - return createFile(e.tree); - } - return true; -} - -bool PropertyRowResourceSelector::getHoverInfo(PropertyHoverInfo* hover, const QPoint& cursorPos, const QPropertyTree* tree) const -{ - if (fieldRect(tree).contains(cursorPos) && provider_ && provider_->CanSelect(type_.c_str(), value_.c_str(), id_) && !provider_->IsSelected(type_.c_str(), value_.c_str(), id_)) - { - hover->cursor = QCursor(Qt::PointingHandCursor); - } - else - { - hover->cursor = QCursor(); - } - hover->toolTip = QString::fromLocal8Bit(value_.c_str()); - return true; -} - -void PropertyRowResourceSelector::jumpTo([[maybe_unused]] QPropertyTree* tree) -{ - if (multiValue()) - { - return; - } - if (provider_) - { - provider_->Select(type_.c_str(), value_.c_str(), id_); - } - return; -} - -bool PropertyRowResourceSelector::pickResource(QPropertyTree* tree) -{ - if (!GetIEditor()) - { - return false; - } - - context_.typeName = type_.c_str(); - context_.parentWidget = tree; - QString filename = GetIEditor()->GetResourceSelectorHost()->SelectResource(context_, value_.c_str()); - - tree->model()->rowAboutToBeChanged(this); - value_ = filename.toUtf8().constData(); - tree->model()->rowChanged(this); - - return true; -} - -QString convertMFCToQtFileFilter(QString* defaultSuffix, const char* mfcFilter); - -bool PropertyRowResourceSelector::createFile(QPropertyTree* tree) -{ - if (!provider_) - { - return false; - } - - QString title; - if (labelUndecorated()) - { - title = QString("Create file for '") + labelUndecorated() + "'"; - } - else - { - title = "Choose file"; - } - - string originalFilter; - originalFilter = provider_->GetFileSelectorMaskForType(type_.c_str()); - - QString gameFolder = QString::fromLocal8Bit(Path::GetEditingGameDataFolder().c_str()); - QDir gameFolderDir(QDir::fromNativeSeparators(gameFolder)); - QString defaultSuffix; - QString filter = convertMFCToQtFileFilter(&defaultSuffix, originalFilter.c_str()); - QString existingFile = QString::fromLocal8Bit(PathUtil::ReplaceExtension(defaultPath_.empty() ? value_.c_str() : defaultPath_.c_str(), defaultSuffix.toLocal8Bit().data())); - - QString existingFilePath = (existingFile.isEmpty() || QDir::isAbsolutePath(existingFile)) ? existingFile : gameFolderDir.absoluteFilePath(existingFile); - - // Not using QFileDialog().exec() as it implements custom file dialog that - // freezes for couple of seconds when being open. Scannign network drives? - QString result = QFileDialog::getSaveFileName(tree, title, existingFilePath.isEmpty() ? (gameFolder + "/") : existingFilePath, filter); - if (!result.isEmpty()) - { - QString relativeFilename = gameFolderDir.relativeFilePath(result); - - if (provider_->Create(type_.c_str(), relativeFilename.toLocal8Bit().data(), id_)) - { - tree->model()->rowAboutToBeChanged(this); - value_ = relativeFilename.toLocal8Bit().data(); - tree->model()->rowChanged(this); - } - } - return true; -} - -void PropertyRowResourceSelector::setValueAndContext(const Serialization::SStruct& ser, IArchive& ar) -{ - IResourceSelector* value = (IResourceSelector*)ser.pointer(); - if (type_ != value->resourceType) - { - type_ = value->resourceType; - const char* resourceIconPath = GetIEditor()->GetResourceSelectorHost()->ResourceIconPath(type_.c_str()); - icon_ = resourceIconPath[0] ? QIcon(QString::fromLocal8Bit(resourceIconPath)) : QIcon(); - } - value_ = value->GetValue(); - id_ = value->GetId(); - searchHandle_ = value->GetHandle(); - wrappedType_ = value->GetType(); - - provider_ = ar.FindContext(); - if (!provider_ || !provider_->IsRegistered(type_)) - { - provider_ = 0; - } - - Serialization::TypeID contextObjectType = GetIEditor()->GetResourceSelectorHost()->ResourceContextType(type_.c_str()); - if (contextObjectType != Serialization::TypeID()) - { - context_.contextObject = ar.FindContextByType(contextObjectType); - context_.contextObjectType = contextObjectType; - } - - if (Serialization::SNavigationContext* navigationContext = ar.FindContext()) - { - defaultPath_ = navigationContext->path.c_str(); - } - else - { - defaultPath_.clear(); - } -} - -bool PropertyRowResourceSelector::assignTo(const Serialization::SStruct& ser) const -{ - ((IResourceSelector*)ser.pointer())->SetValue(value_.c_str()); - return true; -} - -void PropertyRowResourceSelector::serializeValue(Serialization::IArchive& ar) -{ - ar(type_, "type"); - ar(value_, "value"); - ar(id_, "index"); - - if (ar.IsInput()) - { - const char* resourceIconPath = GetIEditor()->GetResourceSelectorHost()->ResourceIconPath(type_.c_str()); - icon_ = resourceIconPath[0] ? QIcon(QString::fromLocal8Bit(resourceIconPath)) : QIcon(); - } -} - -const QIcon& PropertyRowResourceSelector::buttonIcon(const QPropertyTree* tree, int index) const -{ - switch (index) - { - case BUTTON_PICK: - { - if (provider_ != 0 || icon_.isNull()) - { - #include "file_open.xpm" - static QIcon defaultIcon(QPixmap::fromImage(*tree->_iconCache()->getImageForIcon(Serialization::IconXPM(file_open_xpm)))); - return defaultIcon; - } - else - { - return icon_; - } - } - case BUTTON_CREATE: - { - static QIcon addIcon("Icons/animation/add.png"); - ; - return addIcon; - } - default: - { - static QIcon defaultIcon; - return defaultIcon; - } - } -} - -string PropertyRowResourceSelector::valueAsString() const -{ - return value_; -} - -void PropertyRowResourceSelector::clear() -{ - value_.clear(); -} - -bool PropertyRowResourceSelector::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - Serialization::SharedPtr selfPointer(this); - - ResourceSelectorMenuHandler* handler = new ResourceSelectorMenuHandler(tree, this); - if (!multiValue() && provider_ && provider_->CanSelect(type_.c_str(), value_.c_str(), id_)) - { - QAction* jumpToAction = menu.addAction("Jump to", handler, SLOT(onMenuJumpTo())); - menu.setDefaultAction(jumpToAction); - } - if (!userReadOnly()) - { - if (!provider_ || provider_->CanPickFile(type_.c_str(), id_)) - { - menu.addAction(buttonIcon(tree, 0), "Pick Resource...", handler, SLOT(onMenuPickResource()))->setEnabled(!userReadOnly()); - } - if (provider_ && provider_->CanCreate(type_.c_str(), id_)) - { - menu.addAction(buttonIcon(tree, 1), "Create...", handler, SLOT(onMenuCreateFile())); - } - menu.addAction("Clear", handler, SLOT(onMenuClear()))->setEnabled(!userReadOnly()); - } - tree->addMenuHandler(handler); - - PropertyRow::onContextMenu(menu, tree); - return true; -} - -static const wchar_t* getFilenameFromPath(const wchar_t* path) -{ - const wchar_t* lastSep = wcsrchr(path, L'/'); - if (!lastSep) - { - return path; - } - return lastSep + 1; -} - -void PropertyRowResourceSelector::redraw(const PropertyDrawContext& context) -{ - ////! TOFIX: THIS CODE IS DUPLICATED IN PropertyRowField.cpp: PropertyRowField::redraw()!!! - // - int buttonCount = this->buttonCount(); - int offset = 0; - for (int i = 0; i < buttonCount; ++i) - { - const QIcon& icon = buttonIcon(context.tree, i); - int width = 16; - QRect iconRect(context.widgetRect.right() - offset - width, context.widgetRect.top(), width, context.widgetRect.height()); - icon.paint(context.painter, iconRect, Qt::AlignCenter, userReadOnly() ? QIcon::Disabled : QIcon::Normal); - offset += width; - } - - int iconSpace = offset ? offset + 2 : 0; - // - //// - - QRect rect = context.widgetRect; - rect.setRight(rect.right() - iconSpace); - bool pressed = context.m_pressed || (provider_ ? provider_->IsSelected(type_.c_str(), value_.c_str(), id_) : false); - bool active = !provider_ || provider_->IsActive(type_.c_str(), value_.c_str(), id_); - bool modified = provider_ && provider_->IsModified(type_.c_str(), value_.c_str(), id_); - QIcon icon = icon_; - if (provider_) - { - icon = QIcon(provider_->GetIcon(type_.c_str(), value_.c_str())); - } - bool canSelect = !multiValue() && provider_ && provider_->CanSelect(type_.c_str(), value_.c_str(), id_); - - wstring text = multiValue() ? L"..." : wstring(modified ? L"*" : L"") + getFilenameFromPath(valueAsWString()); - if (provider_) - { - if (canSelect || !text.empty()) - { - context.drawButtonWithIcon(icon, rect, text.c_str(), selected(), pressed, selected(), !userReadOnly(), canSelect, active ? &context.tree->_boldFont() : &context.tree->font()); - } - } - else - { - context.drawEntry(text.c_str(), true, false, iconSpace); - } -} - -bool PropertyRowResourceSelector::processesKey(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - return true; - } - - return PropertyRowField::processesKey(tree, ev); -} - -bool PropertyRowResourceSelector::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - tree->model()->rowAboutToBeChanged(this); - clear(); - tree->model()->rowChanged(this); - return true; - } - return PropertyRowField::onKeyDown(tree, ev); -} - -REGISTER_PROPERTY_ROW(IResourceSelector, PropertyRowResourceSelector); -DECLARE_SEGMENT(PropertyRowResourceSelector) - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceSelector.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceSelector.h deleted file mode 100644 index 0a614cfaed..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceSelector.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCESELECTOR_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCESELECTOR_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyDrawContext.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "PropertyRowField.h" -#include -#include "Serialization/Decorators/Resources.h" -#include "IResourceSelectorHost.h" -#include -#endif - -using Serialization::IResourceSelector; -namespace Serialization { - struct INavigationProvider; -} - -class PropertyRowResourceSelector - : public PropertyRowField -{ -public: - PropertyRowResourceSelector() - : provider_(0) - , id_(0) - , searchHandle_(0) {} - void clear(); - - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - - void jumpTo(QPropertyTree* tree); - bool createFile(QPropertyTree* tree); - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - bool assignTo(const Serialization::SStruct& ser) const override; - bool onActivate(const PropertyActivationEvent& ev) override; - bool onActivateButton(int button, const PropertyActivationEvent& e) override; - bool getHoverInfo(PropertyHoverInfo* hover, const QPoint& cursorPos, const QPropertyTree* tree) const override; - const void* searchHandle() const override { return searchHandle_; } - Serialization::TypeID typeId() const override { return wrappedType_; } - - int buttonCount() const override; - virtual const QIcon& buttonIcon(const QPropertyTree* tree, int index) const override; - virtual bool usePathEllipsis() const override { return true; } - string valueAsString() const; - void serializeValue(Serialization::IArchive& ar); - void redraw(const PropertyDrawContext& context); - - bool onContextMenu(QMenu& menu, QPropertyTree* tree); - bool pickResource(QPropertyTree* tree); - const char* typeNameForFilter([[maybe_unused]] QPropertyTree* tree) const override { return !type_.empty() ? type_.c_str() : "ResourceSelector"; } - - bool processesKey(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; - -private: - SResourceSelectorContext context_; - Serialization::INavigationProvider* provider_; - const void* searchHandle_; - Serialization::TypeID wrappedType_; - QIcon icon_; - - string type_; - string value_; - string defaultPath_; - int id_; -}; - -struct ResourceSelectorMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - QPropertyTree * tree; - PropertyRowResourceSelector* self; - - ResourceSelectorMenuHandler(QPropertyTree* tree, PropertyRowResourceSelector* container); -public slots: - void onMenuCreateFile(); - void onMenuJumpTo(); - void onMenuClear(); - void onMenuPickResource(); -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCESELECTOR_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSlider.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSlider.cpp deleted file mode 100644 index 6ac69973e0..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSlider.cpp +++ /dev/null @@ -1,521 +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 "EditorCommon_precompiled.h" -#include "Serialization/ClassFactory.h" -#include "PropertyTreeModel.h" -#include "PropertyRowNumber.h" -#include "MathUtils.h" - -#include -#include -#include -#include -#include "QPropertyTree.h" -#include "PropertyRow.h" -#include "PropertyDrawContext.h" - -#include "Serialization.h" -#include "Serialization/Decorators/Slider.h" -#include "Serialization/Decorators/SliderImpl.h" -#include - -using Serialization::SSliderF; -using Serialization::SSliderI; - -class PropertyRowSliderF - : public PropertyRowNumberField -{ -public: - static const bool Custom = true; - PropertyRowSliderF(); - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - int floorHeight() const override { return 18; } - void redraw(const PropertyDrawContext& context) override; - - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onMouseDown(QPropertyTree* tree, QPoint point, bool& changed) override; - void onMouseDrag(const PropertyDragEvent& e) override; - void onMouseUp(QPropertyTree* tree, QPoint point) override; - bool assignTo(const Serialization::SStruct& ser) const override - { - if (ser.size() != sizeof(SSliderF)) - { - return false; - } - SSliderF* slider = (SSliderF*)(ser.pointer()); - *slider->valuePointer = clamp(localValue_, slider->minLimit, slider->maxLimit); - return true; - } - bool handleMouse(QPropertyTree* tree, QPoint point); - - bool setValueFromString(const char* str) override - { - float newValue = aznumeric_cast(atof(str)); - if (localValue_ != newValue) - { - localValue_ = newValue; - return true; - } - else - { - return false; - } - } - - string valueAsString() const override - { - return numberAsString(localValue_); - } - - void startIncrement() override - { - incrementStartValue_ = localValue_; - } - - void endIncrement(QPropertyTree* tree) override - { - if (localValue_ != incrementStartValue_) - { - float localValue = localValue_; - localValue_ = incrementStartValue_; - tree->model()->rowAboutToBeChanged(this); - localValue_ = localValue; - tree->model()->rowChanged(this); - } - } - - void incrementLog(float screenFraction, [[maybe_unused]] float valueFieldFraction) - { - double startPower = log10(fabs(double(incrementStartValue_) + 1.0)) - 3.0; - double power = startPower + fabs(screenFraction) * 10.0f; - double delta = powf(10.0f, aznumeric_cast(power)) - powf(10.0f, aznumeric_cast(startPower)) + 10.0f * fabsf(screenFraction); - double newValue; - if (screenFraction > 0.0f) - { - newValue = double(incrementStartValue_) + delta; - } - else - { - newValue = double(incrementStartValue_) - delta; - } - if (_isnan(newValue)) - { - if (screenFraction > 0.0f) - { - newValue = DBL_MAX; - } - else - { - newValue = -DBL_MAX; - } - } - clampToType(&localValue_, newValue); - } - - void serializeValue(Serialization::IArchive& ar) - { - ar(value_.minLimit, "min"); - ar(value_.maxLimit, "max"); - ar(localValue_, "value"); - } - - double sliderPosition() const override { return 0.0; } - - SSliderF value_; - float localValue_; - float incrementStartValue_; - bool captured_; -}; - -bool PropertyRowSliderF::handleMouse(QPropertyTree* tree, QPoint point) -{ - QStyleOptionSlider slider; - slider.rect = floorRect(tree); - QSlider widgetForContext; - QRect sliderGroove = tree->style()->subControlRect(QStyle::CC_Slider, &slider, QStyle::SC_SliderGroove, &widgetForContext); - QRect sliderHandle = tree->style()->subControlRect(QStyle::CC_Slider, &slider, QStyle::SC_SliderHandle, &widgetForContext); - - int sliderLength = sliderGroove.width() - sliderHandle.width(); - - float valRelative = float(point.x() - (sliderGroove.left() + sliderHandle.width() / 2)) / sliderLength; - if (valRelative < 0.0f) - { - valRelative = 0.0f; - } - if (valRelative > 1.0f) - { - valRelative = 1.0f; - } - float newValue = float(valRelative * (value_.maxLimit - value_.minLimit) + value_.minLimit); - if (newValue != localValue_) - { - localValue_ = newValue; - setMultiValue(false); - return true; - } - else - { - return false; - } -} - -bool PropertyRowSliderF::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - float step = (value_.maxLimit - value_.minLimit) * 0.01f; - if (ev->key() == Qt::Key_Left) - { - tree->model()->rowAboutToBeChanged(this); - localValue_ = clamp(localValue_ - step, value_.minLimit, value_.maxLimit); - tree->model()->rowChanged(this); - return true; - } - if (ev->key() == Qt::Key_Right) - { - tree->model()->rowAboutToBeChanged(this); - localValue_ = clamp(localValue_ + step, value_.minLimit, value_.maxLimit); - tree->model()->rowChanged(this); - return true; - } - return PropertyRowNumberField::onKeyDown(tree, ev); -} - -bool PropertyRowSliderF::onMouseDown(QPropertyTree* tree, QPoint point, [[maybe_unused]] bool& changed) -{ - if (floorRect(tree).contains(point) && !userReadOnly()) - { - tree->model()->rowAboutToBeChanged(this); - if (handleMouse(tree, point)) - { - tree->update(); - } - captured_ = true; - return true; - } - captured_ = false; - return true; -} - -void PropertyRowSliderF::onMouseDrag(const PropertyDragEvent& e) -{ - if (!captured_) - { - return; - } - if (userReadOnly()) - { - return; - } - if (handleMouse(e.tree, e.pos)) - { - e.tree->update(); - } -} - -void PropertyRowSliderF::onMouseUp(QPropertyTree* tree, QPoint point) -{ - if (!captured_) - { - return; - } - handleMouse(tree, point); - tree->model()->rowChanged(this); -} - -void PropertyRowSliderF::setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) -{ - value_ = *(SSliderF*)ser.pointer(); - localValue_ = *value_.valuePointer; - value_.valuePointer = 0; -} - -static void drawSlider(const PropertyDrawContext& context, float relativeVal, bool userReadOnly, bool selected) -{ - // Eliminate x-shift offset in the control rect as it triggers a bug in - // Fusion theme, that causes blue area in the slider groove to stand out to - // the right from slider. - int xOffset = context.lineRect.left(); - context.painter->translate(xOffset, 0); - - QStyleOptionSlider sliderOptions; - sliderOptions.rect = context.lineRect.translated(-xOffset, 0); - sliderOptions.minimum = 0; - QSlider widgetForContext; - QRect sliderGroove = context.tree->style()->subControlRect(QStyle::CC_Slider, &sliderOptions, QStyle::SC_SliderGroove, &widgetForContext); - QRect sliderHandle = context.tree->style()->subControlRect(QStyle::CC_Slider, &sliderOptions, QStyle::SC_SliderHandle, &widgetForContext); - int width = sliderGroove.width() - sliderHandle.width() + 1; - sliderOptions.maximum = width; - sliderOptions.pageStep = width / 100; - sliderOptions.sliderPosition = aznumeric_cast(width * relativeVal); - sliderOptions.state = !userReadOnly ? (QStyle::State_Enabled | (selected ? QStyle::State_HasFocus : QStyle::State())) : QStyle::State(); - - context.tree->style()->drawComplexControl(QStyle::CC_Slider, &sliderOptions, context.painter, &widgetForContext); - - context.painter->translate(-xOffset, 0); -} - -void PropertyRowSliderF::redraw(const PropertyDrawContext& context) -{ - PropertyRowNumberField::redraw(context); - float val = localValue_; - float valRange = value_.maxLimit - value_.minLimit; - if (valRange == 0.0f) - { - valRange = 0.00001f; - } - float relativeVal = clamp((val - value_.minLimit) / valRange, 0.0f, 1.0f); - - drawSlider(context, relativeVal, userReadOnly(), selected()); -} - -PropertyRowSliderF::PropertyRowSliderF() - : captured_(false) - , localValue_() - , incrementStartValue_() -{ -} - -DECLARE_SEGMENT(PropertyRowSliderF) -REGISTER_PROPERTY_ROW(SSliderF, PropertyRowSliderF) - -// --------------------------------------------------------------------------- - -class PropertyRowSliderI - : public PropertyRowNumberField -{ -public: - static const bool Custom = true; - PropertyRowSliderI(); - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - int floorHeight() const override { return 18; } - void redraw(const PropertyDrawContext& context) override; - - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onMouseDown(QPropertyTree* tree, QPoint point, bool& changed) override; - void onMouseDrag(const PropertyDragEvent& e) override; - void onMouseUp(QPropertyTree* tree, QPoint point) override; - bool assignTo(const Serialization::SStruct& ser) const override - { - if (ser.size() != sizeof(SSliderI)) - { - return false; - } - SSliderI* slider = (SSliderI*)(ser.pointer()); - *slider->valuePointer = clamp(localValue_, slider->minLimit, slider->maxLimit); - return true; - } - bool handleMouse(QPropertyTree* tree, QPoint point); - - bool setValueFromString(const char* str) override - { - int newValue = atoi(str); - if (localValue_ != newValue) - { - localValue_ = newValue; - return true; - } - else - { - return false; - } - } - Serialization::string valueAsString() const override - { - return numberAsString(localValue_); - } - - void startIncrement() override - { - incrementStartValue_ = localValue_; - } - - void endIncrement(QPropertyTree* tree) override - { - if (localValue_ != incrementStartValue_) - { - int localValue = localValue_; - localValue_ = incrementStartValue_; - tree->model()->rowAboutToBeChanged(this); - localValue_ = localValue; - tree->model()->rowChanged(this); - } - } - - void incrementLog(float screenFraction, [[maybe_unused]] float valueFieldFraction) - { - double startPower = log10(fabs(double(incrementStartValue_) + 1.0)) - 3.0; - double power = startPower + fabs(screenFraction) * 10.0f; - double delta = powf(10.0f, aznumeric_cast(power)) - powf(10.0f, aznumeric_cast(startPower)) + 1000.0f * fabsf(screenFraction); - double newValue; - if (screenFraction > 0.0f) - { - newValue = double(incrementStartValue_) + delta; - } - else - { - newValue = double(incrementStartValue_) - delta; - } - if (_isnan(newValue)) - { - if (screenFraction > 0.0f) - { - newValue = DBL_MAX; - } - else - { - newValue = -DBL_MAX; - } - } - clampToType(&localValue_, newValue); - } - - void serializeValue(Serialization::IArchive& ar) - { - ar(value_.minLimit, "min"); - ar(value_.maxLimit, "max"); - ar(localValue_, "value"); - } - - double sliderPosition() const override { return 0.0; } - - SSliderI value_; - int localValue_; - int incrementStartValue_; - bool captured_; -}; - -bool PropertyRowSliderI::handleMouse(QPropertyTree* tree, QPoint point) -{ - QStyleOptionSlider slider; - slider.rect = floorRect(tree); - - QSlider widgetForContext; - QRect sliderGroove = tree->style()->subControlRect(QStyle::CC_Slider, &slider, QStyle::SC_SliderGroove, &widgetForContext); - QRect sliderHandle = tree->style()->subControlRect(QStyle::CC_Slider, &slider, QStyle::SC_SliderHandle, &widgetForContext); - - int sliderLength = sliderGroove.width() - sliderHandle.width(); - - float valRelative = float(point.x() - (sliderGroove.left() + sliderHandle.width() / 2)) / sliderLength; - if (valRelative < 0.0f) - { - valRelative = 0.0f; - } - if (valRelative > 1.0f) - { - valRelative = 1.0f; - } - int newValue = int(valRelative * (value_.maxLimit - value_.minLimit) + value_.minLimit); - if (newValue != localValue_) - { - localValue_ = newValue; - setMultiValue(false); - return true; - } - else - { - return false; - } -} - -bool PropertyRowSliderI::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - int step = aznumeric_cast((value_.maxLimit - value_.minLimit) * 0.01f); - if (ev->key() == Qt::Key_Left) - { - tree->model()->rowAboutToBeChanged(this); - localValue_ = clamp(localValue_ - step, value_.minLimit, value_.maxLimit); - tree->model()->rowChanged(this); - return true; - } - if (ev->key() == Qt::Key_Right) - { - tree->model()->rowAboutToBeChanged(this); - localValue_ = clamp(localValue_ + step, value_.minLimit, value_.maxLimit); - tree->model()->rowChanged(this); - return true; - } - return PropertyRowNumberField::onKeyDown(tree, ev); -} - -bool PropertyRowSliderI::onMouseDown(QPropertyTree* tree, QPoint point, [[maybe_unused]] bool& changed) -{ - if (floorRect(tree).contains(point) && !userReadOnly()) - { - tree->model()->rowAboutToBeChanged(this); - if (handleMouse(tree, point)) - { - tree->update(); - } - captured_ = true; - return true; - } - captured_ = false; - return true; -} - -void PropertyRowSliderI::onMouseDrag(const PropertyDragEvent& e) -{ - if (!captured_) - { - return; - } - if (userReadOnly()) - { - return; - } - if (handleMouse(e.tree, e.pos)) - { - e.tree->update(); - } -} - -void PropertyRowSliderI::onMouseUp(QPropertyTree* tree, QPoint point) -{ - if (!captured_) - { - return; - } - handleMouse(tree, point); - tree->model()->rowChanged(this); -} - -void PropertyRowSliderI::setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) -{ - value_ = *(SSliderI*)ser.pointer(); - localValue_ = *value_.valuePointer; - value_.valuePointer = 0; -} - -void PropertyRowSliderI::redraw(const PropertyDrawContext& context) -{ - PropertyRowNumberField::redraw(context); - int val = localValue_; - int valRange = value_.maxLimit - value_.minLimit; - if (valRange == 0) - { - valRange = 1; - } - float relativeVal = clamp(float(val - value_.minLimit) / valRange, 0.0f, 1.0f); - - drawSlider(context, relativeVal, userReadOnly(), selected()); -} - -PropertyRowSliderI::PropertyRowSliderI() - : captured_(false) - , localValue_() - , incrementStartValue_() -{ -} - -DECLARE_SEGMENT(PropertyRowSliderI) -REGISTER_PROPERTY_ROW(SSliderI, PropertyRowSliderI) diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSprite.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSprite.cpp deleted file mode 100644 index 3a0afc103c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSprite.cpp +++ /dev/null @@ -1,299 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "SpriteBorderEditorCommon.h" -#include "QPropertyTree.h" -#include "PropertyRowField.h" -#include "PropertyRowSprite.h" -#include "PropertyDrawContext.h" -#include "PropertyTreeModel.h" -#include -#include -#include -#include - -extern QString AssetRelativePathFromAbsolutePath(const QString& absPath); - -bool PropertyRowSprite::onActivateButton(int buttonIndex, const PropertyActivationEvent& ev) -{ - Show show = FromButtonIndexToShow( buttonIndex ); - - if( show == Show::kFilePicker ) - { - return showFilePicker( ev ); - } - - if( show == Show::kSpriteBorderEditor ) - { - return showSpriteBorderEditor( ev ); - } - - // This is to avoid a compiler warning. - // We should NEVER get here. - CRY_ASSERT( 0 ); - return false; -} - -bool PropertyRowSprite::onActivate(const PropertyActivationEvent& ev) -{ - if( PropertyRowField::onActivate( ev ) ) - { - // PropertyRowSprite::onActivateButton() has handled this event. - // Nothing else to do. - return true; - } - - return showFilePicker( ev ); -} - -void PropertyRowSprite::setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) -{ - Serialization::Sprite* value = (Serialization::Sprite *)ser.pointer(); - - m_path = value->m_path->c_str(); -} - -bool PropertyRowSprite::assignTo(const Serialization::SStruct& ser) const -{ - if( ser.size() != sizeof(Serialization::Sprite) ) - { - return false; - } - - Serialization::Sprite* s = (Serialization::Sprite *)ser.pointer(); - - *s->m_path = m_path.c_str(); - - return true; -} - -void PropertyRowSprite::serializeValue(Serialization::IArchive& ar) -{ - ar(m_path, "path"); - ar(m_filter, "filter"); - ar(m_startFolder, "startFolder"); -} - -int PropertyRowSprite::buttonCount() const -{ - return ( CanBeEdited() ? 2 : 1 ); -} - -const QIcon& PropertyRowSprite::buttonIcon(const QPropertyTree* tree, int index) const -{ - Show show = FromButtonIndexToShow( index ); - - if( show == Show::kFilePicker ) - { - #include "file_open.xpm" - static QIcon icon = QIcon(QPixmap::fromImage(*tree->_iconCache()->getImageForIcon(Serialization::IconXPM(file_open_xpm)))); - return icon; - } - - if( show == Show::kSpriteBorderEditor ) - { - #include "gear.xpm" - static QIcon icon = QIcon(QPixmap::fromImage(*tree->_iconCache()->getImageForIcon(Serialization::IconXPM(gear_xpm)))); - return icon; - } - - // This is to avoid a compiler warning. - // We should NEVER get here. - CRY_ASSERT( 0 ); - - #include "gear.xpm" - static QIcon icon; - return icon; -} - -string PropertyRowSprite::valueAsString() const -{ - return m_path; -} - -void PropertyRowSprite::clear() -{ - m_path.clear(); -} - -bool PropertyRowSprite::onContextMenu(QMenu &menu, QPropertyTree* tree) -{ - QAction* action = nullptr; - - action = menu.addAction("Clear"); - QObject::connect( action, - &QAction::triggered, - tree, - [ this, tree ] - { - Clear( tree ); - } ); - - int buttonIndex = ( buttonCount() - 1 ); - - action = menu.addAction(buttonIcon(tree, buttonIndex--), "Pick Resource..."); - QObject::connect( action, - &QAction::triggered, - tree, - [ this, tree ] - { - PropertyActivationEvent ev; - ev.tree = tree; - showFilePicker( ev ); - } ); - - if( buttonIndex >= 0 ) - { - action = menu.addAction(buttonIcon(tree, buttonIndex), "Edit"); - QObject::connect( action, - &QAction::triggered, - tree, - [ this, tree ] - { - PropertyActivationEvent ev; - ev.tree = tree; - showSpriteBorderEditor( ev ); - } ); - } - - return true; -} - -bool PropertyRowSprite::processesKey(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - return true; - } - - return PropertyRowField::processesKey(tree, ev); -} - -bool PropertyRowSprite::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if( ev->key() == Qt::Key_Delete ) - { - Clear( tree ); - return true; - } - return PropertyRowField::onKeyDown(tree, ev); -} - -void PropertyRowSprite::Clear(QPropertyTree* tree) -{ - tree->model()->rowAboutToBeChanged(this); - clear(); - tree->model()->rowChanged(this); -} - -bool PropertyRowSprite::showFilePicker(const PropertyActivationEvent& ev) -{ - if (ev.reason == ev.REASON_RELEASE) - return false; - - // Open the file picker and get the filename the user selects - // (QFileDialog can traverse symlinks and shortcuts) - QString filename = QFileDialog::getOpenFileName(ev.tree, - "Choose file", - QString(), - "*.tif;;*.sprite" ); - - // Early out. - { - if (filename.isEmpty()) - { - // Nothing selected. - return true; - } - - QFileInfo fileInfo( filename ); - if( ! ( ( fileInfo.suffix() == "tif" ) || - ( fileInfo.suffix() == "sprite" ) ) ) - { - // Incompatible files selected. - return true; - } - } - - ev.tree->model()->rowAboutToBeChanged(this); - m_path = AssetRelativePathFromAbsolutePath(filename).toStdString().c_str();; - ev.tree->model()->rowChanged(this); - - return true; -} - -bool PropertyRowSprite::showSpriteBorderEditor(const PropertyActivationEvent& ev) -{ - SpriteBorderEditor sbe( m_path.c_str(), ev.tree ); - if (sbe.GetHasBeenInitializedProperly()) - { - sbe.exec(); - return true; - } - - return false; -} - -bool PropertyRowSprite::CanBeEdited() const -{ - return ( ! m_path.empty() ); -} - -PropertyRowSprite::Show PropertyRowSprite::FromButtonIndexToShow(int index) const -{ - bool showFile = false; - bool showGear = false; - - if( index ) - { - // Second icon from the right. - - showFile = true; - } - else - { - // First icon from the right (right-most icon). - - if( CanBeEdited() ) - { - showGear = true; - } - else - { - showFile = true; - } - } - - if( showFile ) - { - return Show::kFilePicker; - } - - if( showGear ) - { - return Show::kSpriteBorderEditor; - } - - // This is to avoid a compiler warning. - // We should NEVER get here. - CRY_ASSERT( 0 ); - return (Show)0; -} - -DECLARE_SEGMENT(PropertyRowSprite) -REGISTER_PROPERTY_ROW(Serialization::Sprite, PropertyRowSprite); - diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSprite.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSprite.h deleted file mode 100644 index e6f278023d..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSprite.h +++ /dev/null @@ -1,70 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSPRITE_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSPRITE_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyRowField.h" -#endif - -class PropertyRowSprite -: public PropertyRowField -{ -public: - void clear(); - - bool isLeaf() const override{ return true; } - bool isStatic() const override{ return false; } - - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - bool assignTo(const Serialization::SStruct& ser) const override; - bool onActivateButton(int buttonIndex, const PropertyActivationEvent& ev) override; - bool onActivate(const PropertyActivationEvent& ev) override; - - int buttonCount() const override; - virtual const QIcon& buttonIcon(const QPropertyTree* tree, int index) const override; - virtual bool usePathEllipsis() const override { return true; } - string valueAsString() const override; - void serializeValue(Serialization::IArchive& ar); - - bool onContextMenu(QMenu& menu, QPropertyTree* tree); - - bool processesKey(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; - -private: - - enum class Show - { - kFilePicker, - kSpriteBorderEditor - }; - - void Clear(QPropertyTree* tree); - bool showFilePicker(const PropertyActivationEvent& ev); - bool showSpriteBorderEditor(const PropertyActivationEvent& ev); - bool CanBeEdited() const; - Show FromButtonIndexToShow(int index) const; - - string m_path; - string m_filter; - string m_startFolder; - int m_flags; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSPRITE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowString.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowString.cpp deleted file mode 100644 index 200c75d09e..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowString.cpp +++ /dev/null @@ -1,87 +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 "EditorCommon_precompiled.h" -#include - -#include "PropertyRowString.h" -#include "PropertyTreeModel.h" -#include "PropertyDrawContext.h" -#include "QPropertyTree.h" - -#include "Serialization/IArchive.h" -#include "Serialization/ClassFactory.h" -#include -#include "Unicode.h" - -// --------------------------------------------------------------------------- -SERIALIZATION_CLASS_NAME(PropertyRow, PropertyRowString, "PropertyRowString", "string"); - -bool PropertyRowString::assignTo(string& str) const -{ - str = fromWideChar(value_.c_str()); - return true; -} - -bool PropertyRowString::assignTo(wstring& str) const -{ - str = value_; - return true; -} - -PropertyRowWidget* PropertyRowString::createWidget(QPropertyTree* tree) -{ - return new PropertyRowWidgetString(this, tree); -} - -bool PropertyRowString::assignToByPointer(void* instance, const Serialization::TypeID& type) const -{ - if (type == Serialization::TypeID::get()) - { - assignTo(*(string*)instance); - return true; - } - else if (type == Serialization::TypeID::get()) - { - assignTo(*(wstring*)instance); - return true; - } - return false; -} - -string PropertyRowString::valueAsString() const -{ - return fromWideChar(value_.c_str()); -} - -void PropertyRowString::setValue(const wchar_t* str, const void* handle, const Serialization::TypeID& type) -{ - value_ = str; - serializer_.setPointer((void*)handle); - serializer_.setType(type); -} - -void PropertyRowString::setValue(const char* str, const void* handle, const Serialization::TypeID& type) -{ - value_ = toWideChar(str); - serializer_.setPointer((void*)handle); - serializer_.setType(type); -} - -void PropertyRowString::serializeValue(Serialization::IArchive& ar) -{ - ar(value_, "value", "Value"); -} - -#include -// vim:ts=4 sw=4: diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowString.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowString.h deleted file mode 100644 index 4a85466463..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowString.h +++ /dev/null @@ -1,114 +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_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSTRING_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSTRING_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyRowField.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Unicode.h" -#include "MathUtils.h" - -#include -#endif - -class PropertyRowString - : public PropertyRowField -{ -public: - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - using PropertyRowField::assignTo; - bool assignTo(string& str) const; - bool assignTo(wstring& str) const; - void setValue(const char* str, const void* handle, const Serialization::TypeID& typeId); - void setValue(const wchar_t* str, const void* handle, const Serialization::TypeID& typeId); - PropertyRowWidget* createWidget(QPropertyTree* tree); - string valueAsString() const; - wstring valueAsWString() const { return value_; } - WidgetPlacement widgetPlacement() const override { return WIDGET_VALUE; } - void serializeValue(Serialization::IArchive& ar) override; - const wstring& value() const{ return value_; } - bool assignToByPointer(void* instance, const Serialization::TypeID& type) const; -protected: - wstring value_; -}; - -class PropertyRowWidgetString - : public PropertyRowWidget -{ - Q_OBJECT -public: - PropertyRowWidgetString(PropertyRowString* row, QPropertyTree* tree) - : PropertyRowWidget(row, tree) - , entry_(new QLineEdit()) - , tree_(tree) - { - initialValue_ = QString(fromWideChar(row->value().c_str()).c_str()); - entry_->setText(initialValue_); - entry_->selectAll(); - connect(entry_.data(), SIGNAL(editingFinished()), this, SLOT(onEditingFinished())); - connect(entry_.data(), &QLineEdit::textChanged, this, [this, tree] { - QFontMetrics fm(entry_->font()); - int contentWidth = min((int)fm.horizontalAdvance(entry_->text()) + 8, tree->width() - entry_->x()); - if (contentWidth > entry_->width()) - { - entry_->resize(contentWidth, entry_->height()); - } - }); - } - ~PropertyRowWidgetString() - { - entry_->hide(); - entry_->setParent(0); - entry_.take()->deleteLater(); - } - - void commit() - { - onEditingFinished(); - } - QWidget* actualWidget() { return entry_.data(); } - -public slots: - void onEditingFinished() - { - PropertyRowString* row = static_cast(this->row()); - if (initialValue_ != entry_->text() || row_->multiValue()) - { - model()->rowAboutToBeChanged(row); - vector str; - QString text = entry_->text(); - str.resize(text.size() + 1, L'\0'); - if (!text.isEmpty()) - { - text.toWCharArray(&str[0]); - } - row->setValue(&str[0], row->searchHandle(), row->typeId()); - model()->rowChanged(row); - } - else - { - tree_->_cancelWidget(); - } - } -protected: - QPropertyTree* tree_; - QScopedPointer entry_; - QString initialValue_; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSTRING_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowStringListValue.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowStringListValue.cpp deleted file mode 100644 index 35d4589388..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowStringListValue.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 "EditorCommon_precompiled.h" -#include "Factory.h" -#include "PropertyRowStringListValue.h" - -#include "Serialization/IArchive.h" -#include "Serialization/ClassFactory.h" - -using Serialization::StringList; -using Serialization::StringListValue; - -REGISTER_PROPERTY_ROW(StringListValue, PropertyRowStringListValue) - -PropertyRowWidget * PropertyRowStringListValue::createWidget(QPropertyTree * tree) -{ - return new PropertyRowWidgetStringListValue(this, tree); -} - -// --------------------------------------------------------------------------- -REGISTER_PROPERTY_ROW(StringListStaticValue, PropertyRowStringListStaticValue) - -PropertyRowWidget * PropertyRowStringListStaticValue::createWidget(QPropertyTree * tree) -{ - return new PropertyRowWidgetStringListValue(this, tree); -} - -DECLARE_SEGMENT(PropertyRowStringList) - -#include -// vim:ts=4 sw=4: diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowStringListValue.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowStringListValue.h deleted file mode 100644 index f8d31ac45b..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowStringListValue.h +++ /dev/null @@ -1,303 +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_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSTRINGLISTVALUE_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSTRINGLISTVALUE_H -#pragma once -#if !defined(Q_MOC_RUN) -#include "PropertyRowImpl.h" -#include "PropertyTreeModel.h" -#include "PropertyDrawContext.h" -#include "QPropertyTree.h" -#include -#include -#include -#include -#include -#endif - -using Serialization::StringListValue; -class PropertyRowStringListValue - : public PropertyRow -{ -public: - PropertyRowStringListValue() - : handle_() {} - PropertyRowWidget* createWidget(QPropertyTree* tree) override; - string valueAsString() const override { return value_.c_str(); } - bool assignTo(const Serialization::SStruct& ser) const override - { - *((StringListValue*)ser.pointer()) = value_.c_str(); - return true; - } - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override - { - YASLI_ESCAPE(ser.size() == sizeof(StringListValue), return ); - const StringListValue& stringListValue = *((StringListValue*)(ser.pointer())); - stringList_ = stringListValue.stringList(); - value_ = stringListValue.c_str(); - handle_ = stringListValue.handle(); - type_ = stringListValue.type(); - } - - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - int widgetSizeMin(const QPropertyTree* tree) const override - { - if (userWidgetToContent()) - { - return widthCache_.getOrUpdate(tree, this, tree->_defaultRowHeight()); - } - else - { - return 80; - } - } - WidgetPlacement widgetPlacement() const override { return WIDGET_VALUE; } - const void* searchHandle() const override { return handle_; } - Serialization::TypeID typeId() const override { return type_; } - - void redraw(const PropertyDrawContext& context) override - { - if (multiValue()) - { - context.drawEntry(L" ... ", false, true, 0); - } - else if (userReadOnly()) - { - context.drawValueText(pulledSelected(), valueAsWString().c_str()); - } - else - { - QStyleOptionComboBox option; - option.editable = false; - option.frame = true; - option.currentText = QString(valueAsString().c_str()); - option.state |= QStyle::State_Enabled; - option.rect = QRect(0, 0, context.widgetRect.width(), context.widgetRect.height()); - // we have to translate painter here to work around bug in some themes - context.painter->translate(context.widgetRect.left(), context.widgetRect.top()); - - // create a real instance of a combo so that it has the style sheet applied. - QComboBox widgetForContext; - context.tree->style()->drawComplexControl(QStyle::CC_ComboBox, &option, context.painter, &widgetForContext); - context.painter->setPen(QPen(context.tree->palette().color(QPalette::WindowText))); - QRect textRect = context.tree->style()->subControlRect(QStyle::CC_ComboBox, &option, QStyle::SC_ComboBoxEditField, &widgetForContext); - - textRect.adjust(1, 0, -1, 0); - context.tree->_drawRowValue(*context.painter, valueAsWString().c_str(), &context.tree->font(), textRect, context.tree->palette().color(QPalette::WindowText), false, false); - context.painter->translate(-context.widgetRect.left(), -context.widgetRect.top()); - } - } - - - void serializeValue(Serialization::IArchive& ar) - { - ar(value_, "value", "Value"); - ar(stringList_, "stringList", "String List"); - } -private: - Serialization::StringList stringList_; - string value_; - const void* handle_; - Serialization::TypeID type_; - friend class PropertyRowWidgetStringListValue; - mutable RowWidthCache widthCache_; -}; - -using Serialization::StringListStaticValue; -class PropertyRowStringListStaticValue - : public PropertyRowImpl -{ -public: - PropertyRowStringListStaticValue() - : handle_() {} - PropertyRowWidget* createWidget(QPropertyTree* tree) override; - string valueAsString() const override { return value_.c_str(); } - bool assignTo(const Serialization::SStruct& ser) const override - { - *((StringListStaticValue*)ser.pointer()) = value_.c_str(); - return true; - } - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override - { - YASLI_ESCAPE(ser.size() == sizeof(StringListStaticValue), return ); - const StringListStaticValue& stringListValue = *((StringListStaticValue*)(ser.pointer())); - stringList_.resize(stringListValue.stringList().size()); - for (size_t i = 0; i < stringList_.size(); ++i) - { - stringList_[i] = stringListValue.stringList()[i]; - } - value_ = stringListValue.c_str(); - handle_ = stringListValue.handle(); - type_ = stringListValue.type(); - } - - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - int widgetSizeMin(const QPropertyTree* tree) const override - { - if (userWidgetToContent()) - { - return widthCache_.getOrUpdate(tree, this, tree->_defaultRowHeight()); - } - else - { - return 80; - } - } - WidgetPlacement widgetPlacement() const override { return WIDGET_VALUE; } - const void* searchHandle() const override { return handle_; } - Serialization::TypeID typeId() const override { return type_; } - void redraw(const PropertyDrawContext& context) override - { - if (multiValue()) - { - context.drawEntry(L" ... ", false, true, 0); - } - else if (userReadOnly()) - { - context.drawValueText(pulledSelected(), valueAsWString().c_str()); - } - else - { - QStyleOptionComboBox option; - option.currentText = QString(valueAsString().c_str()); - option.state |= QStyle::State_Enabled; - option.rect = context.widgetRect; - - // create a real instance of a combo so that it has the style sheet applied. - QComboBox widgetForContext; - context.tree->style()->drawComplexControl(QStyle::CC_ComboBox, &option, context.painter, &widgetForContext); - context.painter->setPen(QPen(context.tree->palette().color(QPalette::WindowText))); - QRect textRect = context.tree->style()->subControlRect(QStyle::CC_ComboBox, &option, QStyle::SC_ComboBoxEditField, &widgetForContext); - - textRect.adjust(1, 0, -1, 0); - context.tree->_drawRowValue(*context.painter, valueAsWString().c_str(), &context.tree->font(), textRect, context.tree->palette().color(QPalette::WindowText), false, false); - } - } - - - void serializeValue(Serialization::IArchive& ar) - { - ar(value_, "value", "Value"); - ar(stringList_, "stringList", "String List"); - } -private: - Serialization::StringList stringList_; - string value_; - const void* handle_; - Serialization::TypeID type_; - friend class PropertyRowWidgetStringListValue; - mutable RowWidthCache widthCache_; -}; - - -// --------------------------------------------------------------------------- - - -class PropertyRowWidgetStringListValue - : public PropertyRowWidget -{ - Q_OBJECT -public: - PropertyRowWidgetStringListValue(PropertyRowStringListValue* row, QPropertyTree* tree) - : PropertyRowWidget(row, tree) - , comboBox_(new QComboBox()) - { - const Serialization::StringList& stringList = row->stringList_; - for (size_t i = 0; i < stringList.size(); ++i) - { - comboBox_->addItem(stringList[i].c_str()); - } - comboBox_->setCurrentIndex(stringList.find(row->value_.c_str())); - connect(comboBox_, SIGNAL(activated(int)), this, SLOT(onChange(int))); - } - - PropertyRowWidgetStringListValue(PropertyRowStringListStaticValue* row, QPropertyTree* tree) - : PropertyRowWidget(row, tree) - , comboBox_(new QComboBox()) - { - const Serialization::StringList& stringList = row->stringList_; - for (size_t i = 0; i < stringList.size(); ++i) - { - comboBox_->addItem(stringList[i].c_str()); - } - comboBox_->setCurrentIndex(stringList.find(row->value_.c_str())); - connect(comboBox_, SIGNAL(currentIndexChanged(int)), this, SLOT(onChange(int))); - } - - void showPopup() override - { - // Here comboBox_->showPopup() should be sufficient, but sadly with Fusion - // theme ComboBox, when clicked, it fires a mouseReleseTimer, which doesn't - // happen with showPopup. It is used to distinguish click-and-hold from - // simple click. If timer is not fired following mouse release hides combo - // box. That's why the user click is emulated here. - QSize size = comboBox_->size(); - QPoint localPoint = QPoint(aznumeric_cast(size.width() * 0.5f), aznumeric_cast(size.height() * 0.5f)); - QMouseEvent ev(QMouseEvent::MouseButtonPress, localPoint, comboBox_->mapToGlobal(localPoint), Qt::LeftButton, Qt::LeftButton, Qt::KeyboardModifiers()); - QApplication::sendEvent(comboBox_, &ev); - } - - ~PropertyRowWidgetStringListValue() - { - comboBox_->hide(); - comboBox_->setParent(0); - comboBox_->deleteLater(); - comboBox_ = 0; - } - - - void commit(){} - QWidget* actualWidget() { return comboBox_; } -public slots: - void onChange(int) - { - if (strcmp(this->row()->typeName(), Serialization::TypeID::get().name()) == 0) - { - PropertyRowStringListValue* r = static_cast(this->row()); - QByteArray newValue = comboBox_->currentText().toUtf8(); - if (r->value_ != newValue.data()) - { - model()->rowAboutToBeChanged(r); - r->value_ = newValue.data(); - model()->rowChanged(r); - } - else - { - tree_->_cancelWidget(); - } - } - else if (strcmp(this->row()->typeName(), Serialization::TypeID::get().name()) == 0) - { - PropertyRowStringListStaticValue* r = static_cast(this->row()); - QByteArray newValue = comboBox_->currentText().toUtf8(); - if (r->value_ != newValue.data()) - { - model()->rowAboutToBeChanged(r); - r->value_ = newValue.data(); - model()->rowChanged(r); - } - else - { - tree_->_cancelWidget(); - } - } - } -protected: - QComboBox* comboBox_; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSTRINGLISTVALUE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowTagList.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowTagList.cpp deleted file mode 100644 index 832357bfc7..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowTagList.cpp +++ /dev/null @@ -1,132 +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 "EditorCommon_precompiled.h" -#include "PropertyRowTagList.h" -#include "PropertyRowString.h" -#include "QPropertyTree.h" -#include "Serialization/Decorators/TagList.h" -#include "Serialization/ClassFactory.h" -#include "Serialization/IArchive.h" -#include "Serialization/Decorators/TagListImpl.h" -#include - -PropertyRowTagList::PropertyRowTagList() - : source_(0) -{ -} - -PropertyRowTagList::~PropertyRowTagList() -{ - if (source_) - { - source_->Release(); - } -} - -void PropertyRowTagList::generateMenu(QMenu& item, QPropertyTree* tree, [[maybe_unused]] bool addActions) -{ - if (userReadOnly() || isFixedSize()) - { - return; - } - - if (!source_) - { - return; - } - - TagListMenuHandler* handler = new TagListMenuHandler(); - handler->tree = tree; - handler->row = this; - tree->addMenuHandler(handler); - - unsigned int numGroups = source_->GroupCount(); - for (unsigned int group = 0; group < numGroups; ++group) - { - unsigned int tagCount = source_->TagCount(group); - if (tagCount == 0) - { - continue; - } - const char* groupName = source_->GroupName(group); - QString title = QString("From ") + groupName; - QMenu* menu = item.addMenu(title); - for (unsigned int tagIndex = 0; tagIndex < tagCount; ++tagIndex) - { - QString str; - str = source_->TagValue(group, tagIndex); - const char* desc = source_->TagDescription(group, tagIndex); - if (desc && desc[0] != '\0') - { - str += "\t"; - str += desc; - } - QAction* action = menu->addAction(str); - QString tag = QString::fromLocal8Bit(source_->TagValue(group, tagIndex)); - action->setData(QVariant(tag)); - QObject::connect(action, SIGNAL(triggered()), handler, SLOT(onMenuAddTag())); - } - } - - - QAction* action = item.addAction("Add"); - action->setData(QVariant(QString())); - QObject::connect(action, SIGNAL(triggered()), handler, SLOT(onMenuAddTag())); - - PropertyRowContainer::generateMenu(item, tree, false); -} - -void PropertyRowTagList::addTag(const char* tag, QPropertyTree* tree) -{ - Serialization::SharedPtr ref(this); - - PropertyRow* child = addElement(tree, false); - if (child && strcmp(child->typeName(), "string") == 0) - { - PropertyRowString* stringRow = static_cast(child); - tree->model()->rowAboutToBeChanged(stringRow); - stringRow->setValue(tag, stringRow->searchHandle(), stringRow->typeId()); - tree->model()->rowChanged(stringRow); - } -} - -void TagListMenuHandler::onMenuAddTag() -{ - if (QAction* action = qobject_cast(sender())) - { - QString str = action->data().toString(); - row->addTag(str.toLocal8Bit().data(), tree); - } -} - -void PropertyRowTagList::setValueAndContext(const Serialization::IContainer& value, Serialization::IArchive& ar) -{ - if (source_) - { - source_->Release(); - } - source_ = ar.FindContext(); - if (source_) - { - source_->AddRef(); - } - - PropertyRowContainer::setValueAndContext(value, ar); -} - - -REGISTER_PROPERTY_ROW(TagList, PropertyRowTagList) -DECLARE_SEGMENT(PropertyRowTagList) - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowTagList.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowTagList.h deleted file mode 100644 index 4ea032efa9..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowTagList.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWTAGLIST_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWTAGLIST_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyRowContainer.h" -#endif - -struct ITagSource; - -class PropertyRowTagList - : public PropertyRowContainer -{ -public: - PropertyRowTagList(); - ~PropertyRowTagList(); - void setValueAndContext(const Serialization::IContainer& value, Serialization::IArchive& ar) override; - void generateMenu(QMenu& item, QPropertyTree* tree, bool addActions) override; - void addTag(const char* tag, QPropertyTree* tree); - -private: - using PropertyRow::setValueAndContext; - ITagSource* source_; -}; - -struct TagListMenuHandler - : public PropertyRowMenuHandler -{ - Q_OBJECT -public: - - PropertyRowTagList * row; - QPropertyTree* tree; -public slots: - void onMenuAddTag(); -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWTAGLIST_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowToggleButton.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowToggleButton.cpp deleted file mode 100644 index 7ae3231673..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowToggleButton.cpp +++ /dev/null @@ -1,205 +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 "EditorCommon_precompiled.h" -#include - -#include "Serialization/ClassFactory.h" -#include "PropertyDrawContext.h" -#include "PropertyRowImpl.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Serialization.h" -#include "Color.h" -#include "Unicode.h" -#include "Serialization/Decorators/ToggleButton.h" -using Serialization::ToggleButton; -using Serialization::RadioButton; - -class PropertyRowToggleButton - : public PropertyRow -{ -public: - PropertyRowToggleButton() - : underMouse_(false) - , value_(false) - { - } - - bool isLeaf() const{ return true; } - bool isStatic() const{ return false; } - bool isSelectable() const{ return true; } - - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override - { - ToggleButton* value = (ToggleButton*)(ser.pointer()); - value_ = *value->value; - } - - bool assignTo(const Serialization::SStruct& ser) const override - { - ToggleButton* value = (ToggleButton*)(ser.pointer()); - *value->value = value_; - return true; - } - wstring valueAsWString() const override { return L""; } - WidgetPlacement widgetPlacement() const override { return WIDGET_INSTEAD_OF_TEXT; } - void serializeValue([[maybe_unused]] Serialization::IArchive& ar) {} - int widgetSizeMin([[maybe_unused]] const QPropertyTree* tree) const override { return 36; } - - bool onActivate(const PropertyActivationEvent& e) override - { - if (e.reason == PropertyActivationEvent::REASON_KEYBOARD) - { - value_; - } - return true; - } - - bool onMouseDown(QPropertyTree* tree, QPoint point, [[maybe_unused]] bool& changed) override - { - if (widgetRect(tree).contains(point)) - { - underMouse_ = true; - pressed_ = true; - tree->update(); - return true; - } - return false; - } - - void onMouseDrag(const PropertyDragEvent& e) override - { - bool underMouse = widgetRect(e.tree).contains(e.pos); - if (underMouse != underMouse_) - { - underMouse_ = underMouse; - e.tree->update(); - } - } - - void onMouseUp(QPropertyTree* tree, QPoint point) override - { - if (widgetRect(tree).contains(point)) - { - tree->model()->rowAboutToBeChanged(this); - pressed_ = false; - value_ = !value_; - tree->model()->rowChanged(this); - } - } - - void redraw(const PropertyDrawContext& context) override - { - QRect rect = context.widgetRect; - - wstring text = toWideChar(labelUndecorated()); - int buttonFlags = BUTTON_CENTER; - if ((value_ || pressed_) && underMouse_) - { - buttonFlags |= BUTTON_PRESSED; - } - if (selected() || pressed_) - { - buttonFlags |= BUTTON_FOCUSED; - } - if (userReadOnly()) - { - buttonFlags |= BUTTON_DISABLED; - } - context.drawButton(rect, text.c_str(), buttonFlags, &context.tree->font()); - } -protected: - bool pressed_ : 1; - bool underMouse_ : 1; - bool value_ : 1; -}; - -class PropertyRowRadioButton - : public PropertyRow -{ -public: - - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - bool isSelectable() const override { return false; } - - bool onActivate(const PropertyActivationEvent& e) override - { - if (!m_justSet) - { - e.tree->model()->rowAboutToBeChanged(this); - m_justSet = true; - e.tree->model()->rowChanged(this); - } - return true; - } - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override - { - RadioButton* value = (RadioButton*)(ser.pointer()); - m_value = value->buttonValue; - m_toggled = m_value == *value->value; - m_justSet = false; - } - bool assignTo(const Serialization::SStruct& ser) const override - { - if (m_justSet) - { - *((RadioButton*)ser.pointer())->value = m_value; - } - return true; - } - wstring valueAsWString() const override { return L""; } - WidgetPlacement widgetPlacement() const override { return WIDGET_INSTEAD_OF_TEXT; } - void serializeValue(Serialization::IArchive& ar) override - { - bool oldToggled = m_toggled; - ar(m_toggled, "toggled"); - if (m_toggled && !oldToggled) - { - m_justSet = true; - } - ar(m_value, "value"); - } - int widgetSizeMin([[maybe_unused]] const QPropertyTree* tree) const override { return 40; } - - void redraw(const PropertyDrawContext& context) - { - QRect rect = context.widgetRect; - bool pressed = context.m_pressed || m_toggled || m_justSet; - - wstring text = toWideChar(labelUndecorated()); - int buttonFlags = BUTTON_CENTER; - if (pressed) - { - buttonFlags |= BUTTON_PRESSED; - } - if (selected()) - { - buttonFlags |= BUTTON_FOCUSED; - } - if (userReadOnly()) - { - buttonFlags |= BUTTON_DISABLED; - } - context.drawButton(rect, text.c_str(), buttonFlags, &context.tree->font()); - } -protected: - bool m_toggled; - bool m_justSet; - int m_value; -}; - -REGISTER_PROPERTY_ROW(ToggleButton, PropertyRowToggleButton); -REGISTER_PROPERTY_ROW(RadioButton, PropertyRowRadioButton); diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeMenuHandler.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeMenuHandler.h deleted file mode 100644 index 2d821266da..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeMenuHandler.h +++ /dev/null @@ -1,45 +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_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEMENUHANDLER_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEMENUHANDLER_H -#pragma once - -#include "PropertyRow.h" - -struct PropertyTreeMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - PropertyRow * row; - QPropertyTree* tree; - - string filterName; - string filterValue; - string filterType; - -public slots: - void onMenuFilter(); - void onMenuFilterByName(); - void onMenuFilterByValue(); - void onMenuFilterByType(); - - void onMenuUndo(); - void onMenuRedo(); - - void onMenuCopy(); - void onMenuPaste(); -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEMENUHANDLER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeModel.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeModel.cpp deleted file mode 100644 index 7192757ecc..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeModel.cpp +++ /dev/null @@ -1,445 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "PropertyTreeModel.h" -#include "QPropertyTree.h" -#include "Serialization.h" -#include "Serialization/ClassFactory.h" -#include "Serialization/Callback.h" - -PropertyTreeModel::PropertyTreeModel() -: expandLevels_(0) -, undoEnabled_(true) -, fullUndo_(false) -{ - clear(); -} - -PropertyTreeModel::~PropertyTreeModel() -{ - root_ = 0; - defaultTypes_.clear(); - defaultTypesPoly_.clear(); -} - -TreePath PropertyTreeModel::pathFromRow(PropertyRow* row) -{ - TreePath result; - if(row) - { - while(row->parent()){ - int childIndex = row->parent()->childIndex(row); - YASLI_ESCAPE(childIndex >= 0, return TreePath()); - result.insert(result.begin(), childIndex); - row = row->parent(); - } - } - return result; -} - -void PropertyTreeModel::selectRow(PropertyRow* row, bool select, bool exclusive) -{ - if(exclusive) - deselectAll(); - - row->setSelected(select); - - Selection::iterator it = std::find(selection_.begin(), selection_.end(), pathFromRow(row)); - if(select){ - if(it == selection_.end()) - selection_.push_back(pathFromRow(row)); - setFocusedRow(row); - } - else if(it != selection_.end()){ -#if !defined(NDEBUG) - PropertyRow* it_row = rowFromPath(*it); -#endif - YASLI_ASSERT(it_row->refCount() > 0 && it_row->refCount() < 0xFFFF); - selection_.erase(it); - } -} - -void PropertyTreeModel::deselectAll() -{ - Selection::iterator it; - for(it = selection_.begin(); it != selection_.end(); ++it){ - PropertyRow* row = rowFromPath(*it); - row->setSelected(false); - } - selection_.clear(); -} - -PropertyRow* PropertyTreeModel::rowFromPath(const TreePath& path) -{ - PropertyRow* row = root(); - if (!root()) - return 0; - TreePath::const_iterator it; - for(it = path.begin(); it != path.end(); ++it){ - int index = it->index; - if(index < int(row->count()) && index >= 0){ - PropertyRow* nextRow = row->childByIndex(index); - if(!nextRow) - return row; - else - row = nextRow; - } - else - return row; - } - return row; -} - -void PropertyTreeModel::setSelection(const Selection& selection) -{ - deselectAll(); - Selection::const_iterator it; - for(it = selection.begin(); it != selection.end(); ++it){ - const TreePath& path = *it; - PropertyRow* row = rowFromPath(path); - if(row) - selectRow(row, true, false); - } -} - -void PropertyTreeModel::clear() -{ - if(root_) - root_->clear(); - root_ = 0; - setRoot(new PropertyRow()); - root_->setNames("", "root", ""); - selection_.clear(); -} - -void PropertyTreeModel::onUpdated(const PropertyRows& rows, bool needApply) -{ - signalUpdated(rows, needApply); -} - -void PropertyTreeModel::applyOperator(PropertyTreeOperator* op) -{ - YASLI_ESCAPE(op, return); - PropertyRow *dest = rowFromPath(op->path_); - YASLI_ESCAPE(dest && "Unable to apply operator!", return); - if(op->type_ == PropertyTreeOperator::NONE) - return; - YASLI_ESCAPE(op->row_, return); - if(dest->parent()) - dest->parent()->replaceAndPreserveState(dest, op->row_, 0); - else{ - op->row_->assignRowProperties(root_); - root_ = op->row_; - } - PropertyRow* newRow = op->row_; - op->row_ = 0; - rowChanged(newRow); -} - -void PropertyTreeModel::undo() -{ - YASLI_ESCAPE(!undoOperators_.empty(), return); - - auto op = &undoOperators_.back(); - PropertyRow *dest = rowFromPath(op->path_); - PropertyTreeOperator redoOp = getCurrentStateTreeOperator(dest); - - applyOperator(op); - undoOperators_.pop_back(); - - pushRedo(redoOp); -} - -void PropertyTreeModel::redo() -{ - YASLI_ESCAPE(!redoOperators_.empty(), return); - - auto op = &redoOperators_.back(); - PropertyRow *dest = rowFromPath(op->path_); - PropertyTreeOperator undoOp = getCurrentStateTreeOperator(dest); - - applyOperator(op); - redoOperators_.pop_back(); - - pushUndo(undoOp); -} - -void PropertyTreeModel::clearUndo() -{ - undoOperators_.clear(); - redoOperators_.clear(); - - Q_EMIT signalUndoRedoStackChanged(false, false); -} - -PropertyTreeModel::UpdateLock PropertyTreeModel::lockUpdate() -{ - if(updateLock_) - return updateLock_; - else { - UpdateLock lock = new PropertyTreeModel::LockedUpdate(this);; - updateLock_ = lock; - lock->release(); - return lock; - } -} - -void PropertyTreeModel::dismissUpdate() -{ - if(updateLock_) - updateLock_->dismissUpdate(); -} - -void PropertyTreeModel::requestUpdate(const PropertyRows& rows, bool apply) -{ - if(updateLock_) - updateLock_->requestUpdate(rows, apply); - else - onUpdated(rows, apply); -} - -struct RowObtainer { - RowObtainer(std::vector& states) : states_(states) {} - ScanResult operator()(PropertyRow* row) - { - states_.push_back(row->expanded() ? 1 : 0); - return row->expanded() ? SCAN_CHILDREN_SIBLINGS : SCAN_SIBLINGS; - } -protected: - std::vector& states_; -}; - -struct RowExpander { - RowExpander(const std::vector& states) : states_(states), index_(0) {} - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, [[maybe_unused]] int index) - { - if(size_t(index_) >= states_.size()) - return SCAN_FINISHED; - - if(states_[index_++]){ - if(row->canBeToggled(tree)) - row->_setExpanded(true); - return SCAN_CHILDREN_SIBLINGS; - } - else{ - row->_setExpanded(false); - return SCAN_SIBLINGS; - } - } -protected: - int index_; - const std::vector& states_; -}; - -void PropertyTreeModel::Serialize(Serialization::IArchive& ar, QPropertyTree* tree) -{ - ar(focusedRow_, "focusedRow", 0); - ar(selection_, "selection", 0); - - if (root()) { - std::vector expanded; - if(ar.IsOutput()) { - RowObtainer op(expanded); - root()->scanChildren(op); - } - ar(expanded, "expanded", 0); - if(ar.IsInput()){ - Selection sel = selection_; - setSelection(sel); - RowExpander op(expanded); - root()->scanChildren(op, tree); - root()->setLayoutChanged(); - root()->setLayoutChangedToChildren(); - } - } -} - -void PropertyTreeModel::pushUndo(const PropertyTreeOperator& op) -{ - PropertyTreeOperator oper = op; - bool handled = false; - signalPushUndo(&oper, &handled); - if(!handled && oper.row_ != 0) - undoOperators_.push_back(oper); - - Q_EMIT signalUndoRedoStackChanged(!undoOperators_.empty(), !redoOperators_.empty()); -} - -void PropertyTreeModel::pushRedo(const PropertyTreeOperator& op) -{ - PropertyTreeOperator oper = op; - bool handled = false; - signalPushRedo(&oper, &handled); - if (!handled && oper.row_ != 0) - redoOperators_.push_back(oper); - - Q_EMIT signalUndoRedoStackChanged(!undoOperators_.empty(), !redoOperators_.empty()); -} - -PropertyTreeOperator PropertyTreeModel::getCurrentStateTreeOperator(PropertyRow* row) -{ - if (fullUndo_){ - if (undoEnabled_){ - SharedPtr clonedRow = root()->clone(constStrings()); - clonedRow->assignRowState(*root(), true); - return PropertyTreeOperator(TreePath(), clonedRow); - } - else{ - return PropertyTreeOperator(TreePath(), 0); - } - } - else{ - if (undoEnabled_){ - SharedPtr clonedRow = row->clone(constStrings()); - clonedRow->assignRowState(*row, true); - return PropertyTreeOperator(pathFromRow(row), clonedRow); - } - else{ - return PropertyTreeOperator(pathFromRow(row), 0); - } - } -} - -void PropertyTreeModel::rowAboutToBeChanged(PropertyRow* row) -{ - YASLI_ESCAPE(row, return); - pushUndo(getCurrentStateTreeOperator(row)); - - // clear the redo stack now - redoOperators_.clear(); - Q_EMIT signalUndoRedoStackChanged(true, false); -} - -void PropertyTreeModel::callRowCallback(PropertyRow* row) -{ - PropertyRow* current = row; - while (true) { - Serialization::ICallback* callback = current->callback(); - if (callback) { - auto applyFunc = [=](void* arg, [[maybe_unused]] const TypeID& type) { - current->assignToByPointer(arg, callback->Type()); - }; - callback->Call(applyFunc); - return; - } - current = current->parent(); - if (current) - current->handleChildrenChange(); - else - break; - } -} - -void PropertyTreeModel::rowChanged(PropertyRow* row, bool apply) -{ - callRowCallback(row); - - YASLI_ESCAPE(row, return); - row->setLabelChanged(); - row->setLayoutChanged(); - - PropertyRow* parentObj = row; - while (parentObj->parent() && !parentObj->isObject()) - parentObj = parentObj->parent(); - - row->setMultiValue(false); - - PropertyRows rows; - rows.push_back(parentObj); - requestUpdate(rows, apply); -} - -bool PropertyTreeModel::defaultTypeRegistered(const char* typeName) const -{ - return defaultTypes_.find(typeName) != defaultTypes_.end(); -} - -void PropertyTreeModel::addDefaultType(PropertyRow* row, const char* typeName) -{ - YASLI_ESCAPE(typeName != 0, return); - defaultTypes_[typeName] = row; -} - -PropertyRow* PropertyTreeModel::defaultType(const char* typeName) const -{ - DefaultTypes::const_iterator it = defaultTypes_.find(typeName); - YASLI_ESCAPE(it != defaultTypes_.end(), return 0); - return it->second; -} - -void PropertyTreeModel::addDefaultType(const TypeID& type, const PropertyDefaultDerivedTypeValue& value) -{ - YASLI_ASSERT(type != TypeID()); - - BaseClass& base = defaultTypesPoly_[type]; - for (DerivedTypes::iterator it = base.types.begin(); it != base.types.end(); ++it){ - if (it->registeredName == value.registeredName) { - YASLI_ASSERT(it->root == 0); - *it = value; - return; - } - } - - base.types.push_back(value); - base.strings.push_back(value.label.c_str()); -} - -const PropertyDefaultDerivedTypeValue* PropertyTreeModel::defaultType(const TypeID& baseType, int derivedIndex) const -{ - DefaultTypesPoly::const_iterator it = defaultTypesPoly_.find(baseType); - YASLI_ESCAPE(it != defaultTypesPoly_.end(), return 0); - const BaseClass& base = it->second; - YASLI_ESCAPE(size_t(derivedIndex) < base.types.size(), return 0); - return &base.types[derivedIndex]; -} - -bool PropertyTreeModel::defaultTypeRegistered(const TypeID& baseType, const char* derivedRegisteredName) const -{ - if (!derivedRegisteredName) - derivedRegisteredName = ""; - DefaultTypesPoly::const_iterator it = defaultTypesPoly_.find(baseType); - - if (it == defaultTypesPoly_.end()) - return false; - - const BaseClass& base = it->second; - DerivedTypes::const_iterator dit; - for (dit = base.types.begin(); dit != base.types.end(); ++dit){ - if (dit->registeredName == derivedRegisteredName) - return true; - } - return false; -} - -const Serialization::StringList& PropertyTreeModel::typeStringList(const TypeID& baseType) const -{ - DefaultTypesPoly::const_iterator it = defaultTypesPoly_.find(baseType); - - static Serialization::StringList empty; - YASLI_ESCAPE(it != defaultTypesPoly_.end(), return empty); - const BaseClass& base = it->second; - return base.strings; -} - -// ---------------------------------------------------------------------------------- - -bool Serialize(Serialization::IArchive& ar, TreePathLeaf& value, const char* name, const char* label) -{ - return ar(value.index, name, label); -} - -bool Serialize(Serialization::IArchive& ar, TreeSelection& value, const char* name, const char* label) -{ - return ar(static_cast&>(value), name, label); -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeModel.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeModel.h deleted file mode 100644 index 0b518f8171..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeModel.h +++ /dev/null @@ -1,208 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEMODEL_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEMODEL_H -#pragma once - - -#if !defined(Q_MOC_RUN) -#include -#include "PropertyRow.h" -#include "PropertyTreeOperator.h" -#include "Serialization/Pointers.h" -#endif - -using std::vector; -using std::map; - -struct TreeSelection : vector -{ - bool operator==(const TreeSelection& rhs){ - if(size() != rhs.size()) - return false; - for(int i = 0; i < int(size()); ++i) - if((*this)[i] != rhs[i]) - return false; - return true; - } -}; - -struct PropertyDefaultDerivedTypeValue -{ - string registeredName; - Serialization::SharedPtr root; - Serialization::IClassFactory* factory; - int factoryIndex; - std::string label; - - PropertyDefaultDerivedTypeValue() - : factoryIndex(-1) - , factory(0) - { - } -}; - -struct PropertyDefaultTypeValue -{ - Serialization::TypeID type; - string registedName; - Serialization::SharedPtr root; - Serialization::IClassFactory* factory; - int factoryIndex; - std::string label; - - PropertyDefaultTypeValue() - : factoryIndex(-1) - , factory(0) - { - } -}; - -// --------------------------------------------------------------------------- - -class PropertyTreeModel : public QObject -{ - Q_OBJECT -public: - class LockedUpdate : public Serialization::RefCounter{ - public: - LockedUpdate(PropertyTreeModel* model) - : model_(model) - , apply_(false) - {} - void requestUpdate(const PropertyRows& rows, bool apply) { - for (size_t i = 0; i < rows.size(); ++i) { - PropertyRow* row = rows[i]; - if (std::find(rows_.begin(), rows_.end(), row) == rows_.end()) - rows_.push_back(row); - } - if (apply) - apply_ = true; - } - void dismissUpdate(){ rows_.clear(); } - ~LockedUpdate(){ - model_->updateLock_ = 0; - if(!rows_.empty()) - model_->signalUpdated(rows_, apply_); - } - protected: - PropertyTreeModel* model_; - PropertyRows rows_; - bool apply_; - }; - typedef Serialization::SharedPtr UpdateLock; - - typedef TreeSelection Selection; - - PropertyTreeModel(); - ~PropertyTreeModel(); - - void clear(); - bool canUndo() const{ return !undoOperators_.empty(); } - void undo(); - bool canRedo() const{ return !redoOperators_.empty(); } - void redo(); - void clearUndo(); - - TreePath pathFromRow(PropertyRow* node); - PropertyRow* rowFromPath(const TreePath& path); - void setFocusedRow(PropertyRow* row) { focusedRow_ = pathFromRow(row); } - PropertyRow* focusedRow() { return rowFromPath(focusedRow_); } - - const Selection& selection() const{ return selection_; } - void setSelection(const Selection& selection); - - void setRoot(PropertyRow* root) { root_ = root; } - PropertyRow* root() { return root_; } - const PropertyRow* root() const { return root_; } - - void Serialize(Serialization::IArchive& ar, QPropertyTree* tree); - - UpdateLock lockUpdate(); - void requestUpdate(const PropertyRows& rows, bool needApply); - void dismissUpdate(); - - void selectRow(PropertyRow* row, bool selected, bool exclusive = true); - void deselectAll(); - - void rowAboutToBeChanged(PropertyRow* row); - void callRowCallback(PropertyRow* row); - void rowChanged(PropertyRow* row, bool apply = true); // be careful: it can destroy 'row' - - void setUndoEnabled(bool enabled) { undoEnabled_ = enabled; } - void setFullUndo(bool fullUndo) { fullUndo_ = fullUndo; } - void setExpandLevels(int levels) { expandLevels_ = levels; } - int expandLevels() const{ return expandLevels_; } - - void onUpdated(const PropertyRows& rows, bool needApply); - - // for defaultArchive - const Serialization::StringList& typeStringList(const Serialization::TypeID& baseType) const; - - bool defaultTypeRegistered(const char* typeName) const; - void addDefaultType(PropertyRow* propertyRow, const char* typeName); - PropertyRow* defaultType(const char* typeName) const; - - bool defaultTypeRegistered(const Serialization::TypeID& baseType, const char* derivedRegisteredName) const; - void addDefaultType(const Serialization::TypeID& baseType, const PropertyDefaultDerivedTypeValue& value); - const PropertyDefaultDerivedTypeValue* defaultType(const Serialization::TypeID& baseType, int index) const; - ConstStringList* constStrings() { return &constStrings_; } - -signals: - void signalUpdated(const PropertyRows& rows, bool needApply); - void signalPushUndo(PropertyTreeOperator* op, bool* result); - void signalPushRedo(PropertyTreeOperator* op, bool* result); - - void signalUndoRedoStackChanged(bool undosAvailable, bool redosAvailable); -private: - void applyOperator(PropertyTreeOperator* op); - void pushUndo(const PropertyTreeOperator& op); - void pushRedo(const PropertyTreeOperator& op); - - void clearObjectReferences(); - PropertyTreeOperator getCurrentStateTreeOperator(PropertyRow* row); - - TreePath focusedRow_; - Selection selection_; - - Serialization::SharedPtr root_; - UpdateLock updateLock_; - - typedef std::map > DefaultTypes; - DefaultTypes defaultTypes_; - - - typedef vector DerivedTypes; - struct BaseClass{ - Serialization::TypeID type; - std::string name; - Serialization::StringList strings; - DerivedTypes types; - }; - typedef map DefaultTypesPoly; - DefaultTypesPoly defaultTypesPoly_; - - int expandLevels_; - bool undoEnabled_; - bool fullUndo_; - - std::vector undoOperators_; - std::vector redoOperators_; - - ConstStringList constStrings_; - - friend class TreeImpl; -}; - -bool Serialize(Serialization::IArchive& ar, TreeSelection &selection, const char* name, const char* label); -// vim:ts=4 sw=4: - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEMODEL_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeOperator.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeOperator.cpp deleted file mode 100644 index 1c70b6d73c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeOperator.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "PropertyTreeOperator.h" -#include "PropertyRow.h" -#include "Serialization/Enum.h" -#include "Serialization/STL.h" -#include "Serialization/Pointers.h" -#include "Serialization/IArchive.h" -#include "Serialization/STLImpl.h" -#include "Serialization/PointersImpl.h" - -SERIALIZATION_ENUM_BEGIN_NESTED(PropertyTreeOperator, Type, "PropertyTreeOp") -SERIALIZATION_ENUM_VALUE_NESTED(PropertyTreeOperator, REPLACE, "Replace") -SERIALIZATION_ENUM_VALUE_NESTED(PropertyTreeOperator, ADD, "Add") -SERIALIZATION_ENUM_VALUE_NESTED(PropertyTreeOperator, REMOVE, "Remove") -SERIALIZATION_ENUM_END() - -PropertyTreeOperator::PropertyTreeOperator(const TreePath& path, PropertyRow* row) -: type_(REPLACE) -, path_(path) -, index_(-1) -, row_(row) -{ -} - -PropertyTreeOperator::PropertyTreeOperator() -: type_(NONE) -, index_(-1) -{ -} - -PropertyTreeOperator::~PropertyTreeOperator() -{ -} - -void PropertyTreeOperator::Serialize(Serialization::IArchive& ar) -{ - ar(type_, "type", "Type"); - ar(path_, "path", "Path"); - ar(row_, "row", "Row"); - ar(index_, "index", "Index"); -} - diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeOperator.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeOperator.h deleted file mode 100644 index 0316cfe7cd..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeOperator.h +++ /dev/null @@ -1,65 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEOPERATOR_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEOPERATOR_H -#pragma once - -#include -#include "Serialization/Pointers.h" - -namespace Serialization{ class IArchive; } - -class PropertyRow; - -struct TreePathLeaf -{ - int index; - - TreePathLeaf(int _index = -1) - : index(_index) - { - } - bool operator==(const TreePathLeaf& rhs) const{ - return index == rhs.index; - } - bool operator!=(const TreePathLeaf& rhs) const{ - return index != rhs.index; - } -}; -bool Serialize(Serialization::IArchive& ar, TreePathLeaf& value, const char* name, const char* label); - -typedef std::vector TreePath; -typedef std::vector TreePathes; - -class PropertyTreeOperator -{ -public: - enum Type{ - NONE, - REPLACE, - ADD, - REMOVE - }; - - PropertyTreeOperator(); - ~PropertyTreeOperator(); - PropertyTreeOperator(const TreePath& path, PropertyRow* row); - void Serialize(Serialization::IArchive& ar); -private: - Type type_; - TreePath path_; - Serialization::SharedPtr row_; - int index_; - friend class PropertyTreeModel; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEOPERATOR_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyDialog.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyDialog.cpp deleted file mode 100644 index 87db4de1b0..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyDialog.cpp +++ /dev/null @@ -1,227 +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 "EditorCommon_precompiled.h" -#include "QPropertyDialog.h" -#include "QPropertyTree.h" -#include "Serialization/IArchive.h" -#include "Serialization/BinArchive.h" -#include "Serialization/JSONIArchive.h" -#include "Serialization/JSONOArchive.h" -#include -#include -#include - -#include - -#ifndef SERIALIZATION_STANDALONE -#include -#include -#else -namespace PathUtil -{ - string GetParentDirectory(const char* path) - { - const char* end = strrchr(path, '/'); - if (!end) - { - end = strrchr(path, '\\'); - } - if (end) - { - return string(path, end); - } - else - { - return string(); - } - } -}; -#endif - -#ifndef SERIALIZATION_STANDALONE -#include -#endif - -static string getFullStateFilename(const char* filename) -{ -#ifdef SERIALIZATION_STANDALONE - // use current folder - return filename; -#else - string path = GetIEditor()->GetResolvedUserFolder().toUtf8().data(); - if (!path.empty() && path[path.size() - 1] != '\\' && path[path.size() - 1] != '/') - { - path.push_back('\\'); - } - path += filename; - return path; -#endif -} - -bool QPropertyDialog::edit(Serialization::SStruct& ser, const char* title, const char* windowStateFilename, QWidget* parent) -{ - QPropertyDialog dialog(parent); - dialog.setSerializer(ser); - dialog.setWindowTitle(QString::fromLocal8Bit(title)); - dialog.setWindowStateFilename(windowStateFilename); - - return dialog.exec() == QDialog::Accepted; -} - -QPropertyDialog::QPropertyDialog(QWidget* parent) - : QDialog(parent) - , m_sizeHint(440, 500) - , m_layout(0) - , m_storeContent(false) -{ - connect(this, SIGNAL(accepted()), this, SLOT(onAccepted())); - connect(this, SIGNAL(rejected()), this, SLOT(onRejected())); - setModal(true); - setWindowModality(Qt::ApplicationModal); - - m_propertyTree = new QPropertyTree(this); - m_propertyTree->setExpandLevels(1); - - m_layout = new QBoxLayout(QBoxLayout::TopToBottom, this); - - m_layout->addWidget(m_propertyTree, 1); - QDialogButtonBox* buttons = new QDialogButtonBox(this); - buttons->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(buttons, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttons, SIGNAL(rejected()), this, SLOT(reject())); - m_layout->addWidget(buttons, 0); -} - -QPropertyDialog::~QPropertyDialog() -{ -} - -void QPropertyDialog::revert() -{ - if (m_propertyTree) - { - m_propertyTree->revert(); - } -} - -void QPropertyDialog::setSerializer(const Serialization::SStruct& ser) -{ - if (!m_serializer) - { - m_serializer.reset(new Serialization::SStruct()); - } - *m_serializer = ser; -} - -void QPropertyDialog::setWindowStateFilename(const char* windowStateFilename) -{ - m_windowStateFilename = windowStateFilename; -} - -void QPropertyDialog::setSizeHint(const QSize& size) -{ - m_sizeHint = size; -} - -void QPropertyDialog::setStoreContent(bool storeContent) -{ - m_storeContent = storeContent; -} - -QSize QPropertyDialog::sizeHint() const -{ - return m_sizeHint; -} - -void QPropertyDialog::setVisible(bool visible) -{ - QDialog::setVisible(visible); - - if (visible) - { - string fullStateFilename = getFullStateFilename(m_windowStateFilename.c_str()); - if (!fullStateFilename.empty()) - { - Serialization::JSONIArchive ia; - if (ia.load(fullStateFilename.c_str())) - { - ia(*this); - } - } - - m_backup.reset(new Serialization::BinOArchive()); - if (m_serializer && *m_serializer) - { - const Serialization::SStruct& ser = *m_serializer; - (*m_backup)(ser, "backup"); - m_propertyTree->attach(*m_serializer); - } - } -} - -void QPropertyDialog::onAccepted() -{ - string fullStateFilename = getFullStateFilename(m_windowStateFilename.c_str()); - if (!fullStateFilename.empty()) - { - Serialization::JSONOArchive oa; - oa(*this); - - QDir().mkdir(QString::fromLocal8Bit(PathUtil::GetParentDirectory(fullStateFilename.c_str()).c_str())); - oa.save(fullStateFilename.c_str()); - } -} - -void QPropertyDialog::onRejected() -{ - if (m_backup.get() && m_serializer.get() && *m_serializer) - { - // restore previous object state - Serialization::BinIArchive ia; - if (ia.open(m_backup->buffer(), m_backup->length())) - { - const Serialization::SStruct& ser = *m_serializer; - ia(ser, "backup"); - } - } -} - -void QPropertyDialog::setArchiveContext(Serialization::SContextLink* context) -{ - m_propertyTree->setArchiveContext(context); -} - -void QPropertyDialog::Serialize(Serialization::IArchive& ar) -{ - if (m_storeContent && m_serializer.get()) - { - ar(*m_serializer, "content"); - } - - QByteArray geometry; - if (ar.IsOutput()) - { - geometry = saveGeometry(); - } - std::vector geometryVec(geometry.begin(), geometry.end()); - ar(geometryVec, "geometry"); - if (ar.IsInput() && !geometryVec.empty()) - { - restoreGeometry(QByteArray(geometryVec.data(), (int)geometryVec.size())); - } - - ar(*m_propertyTree, "propertyTree"); -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyDialog.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyDialog.h deleted file mode 100644 index a295ec188f..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyDialog.h +++ /dev/null @@ -1,76 +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_EDITORCOMMON_QPROPERTYTREE_QPROPERTYDIALOG_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_QPROPERTYDIALOG_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "../EditorCommonAPI.h" -#include "Strings.h" -#include - -#include -#endif - -namespace Serialization -{ - struct SStruct; - struct SContextLink; - class BinOArchive; - class IArchive; -} - -class QPropertyTree; -class QBoxLayout; - -class EDITOR_COMMON_API QPropertyDialog - : public QDialog -{ - Q_OBJECT -public: - static bool edit(Serialization::SStruct& ser, const char* title, const char* windowStateFilename, QWidget* parent); - - QPropertyDialog(QWidget* parent); - ~QPropertyDialog(); - - void setSerializer(const Serialization::SStruct& ser); - void setArchiveContext(Serialization::SContextLink* context); - void setWindowStateFilename(const char* windowStateFilename); - void setSizeHint(const QSize& sizeHint); - void setStoreContent(bool storeContent); - - void revert(); - QBoxLayout* layout() { return m_layout; } - - void Serialize(Serialization::IArchive& ar); -protected slots: - void onAccepted(); - void onRejected(); - -protected: - QSize sizeHint() const override; - void setVisible(bool visible) override; -private: - QPropertyTree* m_propertyTree; - QBoxLayout* m_layout; - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - std::unique_ptr m_serializer; - std::unique_ptr m_backup; - string m_windowStateFilename; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - QSize m_sizeHint; - bool m_storeContent; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_QPROPERTYDIALOG_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTree.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTree.cpp deleted file mode 100644 index 0af0b8368a..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTree.cpp +++ /dev/null @@ -1,3083 +0,0 @@ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -/** -* wWidgets - Lightweight UI Toolkit. -* Copyright (C) 2009-2011 Evgeny Andreeshchev -* Alexander Kotliar -* -* This code is distributed under the MIT License: -* http://www.opensource.org/licenses/MIT -*/ - - -#include "EditorCommon_precompiled.h" -#include "QPropertyTree.h" -#include "PropertyDrawContext.h" -#include "Serialization.h" -#include "Serialization/Decorators/Range.h" -using Serialization::Range; -#include "PropertyTreeModel.h" -#include "QPropertyTreeStyle.h" - -#include "PropertyOArchive.h" -#include "PropertyIArchive.h" -#include "Unicode.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "PropertyTreeMenuHandler.h" - -#include "MathUtils.h" - -#include -// only for clipboard: -#include -#include -#include "PropertyRowPointer.h" -#include "PropertyRowContainer.h" -// ^^^ -#include "PropertyRowObject.h" -#include - -using Serialization::SStructs; - -void PropertyTreeMenuHandler::onMenuFilter() -{ - tree->startFilter(""); -} - -void PropertyTreeMenuHandler::onMenuFilterByName() -{ - tree->startFilter(filterName.c_str()); -} - -void PropertyTreeMenuHandler::onMenuFilterByValue() -{ - tree->startFilter(filterValue.c_str()); -} - -void PropertyTreeMenuHandler::onMenuFilterByType() -{ - tree->startFilter(filterType.c_str()); -} - -void PropertyTreeMenuHandler::onMenuUndo() -{ - tree->model()->undo(); -} - -void PropertyTreeMenuHandler::onMenuRedo() -{ - tree->model()->redo(); -} - -static PropertyRow* findFirstLeafPulledRow(PropertyRow* row) -{ - if (row->isLeaf() && - row->widgetPlacement() != PropertyRow::WIDGET_ICON && - row->widgetPlacement() != PropertyRow::WIDGET_NONE) - return row; - - for (int i = 0; i < row->count(); ++i) - { - PropertyRow* child = row->childByIndex(i); - if (!child) - continue; - if (!child->pulledUp()) - continue; - PropertyRow* leaf = findFirstLeafPulledRow(child); - if (leaf) - return leaf; - } - - return 0; -} - -static QMimeData* propertyRowToMimeData(PropertyRow* row, ConstStringList* constStrings) -{ - PropertyRow::setConstStrings(constStrings); - SharedPtr clonedRow(row->clone(constStrings)); - Serialization::BinOArchive oa; - PropertyRow::setConstStrings(constStrings); - if (!oa(clonedRow, "row", "Row")) { - PropertyRow::setConstStrings(0); - return 0; - } - PropertyRow::setConstStrings(0); - - QByteArray byteArray(oa.buffer(), (int)oa.length()); - QMimeData* mime = new QMimeData; - mime->setData("binary/crypropertytree", byteArray); - if (clonedRow) - { - PropertyRow* textRow = findFirstLeafPulledRow(row); - if (textRow) - mime->setText(QString::fromWCharArray(textRow->valueAsWString().c_str())); - } - return mime; -} - -static bool smartPaste(PropertyRow* dest, SharedPtr& source, PropertyTreeModel* model, bool onlyCheck) -{ - bool result = false; - // content of the pulled container has a priority over the node itself - PropertyRowContainer* destPulledContainer = static_cast(dest->pulledContainer()); - if ((destPulledContainer && strcmp(destPulledContainer->elementTypeName(), source->typeName()) == 0)) { - PropertyRow* elementRow = model->defaultType(destPulledContainer->elementTypeName()); - YASLI_ESCAPE(elementRow, return false); - if (strcmp(elementRow->typeName(), source->typeName()) == 0){ - result = true; - if (!onlyCheck){ - PropertyRow* dest = elementRow; - if (dest->isPointer() && !source->isPointer()){ - PropertyRowPointer* d = static_cast(dest); - SharedPtr newSourceRoot = static_cast(d->clone(model->constStrings()).get()); - source->swapChildren(newSourceRoot, model); - source = newSourceRoot; - } - destPulledContainer->add(source.get()); - } - } - } - else if ((source->isContainer() && dest->isContainer() && - strcmp(static_cast(source.get())->elementTypeName(), - static_cast(dest)->elementTypeName()) == 0) || - (!source->isContainer() && !dest->isContainer() && strcmp(source->typeName(), dest->typeName()) == 0)){ - result = true; - if (!onlyCheck){ - if (dest->isPointer() && !source->isPointer()){ - PropertyRowPointer* d = static_cast(dest); - SharedPtr newSourceRoot = static_cast(d->clone(model->constStrings()).get()); - source->swapChildren(newSourceRoot, model); - source = newSourceRoot; - } - const char* name = dest->name(); - const char* nameAlt = dest->label(); - source->setName(name); - source->setLabel(nameAlt); - if (dest->parent()) - dest->parent()->replaceAndPreserveState(dest, source, model); - else{ - dest->swapChildren(source, model); - source->clear(); - } - source->setLabelChanged(); - } - } - else if (dest->isContainer()){ - if (model){ - PropertyRowContainer* container = static_cast(dest); - PropertyRow* elementRow = model->defaultType(container->elementTypeName()); - YASLI_ESCAPE(elementRow, return false); - if (strcmp(elementRow->typeName(), source->typeName()) == 0){ - result = true; - if (!onlyCheck){ - PropertyRow* dest = elementRow; - if (dest->isPointer() && !source->isPointer()){ - PropertyRowPointer* d = static_cast(dest); - SharedPtr newSourceRoot = static_cast(d->clone(model->constStrings()).get()); - source->swapChildren(newSourceRoot, model); - source = newSourceRoot; - } - - container->add(source.get()); - } - } - container->setLabelChanged(); - } - } - - return result; -} - -static bool propertyRowFromMimeData(SharedPtr& row, const QMimeData* mimeData, ConstStringList* constStrings) -{ - PropertyRow::setConstStrings(constStrings); - QStringList formats = mimeData->formats(); - QByteArray array = mimeData->data("binary/crypropertytree"); - if (array.isEmpty()) - return 0; - Serialization::BinIArchive ia; - if (!ia.open(array.data(), array.size())) - return 0; - - if (!ia(row, "row", "Row")) - return false; - - PropertyRow::setConstStrings(0); - return true; - -} - -bool propertyRowFromClipboard(SharedPtr& row, ConstStringList* constStrings) -{ - const QMimeData* mime = QApplication::clipboard()->mimeData(); - if (!mime) - return false; - return propertyRowFromMimeData(row, mime, constStrings); -} - -void PropertyTreeMenuHandler::onMenuCopy() -{ - QMimeData* mime = propertyRowToMimeData(row, tree->model()->constStrings()); - if (mime) - QApplication::clipboard()->setMimeData(mime); -} - -void PropertyTreeMenuHandler::onMenuPaste() -{ - if (!tree->canBePasted(row)) - return; - PropertyRow* parent = row->parent(); - - tree->model()->rowAboutToBeChanged(row); - - SharedPtr source; - if (!propertyRowFromClipboard(source, tree->model()->constStrings())) - return; - - if (!smartPaste(row, source, tree->model(), false)) - return; - - tree->model()->rowChanged(parent ? parent : tree->model()->root()); -} - -class FilterEntry : public QLineEdit -{ -public: - FilterEntry(QPropertyTree* tree) - : QLineEdit(tree) - , tree_(tree) - { - } -protected: - - void keyPressEvent(QKeyEvent * ev) - { - if (ev->key() == Qt::Key_Escape || ev->key() == Qt::Key_Return) - { - ev->accept(); - tree_->setFocus(); - tree_->keyPressEvent(ev); - } - - if (ev->key() == Qt::Key_Backspace && text().isEmpty()) - { - tree_->setFilterMode(false); - } - QLineEdit::keyPressEvent(ev); - } -private: - QPropertyTree* tree_; -}; - -// --------------------------------------------------------------------------- - -DragWindow::DragWindow(QPropertyTree* tree) - : tree_(tree) - , offset_(0, 0) -{ - QWidget::setWindowFlags(Qt::ToolTip); - QWidget::setWindowOpacity(192.0f / 256.0f); -} - -void DragWindow::set(QPropertyTree* tree, PropertyRow* row, const QRect& rowRect) -{ - QRect rect = tree->rect(); - rect.setTopLeft(tree->mapToGlobal(rect.topLeft())); - - offset_ = rect.topLeft(); - - row_ = row; - rect_ = rowRect; -} - -void DragWindow::setWindowPos([[maybe_unused]] bool visible) -{ - QWidget::move(rect_.left() + offset_.x() - 3, rect_.top() + offset_.y() - 3 + tree_->area_.top()); - QWidget::resize(rect_.width() + 5, rect_.height() + 5); -} - -void DragWindow::show() -{ - setWindowPos(true); - QWidget::show(); -} - -void DragWindow::move(int deltaX, int deltaY) -{ - offset_ += QPoint(deltaX, deltaY); - setWindowPos(isVisible()); -} - -void DragWindow::hide() -{ - setWindowPos(false); - QWidget::hide(); -} - -struct DrawRowVisitor -{ - DrawRowVisitor(QPainter& painter) : painter_(painter) {} - - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, int index) - { - if (row->pulledUp() && row->visible(tree)) { - row->drawRow(painter_, tree, index, true); - row->drawRow(painter_, tree, index, false); - } - - return SCAN_CHILDREN_SIBLINGS; - } - -protected: - QPainter& painter_; -}; - -void DragWindow::drawRow(QPainter& p) -{ - QRect entireRowRect(0, 0, rect_.width() + 4, rect_.height() + 4); - - p.setBrush(tree_->palette().button()); - p.setPen(QPen(tree_->palette().color(QPalette::WindowText))); - p.drawRect(entireRowRect); - - QPoint leftTop = row_->rect().topLeft(); - int offsetX = aznumeric_cast(-leftTop.x() - tree_->treeStyle().firstLevelIndent * tree_->_defaultRowHeight() + 3); - int offsetY = -leftTop.y() + 3; - p.translate(offsetX, offsetY); - int rowIndex = 0; - if (row_->parent()) - rowIndex = row_->parent()->childIndex(row_); - row_->drawRow(p, tree_, 0, true); - row_->drawRow(p, tree_, 0, false); - DrawRowVisitor visitor(p); - row_->scanChildren(visitor, tree_); - p.translate(-offsetX, -offsetY); -} - -void DragWindow::paintEvent([[maybe_unused]] QPaintEvent* ev) -{ - QPainter p(this); - - drawRow(p); -} - -// --------------------------------------------------------------------------- - -class QPropertyTree::DragController -{ -public: - DragController(QPropertyTree* tree) - : tree_(tree) - , captured_(false) - , dragging_(false) - , before_(false) - , row_(0) - , clickedRow_(0) - , window_(tree) - , hoveredRow_(0) - , destinationRow_(0) - { - } - - void beginDrag(PropertyRow* clickedRow, PropertyRow* draggedRow, QPoint pt) - { - row_ = draggedRow; - clickedRow_ = clickedRow; - startPoint_ = pt; - lastPoint_ = pt; - captured_ = true; - dragging_ = false; - } - - bool dragOn(QPoint screenPoint) - { - if (dragging_) - window_.move(screenPoint.x() - lastPoint_.x(), screenPoint.y() - lastPoint_.y()); - - bool needCapture = false; - if (!dragging_ && (startPoint_ - screenPoint).manhattanLength() >= 5) - if (row_->canBeDragged()){ - needCapture = true; - QRect rect = row_->rect(); - rect = QRect(rect.topLeft() - tree_->offset_ + QPoint(aznumeric_cast(tree_->treeStyle().firstLevelIndent * tree_->_defaultRowHeight()), 0), - rect.bottomRight() - tree_->offset_); - - window_.set(tree_, row_, rect); - window_.move(screenPoint.x() - startPoint_.x(), screenPoint.y() - startPoint_.y()); - window_.show(); - dragging_ = true; - } - - if (dragging_){ - QPoint point = tree_->mapFromGlobal(screenPoint); - trackRow(point); - } - lastPoint_ = screenPoint; - return needCapture; - } - - void interrupt() - { - captured_ = false; - dragging_ = false; - row_ = 0; - window_.hide(); - } - - void trackRow(QPoint pt) - { - hoveredRow_ = 0; - destinationRow_ = 0; - - QPoint point = pt; - PropertyRow* row = tree_->rowByPoint(point); - if (!row || !row_) - return; - - row = row->nonPulledParent(); - if (!row->parent() || row->isChildOf(row_) || row == row_) - return; - - float pos = (point.y() - row->rect().top()) / float(row->rect().height()); - if (row_->canBeDroppedOn(row->parent(), row, tree_)){ - if (pos < 0.25f){ - destinationRow_ = row->parent(); - hoveredRow_ = row; - before_ = true; - return; - } - if (pos > 0.75f){ - destinationRow_ = row->parent(); - hoveredRow_ = row; - before_ = false; - return; - } - } - if (row_->canBeDroppedOn(row, 0, tree_)) - hoveredRow_ = destinationRow_ = row; - } - - void drawUnder(QPainter& painter) - { - if (dragging_ && destinationRow_ == hoveredRow_ && hoveredRow_){ - QRect rowRect = hoveredRow_->rect(); - rowRect.setLeft(aznumeric_cast(rowRect.left() + tree_->treeStyle().firstLevelIndent * tree_->_defaultRowHeight())); - QBrush brush(true ? tree_->palette().highlight() : tree_->palette().shadow()); - QColor brushColor = brush.color(); - QColor borderColor(brushColor.alpha() / 4, brushColor.red(), brushColor.green(), brushColor.blue()); - fillRoundRectangle(painter, brush, rowRect, borderColor, 6); - } - } - - void drawOver(QPainter& painter) - { - if (!dragging_) - return; - - QRect rowRect = row_->rect(); - - if (destinationRow_ != hoveredRow_ && hoveredRow_){ - const int tickSize = 4; - QRect hoveredRect = hoveredRow_->rect(); - hoveredRect.setLeft(aznumeric_cast(hoveredRect.left() + tree_->treeStyle().firstLevelIndent * tree_->_defaultRowHeight())); - - if (!before_){ // previous - QRect rect(hoveredRect.left() - 1, hoveredRect.bottom() - 1, hoveredRect.width(), 2); - QRect rectLeft(hoveredRect.left() - 1, hoveredRect.bottom() - tickSize, 2, tickSize * 2); - QRect rectRight(hoveredRect.right() - 1, hoveredRect.bottom() - tickSize, 2, tickSize * 2); - painter.fillRect(rect, tree_->palette().highlight()); - painter.fillRect(rectLeft, tree_->palette().highlight()); - painter.fillRect(rectRight, tree_->palette().highlight()); - } - else{ // next - QRect rect(hoveredRect.left() - 1, hoveredRect.top() - 1, hoveredRect.width(), 2); - QRect rectLeft(hoveredRect.left() - 1, hoveredRect.top() - tickSize, 2, tickSize * 2); - QRect rectRight(hoveredRect.right() - 1, hoveredRect.top() - tickSize, 2, tickSize * 2); - painter.fillRect(rect, tree_->palette().highlight()); - painter.fillRect(rectLeft, tree_->palette().highlight()); - painter.fillRect(rectRight, tree_->palette().highlight()); - } - } - } - - bool drop([[maybe_unused]] QPoint screenPoint) - { - bool rowLayoutChanged = false; - if (row_ && hoveredRow_){ - YASLI_ASSERT(destinationRow_); - clickedRow_->setSelected(false); - row_->dropInto(destinationRow_, destinationRow_ == hoveredRow_ ? 0 : hoveredRow_, tree_, before_); - rowLayoutChanged = true; - } - - captured_ = false; - dragging_ = false; - row_ = 0; - window_.hide(); - hoveredRow_ = 0; - destinationRow_ = 0; - return rowLayoutChanged; - } - - bool captured() const{ return captured_; } - bool dragging() const{ return dragging_; } - PropertyRow* draggedRow() { return row_; } -protected: - DragWindow window_; - QPropertyTree* tree_; - PropertyRow* row_; - PropertyRow* clickedRow_; - PropertyRow* hoveredRow_; - PropertyRow* destinationRow_; - QPoint startPoint_; - QPoint lastPoint_; - bool captured_; - bool dragging_; - bool before_; -}; - -// --------------------------------------------------------------------------- - -AZ_PUSH_DISABLE_WARNING(4335, "-Wunknown-warning-option") -QPropertyTree::QPropertyTree(QWidget* parent) - : QWidget(parent) - , sizeHint_(180, 180) - , model_(0) - , cursorX_(0) - , attachedPropertyTree_(0) - , autoHideAttachedPropertyTree_(false) - , autoRevert_(true) - , dragController_(new DragController(this)) - , leftBorder_(0) - , rightBorder_(0) - , filterMode_(false) - - , applyTime_(0) - , revertTime_(0) - , updateHeightsTime_(0) - , paintTime_(0) - , pressPoint_(-1, -1) - , pressDelta_(0, 0) - , pointerMovedSincePress_(false) - , lastStillPosition_(-1, -1) - , pressedRow_(0) - , capturedRow_(0) - , iconCache_(new IconXPMCache()) - , dragCheckMode_(false) - , dragCheckValue_(false) - , archiveContext_(0) - , outlineMode_(false) - , sizeToContent_(false) - , hideSelection_(false) - , zoomLevel_(10) - , validatorBlock_(new ValidatorBlock) - , style_(new QPropertyTreeStyle()) - - , aggregateMouseEvents_(false) - , aggregatedMouseEventCount_(0) -{ - setFocusPolicy(Qt::WheelFocus); - setMouseTracking(true); // need to receive mouseMoveEvent to update mouse cursor and tooltip - - scrollBar_ = new QScrollBar(Qt::Vertical, this); - connect(scrollBar_, SIGNAL(valueChanged(int)), this, SLOT(onScroll(int))); - - model_.reset(new PropertyTreeModel()); - model_->setExpandLevels(config_.expandLevels); - model_->setUndoEnabled(config_.undoEnabled); - model_->setFullUndo(config_.fullUndo); - - connect(model_.data(), SIGNAL(signalUpdated(const PropertyRows&, bool)), this, SLOT(onModelUpdated(const PropertyRows&, bool))); - connect(model_.data(), SIGNAL(signalPushUndo(PropertyTreeOperator*, bool*)), this, SLOT(onModelPushUndo(PropertyTreeOperator*, bool*))); - connect(model_.data(), SIGNAL(signalPushRedo(PropertyTreeOperator*, bool*)), this, SLOT(onModelPushRedo(PropertyTreeOperator*, bool*))); - //model_->signalPushUndo().connect(this, &QPropertyTree::onModelPushUndo); - - filterEntry_.reset(new FilterEntry(this)); - QObject::connect(filterEntry_.data(), SIGNAL(textChanged(const QString&)), this, SLOT(onFilterChanged(const QString&))); - filterEntry_->hide(); - - mouseStillTimer_ = new QTimer(this); - mouseStillTimer_->setSingleShot(true); - connect(mouseStillTimer_, SIGNAL(timeout()), this, SLOT(onMouseStillTimeout())); - - boldFont_.setBold(true); - backgroundColor_ = palette().color(QPalette::Window); -} -AZ_POP_DISABLE_WARNING - -QPropertyTree::~QPropertyTree() -{ - clearMenuHandlers(); -} - -bool QPropertyTree::onRowKeyDown(PropertyRow* row, const QKeyEvent* ev) -{ - PropertyTreeMenuHandler handler; - handler.row = row; - handler.tree = this; - - if (row->onKeyDown(this, ev)) - return true; - if (row->pulledContainer() && static_cast(row->pulledContainer())->onKeyDownContainer(this, ev)) - return true; - - // NOTE: If you add a new key here, you also have to check for it in rowProcessesKey - - switch (ev->key()){ - case Qt::Key_C: - if (!row->userNonCopyable() && ev->modifiers() == Qt::CTRL) - handler.onMenuCopy(); - return true; - case Qt::Key_V: - if (!row->userNonCopyable() && ev->modifiers() == Qt::CTRL) - handler.onMenuPaste(); - return true; - case Qt::Key_Z: - if (config_.undoEnabled) - { - if (ev->modifiers() == (Qt::SHIFT | Qt::CTRL)) - { - if (model()->canRedo()) - { - handler.onMenuRedo(); - } - return true; - } - else if (ev->modifiers() == Qt::CTRL) - { - if (model()->canUndo()) - { - handler.onMenuUndo(); - } - return true; - } - } - else - { - if (ev->modifiers() == (Qt::SHIFT | Qt::CTRL)) - { - emit signalRedo(); - } - else if (ev->modifiers() == Qt::CTRL) - { - emit signalUndo(); - } - - return true; - } - break; - case Qt::Key_Y: - if (!config_.undoEnabled) - { - if (model()->canRedo()) - { - handler.onMenuRedo(); - } - } - else - { - if (ev->modifiers() == Qt::CTRL) - { - emit signalRedo(); - } - } - return true; - break; - - case Qt::Key_F2: - if (ev->modifiers() == Qt::NoModifier) { - if (selectedRow()) { - PropertyActivationEvent act; - act.tree = this; - act.force = true; - act.reason = PropertyActivationEvent::REASON_KEYBOARD; - selectedRow()->onActivate(act); - } - } - break; - case Qt::Key_Menu: - { - if (ev->modifiers() == Qt::NoModifier) { - QMenu menu(this); - - if (onContextMenu(row, menu)){ - QRect rect(row->rect()); - QPoint pt = _toScreen(QPoint(rect.left() + rect.height(), rect.bottom())); - menu.exec(pt); - } - return true; - } - break; - } - } - - PropertyRow* focusedRow = model()->focusedRow(); - if (!focusedRow) - return false; - PropertyRow* parentRow = focusedRow->nonPulledParent(); - int x = parentRow->horizontalIndex(this, focusedRow); - int y = model()->root()->verticalIndex(this, parentRow); - PropertyRow* selectedRow = 0; - switch (ev->key()){ - case Qt::Key_Up: - if (filterMode_ && y == 0) { - setFilterMode(true); - } - else { - selectedRow = model()->root()->rowByVerticalIndex(this, --y); - if (selectedRow) - selectedRow = selectedRow->rowByHorizontalIndex(this, cursorX_); - } - break; - case Qt::Key_Down: - if (filterMode_ && filterEntry_->hasFocus()) { - setFocus(); - } - else { - selectedRow = model()->root()->rowByVerticalIndex(this, ++y); - if (selectedRow) - selectedRow = selectedRow->rowByHorizontalIndex(this, cursorX_); - } - break; - case Qt::Key_Left: - selectedRow = parentRow->rowByHorizontalIndex(this, cursorX_ = --x); - if (selectedRow == focusedRow && parentRow->canBeToggled(this) && parentRow->expanded()){ - expandRow(parentRow, false); - selectedRow = model()->focusedRow(); - } - break; - case Qt::Key_Right: - selectedRow = parentRow->rowByHorizontalIndex(this, cursorX_ = ++x); - if (selectedRow == focusedRow && parentRow->canBeToggled(this) && !parentRow->expanded()){ - expandRow(parentRow, true); - selectedRow = model()->focusedRow(); - } - break; - case Qt::Key_Home: - if (ev->modifiers() == Qt::CTRL) { - selectedRow = parentRow->rowByHorizontalIndex(this, cursorX_ = INT_MIN); - } - else { - selectedRow = model()->root()->rowByVerticalIndex(this, 0); - if (selectedRow) - selectedRow = selectedRow->rowByHorizontalIndex(this, cursorX_); - } - break; - case Qt::Key_End: - if (ev->modifiers() == Qt::CTRL) { - selectedRow = parentRow->rowByHorizontalIndex(this, cursorX_ = INT_MAX); - } - else { - selectedRow = model()->root()->rowByVerticalIndex(this, INT_MAX); - if (selectedRow) - selectedRow = selectedRow->rowByHorizontalIndex(this, cursorX_); - } - break; - case Qt::Key_Space: - if (config_.filterWhenType) - break; - case Qt::Key_Return: - if (focusedRow->canBeToggled(this)) - expandRow(focusedRow, !focusedRow->expanded()); - else { - PropertyActivationEvent e; - e.tree = this; - e.reason = e.REASON_KEYBOARD; - e.force = false; - focusedRow->onActivate(e); - } - break; - } - if (selectedRow){ - onRowSelected(std::vector(1, selectedRow), false, false); - return true; - } - return false; -} - -bool QPropertyTree::rowProcessesKey(PropertyRow* row, const QKeyEvent* ev) -{ - if (row->processesKey(this, ev)) - { - return true; - } - - if (row->pulledContainer() && static_cast(row->pulledContainer())->processesKeyContainer(this, ev)) - { - return true; - } - - int modifiedKey = ev->key() | ev->modifiers(); - - switch (modifiedKey) - { - case (Qt::CTRL | Qt::Key_Z): - case (Qt::CTRL | Qt::SHIFT | Qt::Key_Z) : - case Qt::Key_Y: - case (Qt::CTRL | Qt::Key_V): - case (Qt::CTRL | Qt::Key_C): - case (Qt::CTRL | Qt::Key_F): - case Qt::Key_Menu: - case Qt::Key_F2: - return true; - break; - - default: - break; - } - - switch (ev->key()) - { - case Qt::Key_Up: - case Qt::Key_Down: - case Qt::Key_Left: - case Qt::Key_Right: - case Qt::Key_Home: - case Qt::Key_End: - case Qt::Key_Return: - return true; - break; - - default: - break; - } - - return false; -} - -struct FirstIssueVisitor -{ - ValidatorEntryType entryType_; - PropertyRow* startRow_; - PropertyRow* result; - - FirstIssueVisitor(ValidatorEntryType type, PropertyRow* startRow) - : entryType_(type) - , startRow_(startRow) - , result() - { - } - - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, int) - { - if ((row->pulledUp() || row->pulledBefore()) && row->nonPulledParent() == startRow_) - return SCAN_SIBLINGS; - if (row->validatorCount()) { - if (const ValidatorEntry* validatorEntries = tree->_validatorBlock()->GetEntry(row->validatorIndex(), row->validatorCount())) { - for (int i = 0; i < row->validatorCount(); ++i) { - const ValidatorEntry* validatorEntry = validatorEntries + i; - if (validatorEntry->type == entryType_) { - result = row; - return SCAN_FINISHED; - } - } - } - } - return SCAN_CHILDREN_SIBLINGS; - } -}; - -void QPropertyTree::jumpToNextHiddenValidatorIssue(bool isError, PropertyRow* start) -{ - FirstIssueVisitor op(isError ? VALIDATOR_ENTRY_ERROR : VALIDATOR_ENTRY_WARNING, start); - start->scanChildren(op, this); - - PropertyRow* row = op.result; - - vector parents; - while (row && row->parent()) { - parents.push_back(row); - row = row->parent(); - } - for (int i = (int)parents.size() - 1; i >= 0; --i) { - if (!parents[i]->visible(this)) - break; - row = parents[i]; - } - if (row) - setSelectedRow(row); - - updateValidatorIcons(); - updateHeights(); -} - -static void rowsInBetween(vector* rows, PropertyRow* a, PropertyRow* b) -{ - if (!a) - return; - if (!b) - return; - vector pathA; - PropertyRow* rootA = a; - while (rootA->parent()) { - pathA.push_back(rootA); - rootA = rootA->parent(); - } - - vector pathB; - PropertyRow* rootB = b; - while (rootB->parent()) { - pathB.push_back(rootB); - rootB = rootB->parent(); - } - - if (rootA != rootB) - return; - - const PropertyRow* commonParent = rootA; - int maxDepth = min((int)pathA.size(), (int)pathB.size()); - for (int i = 0; i < maxDepth; ++i) { - PropertyRow* parentA = pathA[(int)pathA.size() - 1 - i]; - PropertyRow* parentB = pathB[(int)pathB.size() - 1 - i]; - if (parentA != parentB) { - int indexA = commonParent->childIndex(parentA); - int indexB = commonParent->childIndex(parentB); - int minIndex = min(indexA, indexB); - int maxIndex = max(indexA, indexB); - for (int j = minIndex; j <= maxIndex; ++j) - rows->push_back((PropertyRow*)commonParent->childByIndex(j)); - return; - } - commonParent = parentA; - } -} - -bool QPropertyTree::onRowLMBDown(PropertyRow* row, [[maybe_unused]] const QRect& rowRect, QPoint point, bool controlPressed, bool shiftPressed) -{ - pressPoint_ = point; - pressDelta_ = QPoint(0, 0); - pointerMovedSincePress_ = false; - row = model()->root()->hit(this, point); - if (row){ - if (!row->isRoot()) { - if (row->plusRect(this).contains(point) && toggleRow(row)) - return true; - if (row->validatorWarningIconRect(this).contains(point)) { - jumpToNextHiddenValidatorIssue(false, row); - return true; - } - if (row->validatorErrorIconRect(this).contains(point)) { - jumpToNextHiddenValidatorIssue(true, row); - return true; - } - } - - PropertyRow* rowToSelect = row; - while (rowToSelect && !rowToSelect->isSelectable()) - rowToSelect = rowToSelect->parent(); - - if (rowToSelect) { - if (!shiftPressed || !multiSelectable()) { - onRowSelected(std::vector(1, rowToSelect), multiSelectable() && controlPressed, true); - lastSelectedRow_ = rowToSelect; - } - else { - vector rowsToSelect; - - rowsInBetween(&rowsToSelect, lastSelectedRow_, rowToSelect); - onRowSelected(rowsToSelect, false, true); - } - } - } - - PropertyTreeModel::UpdateLock lock = model()->lockUpdate(); - row = model()->root()->hit(this, point); - if (row && !row->isRoot()){ - bool changed = false; - if (row->widgetRect(this).contains(point)) { - DragCheckBegin dragCheck = row->onMouseDragCheckBegin(); - if (dragCheck != DRAG_CHECK_IGNORE) { - dragCheckValue_ = dragCheck == DRAG_CHECK_SET; - dragCheckMode_ = true; - changed = row->onMouseDragCheck(this, dragCheckValue_); - } - } - - if (!dragCheckMode_) { - bool capture = row->onMouseDown(this, point, changed); - if (!changed){ - if (capture) - return true; - else if (row->widgetRect(this).contains(point)){ - if (row->widgetPlacement() != PropertyRow::WIDGET_ICON) - interruptDrag(); - PropertyActivationEvent e; - e.force = false; - e.tree = this; - e.clickPoint = point; - row->onActivate(e); - return false; - } - } - } - } - return false; -} - -void QPropertyTree::onRowLMBUp(PropertyRow* row, [[maybe_unused]] const QRect& rowRect, QPoint point) -{ - onMouseStill(point); - row->onMouseUp(this, point); - - if (!pointerMovedSincePress_ && (pressPoint_ - point).manhattanLength() < 1 && row->widgetRect(this).contains(point)) { - PropertyActivationEvent e; - e.tree = this; - e.clickPoint = point; - e.reason = e.REASON_RELEASE; - row->onActivate(e); - } -} - -void QPropertyTree::onRowRMBDown(PropertyRow* row, [[maybe_unused]] const QRect& rowRect, QPoint point) -{ - SharedPtr handle = row; - PropertyRow* menuRow = 0; - - if (row->isSelectable()){ - menuRow = row; - } - else{ - if (row->parent() && row->parent()->isSelectable()) - menuRow = row->parent(); - } - - if (menuRow) { - onRowSelected(std::vector(1, menuRow), false, true); - QMenu menu(this); - clearMenuHandlers(); - if (onContextMenu(menuRow, menu)) - menu.exec(point); - } -} - -void QPropertyTree::expandParents(PropertyRow* row) -{ - bool hasChanges = false; - typedef std::vector Parents; - Parents parents; - PropertyRow* p = row->nonPulledParent()->parent(); - while (p){ - parents.push_back(p); - p = p->parent(); - } - Parents::iterator it; - for (it = parents.begin(); it != parents.end(); ++it) { - PropertyRow* row = *it; - row->_setExpanded(true); - hasChanges = true; - } - if (hasChanges) { - updateValidatorIcons(); - updateHeights(); - } -} - - -void QPropertyTree::expandAll(PropertyRow* root) -{ - if (!root){ - root = model()->root(); - for (PropertyRows::iterator it = root->begin(); it != root->end(); ++it){ - PropertyRow* row = *it; - row->setExpandedRecursive(this, true); - } - root->setLayoutChanged(); - } - else - root->setExpandedRecursive(this, true); - - for (PropertyRow* r = root; r != 0; r = r->parent()) - r->setLayoutChanged(); - - updateHeights(); -} - -void QPropertyTree::collapseAll(PropertyRow* root) -{ - if (!root){ - root = model()->root(); - - for (PropertyRows::iterator it = root->begin(); it != root->end(); ++it){ - PropertyRow* row = *it; - row->setExpandedRecursive(this, false); - } - } - else{ - root->setExpandedRecursive(this, false); - PropertyRow* row = model()->focusedRow(); - while (row){ - if (root == row){ - model()->selectRow(row, true); - break; - } - row = row->parent(); - } - } - - for (PropertyRow* r = root; r != 0; r = r->parent()) - r->setLayoutChanged(); - - updateHeights(); -} - - -void QPropertyTree::expandRow(PropertyRow* row, bool expanded, bool updateHeights) -{ - bool hasChanges = false; - if (row->expanded() != expanded) { - row->_setExpanded(expanded); - hasChanges = true; - } - - for (PropertyRow* r = row; r != 0; r = r->parent()) - r->setLayoutChanged(); - - if (!row->expanded()){ - PropertyRow* f = model()->focusedRow(); - while (f){ - if (row == f){ - model()->selectRow(row, true); - break; - } - f = f->parent(); - } - } - - if (hasChanges) - updateValidatorIcons(); - if (hasChanges && updateHeights) - this->updateHeights(); -} - -void QPropertyTree::interruptDrag() -{ - dragController_->interrupt(); -} - -void QPropertyTree::updateHeights(bool recalculateTextSize) -{ - QFontMetrics fm(font()); - defaultRowHeight_ = max(16, int(fm.lineSpacing() * 1.666f)); // to fit at least 16x16 icons - - QElapsedTimer timer; - timer.start(); - - model()->root()->updateLabel(this, 0, false); - - QRect widgetRect = this->rect(); - - int scrollBarW = 16; - int lb = 1; - int rb = widgetRect.right() - lb - scrollBarW - 2; - int availableWidth = widgetRect.width() - 4 - scrollBarW; - bool force = recalculateTextSize || lb != leftBorder_ || rb != rightBorder_; - leftBorder_ = lb; - rightBorder_ = rb; - model()->root()->calculateMinimalSize(this, leftBorder_, availableWidth, force, 0, 0, 0); - - updateValidatorIcons(); - - int totalHeight = 0; - model()->root()->adjustVerticalPosition(this, totalHeight); - totalHeight += 4; - QPoint oldSize = size_; - size_.setY(totalHeight); - - updateScrollBar(); - - area_.setLeft(widgetRect.left() + 2); - area_.setRight(widgetRect.right() - 2 - scrollBarW); - area_.setTop(widgetRect.top() + 2); - area_.setBottom(widgetRect.bottom() - 2); - size_.setX(area_.width()); - - int filterAreaHeight = 0; - if (filterMode_) - { - filterAreaHeight = filterEntry_ ? filterEntry_->height() : 0; - area_.setTop(area_.top() + filterAreaHeight + 2 + 2); - } - - _arrangeChildren(); - - int contentHeight = totalHeight + filterAreaHeight + 4; - if (sizeToContent_) - { - setMaximumHeight(contentHeight); - setMinimumHeight(contentHeight); - } - else - { - setMaximumHeight(QWIDGETSIZE_MAX); - setMinimumHeight(0); - } - - update(); - updateHeightsTime_ = aznumeric_cast(timer.elapsed()); - - QSize contentSize = QSize(area_.width(), contentHeight); - if (contentSize_.height() != contentSize.height()) - { - contentSize_ = contentSize; - signalSizeChanged(); - } - else - { - contentSize_ = contentSize; - } -} - -void QPropertyTree::setSizeToContent(bool sizeToContent) -{ - if (sizeToContent != sizeToContent_) - { - sizeToContent_ = sizeToContent; - updateHeights(); - } -} - - -bool QPropertyTree::updateScrollBar() -{ - int pageSize = rect().height(); - offset_.setX(max(0, min(offset_.x(), max(0, size_.x() - area_.right() - 1)))); - offset_.setY(max(0, min(offset_.y(), max(0, size_.y() - pageSize)))); - - if (pageSize < size_.y()) - { - scrollBar_->setRange(0, size_.y() - pageSize); - scrollBar_->setSliderPosition(offset_.y()); - scrollBar_->setPageStep(pageSize); - scrollBar_->show(); - scrollBar_->move(rect().right() - scrollBar_->width(), 0); - scrollBar_->resize(scrollBar_->width(), height()); - return true; - } - else - { - scrollBar_->hide(); - return false; - } -} - -QPoint QPropertyTree::treeSize() const -{ - return size_ + (compact() ? QPoint(0, 0) : QPoint(8, 8)); -} - -void QPropertyTree::onScroll([[maybe_unused]] int pos) -{ - offset_.setY(scrollBar_->sliderPosition()); - _arrangeChildren(); - repaint(); -} - -void QPropertyTree::Serialize(IArchive& ar) -{ - model()->Serialize(ar, this); - - if (ar.IsInput()){ - ensureVisible(model()->focusedRow()); - updateAttachedPropertyTree(false); - updateHeights(); - signalSelected(); - } -} - -void QPropertyTree::ensureVisible(PropertyRow* row, bool update, bool considerChildren) -{ - if (row == 0) - return; - if (row->isRoot()) - return; - - expandParents(row); - - QRect rect = considerChildren ? row->rectIncludingChildren(this) : row->rect(); - if (rect.bottom() > area_.bottom() + offset_.y()){ - offset_.setY(max(0, rect.bottom() - area_.bottom())); - } - if (rect.top() < area_.top() + offset_.y()){ - offset_.setY(max(0, rect.top() - area_.top())); - } - updateScrollBar(); - if (update) - this->update(); -} - -void QPropertyTree::onRowSelected(const std::vector& rows, bool addSelection, bool adjustCursorPos) -{ - for (size_t i = 0; i < rows.size(); ++i) { - PropertyRow* row = rows[i]; - if (!row->isRoot()) { - bool addRowToSelection = !(addSelection && row->selected() && model()->selection().size() > 1) || i > 0; - bool exclusiveSelection = !addSelection && i == 0; - model()->selectRow(row, addRowToSelection, exclusiveSelection); - } - } - if (!rows.empty()) { - ensureVisible(rows.back(), true, false); - if (adjustCursorPos) - cursorX_ = rows.back()->nonPulledParent()->horizontalIndex(this, rows.back()); - } - updateAttachedPropertyTree(false); - signalSelected(); -} - -bool QPropertyTree::attach(const Serialization::SStructs& serializers) -{ - bool changed = false; - if (attached_.size() != serializers.size()) - changed = true; - else { - for (size_t i = 0; i < serializers.size(); ++i) { - if (attached_[i].serializer() != serializers[i]) { - changed = true; - break; - } - } - } - - // We can't perform plain copying here, as it was before: - // attached_ = serializers; - // ...as move forwarder calls copying constructor with non-const argument - // which invokes second templated constructor of Serializer, which is not what we need. - if (changed) { - attached_.assign(serializers.begin(), serializers.end()); - model_->clearUndo(); - } - - revertNoninterrupting(); - - return changed; -} - -void QPropertyTree::attach(const Serialization::SStruct& serializer) -{ - if (attached_.size() != 1 || attached_[0].serializer() != serializer) { - attached_.clear(); - attached_.push_back(Serialization::Object(serializer)); - model_->clearUndo(); - } - revert(); -} - -void QPropertyTree::attach(const Serialization::Object& object) -{ - attached_.clear(); - attached_.push_back(object); - - revert(); -} - -void QPropertyTree::detach() -{ - if (widget_) - widget_.reset(); - attached_.clear(); - model()->root()->clear(); - update(); -} - -int QPropertyTree::revertObjects(vector objectAddresses) -{ - int result = 0; - for (size_t i = 0; i < objectAddresses.size(); ++i) { - if (revertObject(objectAddresses[i])) - ++result; - } - return result; -} - -bool QPropertyTree::revertObject(void* objectAddress) -{ - PropertyRow* row = model()->root()->findByAddress(objectAddress); - if (row && row->isObject()) { - // TODO: - // revertObjectRow(row); - return true; - } - return false; -} - - -void QPropertyTree::revert() -{ - interruptDrag(); - widget_.reset(); - capturedRow_ = 0; - - if (!attached_.empty()) { - validatorBlock_->Clear(); - - QElapsedTimer timer; - timer.start(); - - PropertyOArchive oa(model_.data(), model_->root(), validatorBlock_.data()); - oa.SetOutlineMode(outlineMode_); - if (archiveContext_) - oa.SetInnerContext(archiveContext_); - oa.SetFilter(config_.filter); - - Objects::iterator it = attached_.begin(); - signalAboutToSerialize(oa); - (*it)(oa); - signalSerialized(oa); - - PropertyTreeModel model2; - if (it != attached_.end()) { - while (++it != attached_.end()){ - PropertyOArchive oa2(&model2, model2.root(), validatorBlock_.data()); - oa2.SetOutlineMode(outlineMode_); - Serialization::SContext treeContext(oa2, this); - if (archiveContext_) - oa2.SetInnerContext(archiveContext_); - oa2.SetFilter(config_.filter); - signalAboutToSerialize(oa2); - (*it)(oa2); - signalSerialized(oa2); - model_->root()->intersect(model2.root()); - } - } - revertTime_ = int(timer.elapsed()); - - if (attached_.size() != 1) - validatorBlock_->Clear(); - applyValidation(); - } - else - model_->clear(); - - if (filterMode_) { - if (model_->root()) - model_->root()->updateLabel(this, 0, false); - onFilterChanged(QString()); - } - else { - updateHeights(); - } - - update(); - updateAttachedPropertyTree(true); - - signalReverted(); -} - -struct ValidatorVisitor -{ - ValidatorVisitor(ValidatorBlock* validator) - : validator_(validator) - { - } - - ScanResult operator()(PropertyRow* row, [[maybe_unused]] QPropertyTree* tree, int) - { - const void* rowHandle = row->searchHandle(); - int index = 0; - int count = 0; - Serialization::TypeID typeID = row->typeId(); - if (validator_->FindHandleEntries(&index, &count, rowHandle, typeID)) - { - validator_->MarkAsUsed(index, count); - if (row->setValidatorEntry(index, count)) - row->setLabelChanged(); - } - else - { - if (row->setValidatorEntry(0, 0)) - row->setLabelChanged(); - } - - return SCAN_CHILDREN_SIBLINGS; - } - -protected: - ValidatorBlock* validator_; -}; - -void QPropertyTree::applyValidation() -{ - if (!validatorBlock_->IsEnabled()) - return; - - ValidatorVisitor visitor(validatorBlock_.data()); - model()->root()->scanChildren(visitor, this); - - int rootFirst = 0; - int rootCount = 0; - Serialization::TypeID typeID = model()->root()->typeId(); - // Gather all the items with unknown handle/type pair at root level. - validatorBlock_->MergeUnusedItemsWithRootItems(&rootFirst, &rootCount, model()->root()->searchHandle(), typeID); - model()->root()->setValidatorEntry(rootFirst, rootCount); - model()->root()->setLabelChanged(); -} - -void QPropertyTree::revertNoninterrupting() -{ - if (!capturedRow_) - revert(); -} - -void QPropertyTree::apply(bool continuousUpdate) -{ - QElapsedTimer timer; - timer.start(); - - if (!attached_.empty()) { - Objects::iterator it; - for (it = attached_.begin(); it != attached_.end(); ++it) { - PropertyIArchive ia(model_.data(), model_->root()); - Serialization::SContext treeContext(ia, this); - ia.SetFilter(config_.filter); - if (archiveContext_) - ia.SetInnerContext(archiveContext_); - signalAboutToSerialize(ia); - (*it)(ia); - signalSerialized(ia); - } - } - - if (!continuousUpdate) - signalChanged(); - else - signalContinuousChange(); - applyTime_ = aznumeric_cast(timer.elapsed()); -} - -void QPropertyTree::applyInplaceEditor() -{ - if (widget_) - widget_->commit(); -} - -bool QPropertyTree::spawnWidget(PropertyRow* row, bool ignoreReadOnly) -{ - if (!widget_ || widget_->row() != row || !widget_->actualWidget()->isVisible()){ - interruptDrag(); - setWidget(0); - PropertyRowWidget* newWidget = 0; - if ((ignoreReadOnly && row->userReadOnlyRecurse()) || !row->userReadOnly()) - newWidget = row->createWidget(this); - setWidget(newWidget); - return newWidget != 0; - } - return false; -} - -void QPropertyTree::addMenuHandler(PropertyRowMenuHandler* handler) -{ - menuHandlers_.push_back(handler); -} - -void QPropertyTree::clearMenuHandlers() -{ - for (size_t i = 0; i < menuHandlers_.size(); ++i) - { - PropertyRowMenuHandler* handler = menuHandlers_[i]; - delete handler; - } - menuHandlers_.clear(); -} - -static string quoteIfNeeded(const char* str) -{ - if (!str) - return string(); - if (strchr(str, ' ') != 0) { - string result; - result = "\""; - result += str; - result += "\""; - return result; - } - else { - return string(str); - } -} - -bool QPropertyTree::onContextMenu(PropertyRow* r, QMenu& menu) -{ - SharedPtr row(r); - PropertyTreeMenuHandler* handler = new PropertyTreeMenuHandler(); - addMenuHandler(handler); - handler->tree = this; - handler->row = row; - - PropertyRow::iterator it; - for (it = row->begin(); it != row->end(); ++it){ - PropertyRow* child = *it; - if (child->isContainer() && child->pulledUp()) - child->onContextMenu(menu, this); - } - row->onContextMenu(menu, this); - if (config_.undoEnabled){ - if (!menu.isEmpty()) - menu.addSeparator(); - QAction* undo = menu.addAction("Undo", handler, SLOT(onMenuUndo())); - undo->setEnabled(model()->canUndo()); - undo->setShortcut(QKeySequence("Ctrl+Z")); - - QAction* redo = menu.addAction("Redo", handler, SLOT(onMenuRedo())); - redo->setEnabled(model()->canRedo()); - redo->setShortcut(QKeySequence("Ctrl+Shift+Z")); - } - if (!menu.isEmpty()) - menu.addSeparator(); - - if (!row->userNonCopyable()){ - menu.addAction("Copy", handler, SLOT(onMenuCopy()), QKeySequence("Ctrl+C")); - - if(!row->userReadOnly()){ - QAction* paste = menu.addAction("Paste", handler, SLOT(onMenuPaste()), QKeySequence("Ctrl+V")); - paste->setEnabled(canBePasted(row)); - } - - menu.addSeparator(); - } - - menu.addAction("Filter...", handler, SLOT(onMenuFilter()), QKeySequence("Ctrl+F")); - QMenu* filter = menu.addMenu("Filter by"); - { - string nameFilter = "#"; - nameFilter += quoteIfNeeded(row->labelUndecorated()); - handler->filterName = nameFilter; - filter->addAction((string("Name:\t") + nameFilter).c_str(), handler, SLOT(onMenuFilterByName())); - - string valueFilter = "="; - valueFilter += quoteIfNeeded(row->valueAsString().c_str()); - handler->filterValue = valueFilter; - filter->addAction((string("Value:\t") + valueFilter).c_str(), handler, SLOT(onMenuFilterByValue())); - - string typeFilter = ":"; - typeFilter += quoteIfNeeded(row->typeNameForFilter(this)); - handler->filterType = typeFilter; - filter->addAction((string("Type:\t") + typeFilter).c_str(), handler, SLOT(onMenuFilterByType())); - } - -#if 0 - menu.addSeparator(); - menu.addAction(TRANSLATE("Decompose"), row).connect(this, &QPropertyTree::onRowMenuDecompose); -#endif - return true; -} - -void QPropertyTree::onRowMouseMove(PropertyRow* row, [[maybe_unused]] const QRect& rowRect, QPoint point) -{ - PropertyDragEvent e; - e.tree = this; - e.pos = point; - e.start = pressPoint_; - e.totalDelta = pressDelta_; - row->onMouseDrag(e); - update(); -} - - -bool QPropertyTree::canBePasted(PropertyRow* destination) -{ - SharedPtr source; - if (!propertyRowFromClipboard(source, model_->constStrings())) - return false; - - if (!smartPaste(destination, source, model(), true)) - return false; - return true; -} - -bool QPropertyTree::canBePasted(const char* destinationType) -{ - SharedPtr source; - if (!propertyRowFromClipboard(source, model()->constStrings())) - return false; - - bool result = strcmp(source->typeName(), destinationType) == 0; - return result; -} - -struct DecomposeProxy -{ - DecomposeProxy(SharedPtr& row) : row(row) {} - - void Serialize(IArchive& ar) - { - ar(row, "row", "Row"); - } - - SharedPtr& row; -}; - -void QPropertyTree::onRowMenuDecompose([[maybe_unused]] PropertyRow* row) -{ - // SharedPtr clonedRow = row->clone(); - // DecomposeProxy proxy(clonedRow); - // edit(SStruct(proxy), 0, IMMEDIATE_UPDATE, this); -} - -void QPropertyTree::onModelUpdated([[maybe_unused]] const PropertyRows& rows, bool needApply) -{ - if (widget_) - widget_.reset(); - - if (config_.immediateUpdate){ - if (needApply) - apply(false); - - if (autoRevert_) - revert(); - else { - updateHeights(); - updateAttachedPropertyTree(true); - if (!config_.immediateUpdate) - onSignalChanged(); - } - } - else { - update(); - } -} - -void QPropertyTree::onModelPushUndo([[maybe_unused]] PropertyTreeOperator* op, [[maybe_unused]] bool* handled) -{ - signalPushUndo(); -} - -void QPropertyTree::onModelPushRedo([[maybe_unused]] PropertyTreeOperator* op, [[maybe_unused]] bool* handled) -{ - signalPushRedo(); -} - -void QPropertyTree::setWidget(PropertyRowWidget* widget) -{ - if (widget_){ - widget_->setParent(0); - } - widget_.reset(); - model()->dismissUpdate(); - - if (widget) - { - QWidget* actualWidget = widget->actualWidget(); - if (actualWidget) - { - actualWidget->setParent(this); - actualWidget->setFocus(); - } - - widget_.reset(widget); - _arrangeChildren(); - - if (widget_) - { - widget_->showPopup(); - } - } -} - -bool QPropertyTree::hasFocusOrInplaceHasFocus() const -{ - if (hasFocus()) - return true; - - if (widget_ && widget_->actualWidget() && widget_->actualWidget()->hasFocus()) - return true; - - return false; -} - -void QPropertyTree::setFilterMode(bool inFilterMode) -{ - bool changed = filterMode_ != inFilterMode; - filterMode_ = inFilterMode; - - if (filterMode_) - { - filterEntry_->show(); - filterEntry_->setFocus(); - filterEntry_->selectAll(); - } - else - filterEntry_->hide(); - - if (changed) - { - onFilterChanged(QString()); - } -} - -void QPropertyTree::startFilter(const char* filter) -{ - setFilterMode(true); - filterEntry_->setText(filter); - onFilterChanged(filter); -} - -void QPropertyTree::_arrangeChildren() -{ - if (widget_){ - PropertyRow* row = widget_->row(); - if (row->visible(this)){ - QWidget* w = widget_->actualWidget(); - YASLI_ASSERT(w); - if (w){ - QRect rect = row->widgetRect(this); - rect = QRect(rect.topLeft() - offset_ + area_.topLeft(), - rect.bottomRight() - offset_ + area_.topLeft()); - w->move(rect.topLeft()); - w->resize(rect.size()); - if (!w->isVisible()){ - w->show(); - w->setFocus(); - } - } - else{ - //YASLI_ASSERT(w); - } - } - else{ - widget_.reset(); - } - } - - if (filterEntry_) { - QSize size = rect().size(); - const int padding = 2; - QRect pos(padding, padding, size.width() - padding * 2, filterEntry_->height()); - filterEntry_->move(pos.topLeft()); - filterEntry_->resize(pos.size() - QSize(scrollBar_ ? scrollBar_->width() : 0, 0)); - } -} - - - -void QPropertyTree::setExpandLevels(int levels) -{ - config_.expandLevels = levels; - model()->setExpandLevels(levels); -} - -PropertyRow* QPropertyTree::selectedRow() -{ - const PropertyTreeModel::Selection &sel = model()->selection(); - if (sel.empty()) - return 0; - return model()->rowFromPath(sel.front()); -} - -int QPropertyTree::selectedRowCount() const -{ - return (int)model()->selection().size(); -} - -PropertyRow* QPropertyTree::selectedRowByIndex(int index) -{ - std::vector result; - const PropertyTreeModel::Selection &sel = model()->selection(); - if (size_t(index) >= sel.size()) - return 0; - - return model()->rowFromPath(sel[index]); -} - -bool QPropertyTree::getSelectedObject(Serialization::Object* object) -{ - const PropertyTreeModel::Selection &sel = model()->selection(); - if (sel.empty()) - return 0; - PropertyRow* row = model()->rowFromPath(sel.front()); - while (row && !row->isObject()) - row = row->parent(); - if (!row) - return false; - - if (row->isObject()) { - PropertyRowObject* obj = static_cast(row); - *object = obj->object(); - return true; - } - else { - return false; - } -} - -QPoint QPropertyTree::_toScreen(QPoint point) const -{ - QPoint pt(point.x() - offset_.x() + area_.left(), - point.y() - offset_.y() + area_.top()); - - return mapToGlobal(pt); -} - -bool QPropertyTree::setSelectedRow(PropertyRow* row) -{ - TreeSelection sel; - if (row) - sel.push_back(model()->pathFromRow(row)); - if (model()->selection() != sel) { - model()->setSelection(sel); - if (row) - ensureVisible(row); - updateAttachedPropertyTree(false); - repaint(); - return true; - } - return false; -} - -bool QPropertyTree::selectByAddress(const void* addr, bool keepSelectionIfChildSelected) -{ - if (model()->root()) { - PropertyRow* row = model()->root()->findByAddress(addr); - - bool keepSelection = false; - if (keepSelectionIfChildSelected && row && !model()->selection().empty()) { - keepSelection = true; - TreeSelection::const_iterator it; - for (it = model()->selection().begin(); it != model()->selection().end(); ++it){ - PropertyRow* selectedRow = model()->rowFromPath(*it); - if (!selectedRow) - continue; - if (!selectedRow->isChildOf(row)){ - keepSelection = false; - break; - } - } - } - - if (!keepSelection) - return setSelectedRow(row); - } - return false; -} - -bool QPropertyTree::selectByAddresses(const void* const* addresses, size_t addressCount, bool keepSelectionIfChildSelected) -{ - bool result = false; - if (model()->root()) { - bool keepSelection = false; - vector rows; - for (size_t i = 0; i < addressCount; ++i) { - const void* addr = addresses[i]; - PropertyRow* row = model()->root()->findByAddress(addr); - - if (keepSelectionIfChildSelected && row && !model()->selection().empty()) { - keepSelection = true; - TreeSelection::const_iterator it; - for (it = model()->selection().begin(); it != model()->selection().end(); ++it){ - PropertyRow* selectedRow = model()->rowFromPath(*it); - if (!selectedRow) - continue; - if (!selectedRow->isChildOf(row)){ - keepSelection = false; - break; - } - } - } - - if (row) - rows.push_back(row); - } - - if (!keepSelection) { - TreeSelection sel; - for (size_t j = 0; j < rows.size(); ++j) { - PropertyRow* row = rows[j]; - if (row) - sel.push_back(model()->pathFromRow(row)); - } - if (model()->selection() != sel) { - model()->setSelection(sel); - if (!rows.empty()) - ensureVisible(rows.back()); - update(); - result = true; - if (attachedPropertyTree_) - updateAttachedPropertyTree(false); - } - } - } - return result; -} - -void QPropertyTree::setUndoEnabled(bool enabled, bool full) -{ - config_.undoEnabled = enabled; - config_.fullUndo = full; - model()->setUndoEnabled(enabled); - model()->setFullUndo(full); -} - -void QPropertyTree::attachPropertyTree(QPropertyTree* propertyTree) -{ - if (attachedPropertyTree_) - disconnect(attachedPropertyTree_, SIGNAL(signalChanged()), this, SLOT(onAttachedTreeChanged())); - attachedPropertyTree_ = propertyTree; - if (attachedPropertyTree_) - connect(attachedPropertyTree_, SIGNAL(signalChanged()), this, SLOT(onAttachedTreeChanged())); - updateAttachedPropertyTree(true); -} - -void QPropertyTree::detachPropertyTree() -{ - attachPropertyTree(0); -} - -void QPropertyTree::setAutoHideAttachedPropertyTree(bool autoHide) -{ - autoHideAttachedPropertyTree_ = autoHide; -} - -void QPropertyTree::getSelectionSerializers(Serialization::SStructs* serializers) -{ - TreeSelection::const_iterator i; - for (i = model()->selection().begin(); i != model()->selection().end(); ++i){ - PropertyRow* row = model()->rowFromPath(*i); - if (!row) - continue; - - - while (row && ((row->pulledUp() || row->pulledBefore()) || row->isLeaf())) { - row = row->parent(); - } - if (outlineMode_) { - PropertyRow* topmostContainerElement = 0; - PropertyRow* r = row; - while (r && r->parent()) { - if (r->parent()->isContainer()) - topmostContainerElement = r; - r = r->parent(); - } - if (topmostContainerElement != 0) - row = topmostContainerElement; - } - Serialization::SStruct ser = row->serializer(); - - if (ser) - serializers->push_back(ser); - } -} - -void QPropertyTree::updateAttachedPropertyTree(bool revert) -{ - if (attachedPropertyTree_) { - Serialization::SStructs serializers; - getSelectionSerializers(&serializers); - if (!attachedPropertyTree_->attach(serializers) && revert) - attachedPropertyTree_->revertNoninterrupting(); - if (autoHideAttachedPropertyTree_) - attachedPropertyTree_->setVisible(!serializers.empty()); - } -} - -struct FilterVisitor -{ - const QPropertyTree::RowFilter& filter_; - - FilterVisitor(const QPropertyTree::RowFilter& filter) - : filter_(filter) - { - } - - static void markChildrenAsBelonging(PropertyRow* row, bool belongs) - { - int count = int(row->count()); - for (int i = 0; i < count; ++i) - { - PropertyRow* child = row->childByIndex(i); - child->setBelongsToFilteredRow(belongs); - - markChildrenAsBelonging(child, belongs); - } - } - - static bool hasMatchingChildren(PropertyRow* row) - { - int numChildren = (int)row->count(); - for (int i = 0; i < numChildren; ++i) - { - PropertyRow* child = row->childByIndex(i); - if (!child) - continue; - if (child->matchFilter()) - return true; - if (hasMatchingChildren(child)) - return true; - } - return false; - } - - ScanResult operator()(PropertyRow* row, QPropertyTree* tree) - { - const char* label = row->labelUndecorated(); - Serialization::string value = row->valueAsString(); - - bool matchFilter = filter_.match(label, filter_.NAME_VALUE, 0, 0) || filter_.match(value.c_str(), filter_.NAME_VALUE, 0, 0); - if (matchFilter && filter_.typeRelevant(filter_.NAME)) - filter_.match(label, filter_.NAME, 0, 0); - if (matchFilter && filter_.typeRelevant(filter_.VALUE)) - matchFilter = filter_.match(value.c_str(), filter_.VALUE, 0, 0); - if (matchFilter && filter_.typeRelevant(filter_.TYPE)) - matchFilter = filter_.match(row->typeNameForFilter(tree), filter_.TYPE, 0, 0); - - int numChildren = int(row->count()); - if (matchFilter) { - if (row->pulledBefore() || row->pulledUp()) { - // treat pulled rows as part of parent - PropertyRow* parent = row->parent(); - parent->setMatchFilter(true); - markChildrenAsBelonging(parent, true); - parent->setBelongsToFilteredRow(false); - } - else { - markChildrenAsBelonging(row, true); - row->setBelongsToFilteredRow(false); - row->setLayoutChanged(); - row->setLabelChanged(); - } - } - else { - bool belongs = hasMatchingChildren(row); - row->setBelongsToFilteredRow(belongs); - if (belongs) { - tree->expandRow(row, true, false); - for (int i = 0; i < numChildren; ++i) { - PropertyRow* child = row->childByIndex(i); - if (child->pulledUp()) - child->setBelongsToFilteredRow(true); - } - } - else { - row->_setExpanded(false); - row->setLayoutChanged(); - } - } - - row->setMatchFilter(matchFilter); - return SCAN_CHILDREN_SIBLINGS; - } - -protected: - string labelStart_; -}; - - - -void QPropertyTree::RowFilter::parse(const char* filter) -{ - for (int i = 0; i < NUM_TYPES; ++i) { - start[i].clear(); - substrings[i].clear(); - tillEnd[i] = false; - } - - YASLI_ESCAPE(filter != 0, return); - - vector filterBuf(filter, filter + strlen(filter) + 1); - for (size_t i = 0; i < filterBuf.size(); ++i) - filterBuf[i] = tolower(filterBuf[i]); - - const char* str = &filterBuf[0]; - - Type type = NAME_VALUE; - while (true) - { - bool fromStart = false; - while (*str == '^') { - fromStart = true; - ++str; - } - - const char* tokenStart = str; - - if (*str == '\"') - { - ++str; - while (*str != '\0' && *str != '\"') - ++str; - } - else - { - while (*str != '\0' && *str != ' ' && *str != '=' && *str != ':' && *str != '#') - ++str; - } - if (str != tokenStart) { - if (*tokenStart == '\"' && *str == '\"') { - start[type].assign(tokenStart + 1, str); - tillEnd[type] = true; - ++str; - } - else - { - if (fromStart) - start[type].assign(tokenStart, str); - else - substrings[type].push_back(string(tokenStart, str)); - } - } - while (*str == ' ') - ++str; - if (*str == '#') { - type = NAME; - ++str; - } - else if (*str == '=') { - type = VALUE; - ++str; - } - else if (*str == ':') { - type = TYPE; - ++str; - } - else if (*str == '\0') - break; - } -} - -bool QPropertyTree::RowFilter::match(const char* textOriginal, Type type, size_t* matchStart, size_t* matchEnd) const -{ - YASLI_ESCAPE(textOriginal, return false); - - char* text; - { - size_t textLen = strlen(textOriginal); - text = (char*)alloca((textLen + 1)); - memcpy(text, textOriginal, (textLen + 1)); - for (char* p = text; *p; ++p) - *p = tolower(*p); - } - - const string &startForType = this->start[type]; - if (tillEnd[type]){ - if (startForType == text) { - if (matchStart) - *matchStart = 0; - if (matchEnd) - *matchEnd = startForType.size(); - return true; - } - else - return false; - } - - const vector &substringsForType = this->substrings[type]; - - const char* startPos = text; - - if (matchStart) - *matchStart = 0; - if (matchEnd) - *matchEnd = 0; - if (!startForType.empty()) { - if (strncmp(text, startForType.c_str(), startForType.size()) != 0){ - //_freea(text); - return false; - } - if (matchEnd) - *matchEnd = startForType.size(); - startPos += startForType.size(); - } - - size_t numSubstrings = substringsForType.size(); - for (size_t i = 0; i < numSubstrings; ++i) { - const char* substr = strstr(startPos, substringsForType[i].c_str()); - if (!substr){ - return false; - } - startPos += substringsForType[i].size(); - if (matchStart && i == 0 && startForType.empty()) { - *matchStart = substr - text; - } - if (matchEnd) - *matchEnd = substr - text + substringsForType[i].size(); - } - return true; -} - -void QPropertyTree::onFilterChanged([[maybe_unused]] const QString& text) -{ - QByteArray arr = filterEntry_->text().toLocal8Bit(); - const char* filterStr = filterMode_ ? arr.data() : ""; - rowFilter_.parse(filterStr); - FilterVisitor visitor(rowFilter_); - model()->root()->scanChildrenBottomUp(visitor, this); - updateHeights(); -} - -void QPropertyTree::drawFilteredString(QPainter& p, const wchar_t* text, RowFilter::Type type, const QFont* font, const QRect& rect, const QColor& textColor, bool pathEllipsis, bool center) const -{ - int textLen = (int)wcslen(text); - - if (textLen == 0) - return; - - string textStr(fromWideChar(text)); - QString str(textStr.c_str()); - QFontMetrics fm(*font); - QRect textRect = rect; - int alignment; - if (center) - alignment = Qt::AlignHCenter | Qt::AlignVCenter; - else { - if (pathEllipsis && textRect.width() < fm.horizontalAdvance(str)) - alignment = Qt::AlignRight | Qt::AlignVCenter; - else - alignment = Qt::AlignLeft | Qt::AlignVCenter; - } - - if (filterMode_) { - size_t hiStart = 0; - size_t hiEnd = 0; - bool matched = rowFilter_.match(textStr.c_str(), type, &hiStart, &hiEnd) && hiStart != hiEnd; - if (!matched && (type == RowFilter::NAME || type == RowFilter::VALUE)) - matched = rowFilter_.match(textStr.c_str(), RowFilter::NAME_VALUE, &hiStart, &hiEnd); - if (matched && hiStart != hiEnd) { - QRectF boxFull; - QRectF boxStart; - QRectF boxEnd; - - boxFull = fm.boundingRect(textRect, alignment, str); - - if (hiStart > 0) - boxStart = fm.boundingRect(textRect, alignment, str.left(hiStart)); - else { - boxStart = fm.boundingRect(textRect, alignment, str); - boxStart.setWidth(0.0f); - } - boxEnd = fm.boundingRect(textRect, alignment, str.left(hiEnd)); - - QColor highlightColor, highlightBorderColor; - { - highlightColor = palette().color(QPalette::Highlight); - int h, s, v; - highlightColor.getHsv(&h, &s, &v); - h -= 175; - if (h < 0) - h += 360; - highlightColor.setHsv(h, min(255, int(s * 1.33f)), v, 255); - highlightBorderColor.setHsv(h, aznumeric_cast(s * 0.5f), v, 255); - } - - int left = int(boxFull.left() + boxStart.width()) - 1; - int top = int(boxFull.top()); - int right = int(boxFull.left() + boxEnd.width()); - int bottom = int(boxFull.top() + boxEnd.height()); - QRect highlightRect(left, top, right - left, bottom - top); - QBrush br(highlightColor); - p.setBrush(br); - p.setPen(highlightBorderColor); - bool oldAntialiasing = p.renderHints().testFlag(QPainter::Antialiasing); - p.setRenderHint(QPainter::Antialiasing, true); - - QRect intersectedHighlightRect = rect.intersected(highlightRect); - p.drawRoundedRect(intersectedHighlightRect, 4.0, 4.0); - p.setRenderHint(QPainter::Antialiasing, oldAntialiasing); - } - } - - QBrush textBrush(textColor); - p.setBrush(textBrush); - p.setPen(textColor); - QFont previousFont = p.font(); - p.setFont(*font); - p.drawText(textRect, alignment, str, 0); - p.setFont(previousFont); -} - -void QPropertyTree::_drawRowLabel(QPainter& p, const wchar_t* text, const QFont* font, const QRect& rect, const QColor& textColor) const -{ - drawFilteredString(p, text, RowFilter::NAME, font, rect, textColor, false, false); -} - -void QPropertyTree::_drawRowValue(QPainter& p, const wchar_t* text, const QFont* font, const QRect& rect, const QColor& textColor, bool pathEllipsis, bool center) const -{ - drawFilteredString(p, text, RowFilter::VALUE, font, rect, textColor, pathEllipsis, center); -} - -struct DrawVisitor -{ - DrawVisitor(QPainter& painter, const QRect& area, int scrollOffset, bool selectionPass) - : area_(area) - , painter_(painter) - , offset_(0) - , scrollOffset_(scrollOffset) - , lastParent_(0) - , selectionPass_(selectionPass) - {} - - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, int index) - { - if (row->visible(tree) && ((!row->parent() || (row->parent()->expanded() && !lastParent_)) || row->pulledUp())){ - QRect rect = row->rect(); - if (rect.top() > scrollOffset_ + area_.height()) - lastParent_ = row->parent(); - - int height = row->heightIncludingChildren(); - if ((height == USHRT_MAX || rect.top() + height > scrollOffset_) && rect.width() > 0) - row->drawRow(painter_, tree, index, selectionPass_); - - return SCAN_CHILDREN_SIBLINGS; - } - else - return SCAN_SIBLINGS; - } - -protected: - QPainter& painter_; - QRect area_; - int offset_; - int scrollOffset_; - PropertyRow* lastParent_; - bool selectionPass_; -}; - -QSize QPropertyTree::sizeHint() const -{ - if (sizeToContent_) - return minimumSize(); - else - return sizeHint_; -} - -bool QPropertyTree::event(QEvent* ev) -{ - if (ev->type() == QEvent::ShortcutOverride) - { - if (!widget_) - { - PropertyRow* row = model()->focusedRow(); - if (row) - { - QKeyEvent* keyEvent = static_cast(ev); - bool keyWillBeProcessed = false; - - int modifiedKey = keyEvent->key() | keyEvent->modifiers(); - switch (modifiedKey) - { - case (Qt::Key_F | Qt::CTRL): - case Qt::Key_Escape: - keyWillBeProcessed = true; - break; - - default: - keyWillBeProcessed = rowProcessesKey(row, keyEvent); - break; - } - - if (keyWillBeProcessed) - { - ev->accept(); - return true; - } - } - } - } - - return QWidget::event(ev); -} - -void QPropertyTree::paintEvent([[maybe_unused]] QPaintEvent* ev) -{ - QElapsedTimer timer; - timer.start(); - QPainter painter(this); - QRect clientRect = this->rect(); - - int clientHeight = clientRect.height(); - backgroundColor_ = palette().color(QPalette::Window); - painter.fillRect(clientRect, QBrush(backgroundColor_)); - - painter.translate(-offset_.x(), -offset_.y()); - - if (dragController_->captured()) - dragController_->drawUnder(painter); - - painter.translate(area_.left(), area_.top()); - - if (model()->root()) { - DrawVisitor selectionOp(painter, area_, offset_.y(), true); - model()->root()->scanChildren(selectionOp, this); - - DrawVisitor op(painter, area_, offset_.y(), false); - op(model()->root(), this, 0); - model()->root()->scanChildren(op, this); - } - - painter.translate(-area_.left(), -area_.top()); - painter.translate(offset_.x(), offset_.y()); - - //painter.setClipRect(rect()); - - if (size_.y() > clientHeight) - { - const int shadowHeight = int(_defaultRowHeight() * 0.3f); - QColor color1(0, 0, 0, 0); - QColor color2(0, 0, 0, 96); - - int visibleAreaWidth = area_.width() + 5; - - QRect upperRect(rect().left() + 1, rect().top(), visibleAreaWidth - 2, shadowHeight); - QLinearGradient upperGradient(upperRect.left(), upperRect.top(), upperRect.left(), upperRect.bottom()); - upperGradient.setColorAt(0.0f, color2); - upperGradient.setColorAt(1.0f, color1); - painter.fillRect(upperRect, QBrush(upperGradient)); - - QLinearGradient upperEdgeGradient(upperRect.left(), upperRect.top(), upperRect.left(), upperRect.bottom() + shadowHeight); - upperEdgeGradient.setColorAt(0.0f, color2); - upperEdgeGradient.setColorAt(1.0f, color1); - painter.fillRect(QRect(rect().left(), rect().top(), 1, shadowHeight * 2 + 1), QBrush(upperEdgeGradient)); - painter.fillRect(QRect(visibleAreaWidth - 1, rect().top(), 1, shadowHeight * 2 + 1), QBrush(upperEdgeGradient)); - - QRect lowerRect(rect().left() + 1, rect().bottom() - shadowHeight / 2, visibleAreaWidth - 2, shadowHeight / 2 + 1); - QLinearGradient lowerGradient(lowerRect.left(), lowerRect.top(), lowerRect.left(), lowerRect.bottom()); - lowerGradient.setColorAt(0.0f, color1); - lowerGradient.setColorAt(1.0f, color2); - QBrush lowerBrush(lowerGradient); - painter.fillRect(lowerRect, lowerGradient); - - QLinearGradient lowerEdgeGradient(lowerRect.left(), lowerRect.top() - shadowHeight, lowerRect.left(), lowerRect.bottom()); - lowerEdgeGradient.setColorAt(0.0f, color1); - lowerEdgeGradient.setColorAt(1.0f, color2); - painter.fillRect(QRect(rect().left(), rect().bottom() - shadowHeight * 2, 1, shadowHeight * 2 + 1), QBrush(lowerEdgeGradient)); - painter.fillRect(QRect(visibleAreaWidth - 1, rect().bottom() - shadowHeight * 2, 1, shadowHeight * 2 + 1), QBrush(lowerEdgeGradient)); - } - - if (dragController_->captured()) { - painter.translate(-offset_); - dragController_->drawOver(painter); - painter.translate(offset_); - } - else{ - // if(model()->focusedRow() != 0 && model()->focusedRow()->isRoot() && tree_->hasFocus()){ - // clientRect.left += 2; clientRect.top += 2; - // clientRect.right -= 2; clientRect.bottom -= 2; - // DrawFocusRect(dc, &clientRect); - // } - } - paintTime_ = aznumeric_cast(timer.elapsed()); -} - -QPropertyTree::HitTest QPropertyTree::hitTest(PropertyRow* row, const QPoint& pointInWindowSpace, const QRect& rowRect) -{ - QPoint point = pointToRootSpace(pointInWindowSpace); - - if (!row->hasVisibleChildren(this) && row->plusRect(this).contains(point)) - return TREE_HIT_PLUS; - - if (row->textRect(this).contains(point)) - return TREE_HIT_TEXT; - - if (rowRect.contains(point)) - return TREE_HIT_ROW; - - return TREE_HIT_NONE; - -} - -PropertyRow* QPropertyTree::rowByPoint(const QPoint& pt) -{ - if (!model_->root()) - return 0; - if (!area_.contains(pt)) - return 0; - return model_->root()->hit(this, pointToRootSpace(pt)); -} - -QPoint QPropertyTree::pointToRootSpace(const QPoint& point) const -{ - return QPoint(point.x() + offset_.x() - area_.left(), point.y() + offset_.y() - area_.top()); -} - -QPoint QPropertyTree::pointFromRootSpace(const QPoint& point) const -{ - return QPoint(point.x() - offset_.x() + area_.left(), point.y() - offset_.y() + area_.top()); -} - - -void QPropertyTree::moveEvent(QMoveEvent* ev) -{ - QWidget::moveEvent(ev); -} - -void QPropertyTree::resizeEvent(QResizeEvent* ev) -{ - QWidget::resizeEvent(ev); - - updateHeights(); -} - -void QPropertyTree::mousePressEvent(QMouseEvent* ev) -{ - //QWidget::mousePressEvent(ev); - setFocus(Qt::MouseFocusReason); - - if (ev->button() == Qt::LeftButton) - { - PropertyRow* row = rowByPoint(ev->pos()); - if (row && !row->isSelectable()) - row = row->parent(); - if (row){ - if (onRowLMBDown(row, row->rect(), pointToRootSpace(ev->pos()), ev->modifiers().testFlag(Qt::ControlModifier), ev->modifiers().testFlag(Qt::ShiftModifier))) { - capturedRow_ = row; - lastStillPosition_ = pointToRootSpace(ev->pos()); - } - else if (!dragCheckMode_){ - row = rowByPoint(ev->pos()); - PropertyRow* draggedRow = row; - while (draggedRow && (!draggedRow->isSelectable() || draggedRow->pulledUp() || draggedRow->pulledBefore())) - draggedRow = draggedRow->parent(); - if (draggedRow && !draggedRow->userReadOnly() && !widget_){ - dragController_->beginDrag(row, draggedRow, ev->globalPos()); - } - } - } - update(); - } - else if (ev->button() == Qt::RightButton) - { - QPoint point = ev->pos(); - PropertyRow* row = rowByPoint(point); - if (row){ - model()->setFocusedRow(row); - update(); - - onRowRMBDown(row, row->rect(), _toScreen(pointToRootSpace(point))); - } - else{ - QRect rect = this->rect(); - onRowRMBDown(model()->root(), rect, _toScreen(pointToRootSpace(point))); - } - } - else if (ev->button() == Qt::MiddleButton) - { - QPoint point = ev->pos(); - PropertyRow* row = rowByPoint(point); - if (row){ - switch (hitTest(row, point, row->rect())){ - case TREE_HIT_PLUS: - break; - case TREE_HIT_NONE: - default: - model()->setFocusedRow(row); - update(); - break; - } - - } - } -} - -void QPropertyTree::mouseReleaseEvent(QMouseEvent* ev) -{ - QWidget::mouseReleaseEvent(ev); - - if (ev->button() == Qt::LeftButton) - { - if (dragController_->captured()){ - if (dragController_->drop(QCursor::pos())) - updateHeights(); - else - update(); - } - if (dragCheckMode_) { - dragCheckMode_ = false; - } - else { - QPoint point = ev->pos(); - if (capturedRow_){ - QRect rowRect = capturedRow_->rect(); - onRowLMBUp(capturedRow_, rowRect, pointToRootSpace(ev->pos())); - mouseStillTimer_->stop(); - capturedRow_ = 0; - update(); - } - } - } - else if (ev->button() == Qt::RightButton) - { - - } - - unsetCursor(); -} - -void QPropertyTree::focusInEvent(QFocusEvent* ev) -{ - QWidget::focusInEvent(ev); - widget_.reset(); -} - -void QPropertyTree::keyPressEvent(QKeyEvent* ev) -{ - // NOTE: if you add any new key processing in here, make sure you update QPropertyTree::event() to handle - // it in the ShortcutOverride event. Otherwise, MainWindow/other shortcuts might take priority and eat it before - // it reaches this function. - - if (ev->key() == Qt::Key_F && ev->modifiers() == Qt::CTRL) { - setFilterMode(true); - } - - if (filterMode_) { - if (ev->key() == Qt::Key_Escape && ev->modifiers() == Qt::NoModifier) { - setFilterMode(false); - } - } - - bool result = false; - if (!widget_) { - PropertyRow* row = model()->focusedRow(); - if (row) - onRowKeyDown(row, ev); - } - update(); - if (!result) - QWidget::keyPressEvent(ev); -} - - -void QPropertyTree::mouseDoubleClickEvent(QMouseEvent* ev) -{ - QWidget::mouseDoubleClickEvent(ev); - - QPoint point = ev->pos(); - PropertyRow* row = rowByPoint(point); - if (row){ - PropertyActivationEvent e; - e.tree = this; - e.force = true; - e.reason = e.REASON_DOUBLECLICK; - PropertyRow* nonPulledParent = row; - while (nonPulledParent && nonPulledParent->pulledUp()) - nonPulledParent = nonPulledParent->parent(); - - if (row->widgetRect(this).contains(pointToRootSpace(point))){ - if (!row->onActivate(e)) - toggleRow(nonPulledParent); - } - else if (!toggleRow(row)) { - if (!row->onActivate(e)) - if (!toggleRow(nonPulledParent)) { - // activate first visible inline row - for (size_t i = 0; i < row->count(); ++i) { - PropertyRow* child = row->childByIndex(i); - if (child && child->pulledUp() && child->visible(this)) { - child->onActivate(e); - break; - } - } - } - } - } -} - -void QPropertyTree::onMouseStillTimeout() -{ - onMouseStill(mapFromGlobal(QCursor::pos())); -} - -void QPropertyTree::onMouseStill(QPoint point) -{ - if (capturedRow_) { - PropertyDragEvent e; - e.tree = this; - e.pos = point; - e.start = pressPoint_; - - capturedRow_->onMouseStill(e); - lastStillPosition_ = e.pos; - } -} - -void QPropertyTree::flushAggregatedMouseEvents() -{ - if (aggregatedMouseEventCount_ > 0) { - bool gotPendingEvent = aggregatedMouseEventCount_ > 1; - aggregatedMouseEventCount_ = 0; - if (gotPendingEvent && lastMouseMoveEvent_.data()) - mouseMoveEvent(lastMouseMoveEvent_.data()); - } -} - -void QPropertyTree::mouseMoveEvent(QMouseEvent* ev) -{ - if (ev->type() == QEvent::MouseMove && aggregateMouseEvents_) { - lastMouseMoveEvent_.reset(new QMouseEvent(QEvent::MouseMove, ev->localPos(), ev->windowPos(), ev->screenPos(), ev->button(), ev->buttons(), ev->modifiers())); - ev = lastMouseMoveEvent_.data(); - ++aggregatedMouseEventCount_; - if (aggregatedMouseEventCount_ > 1) - return; - } - - QCursor newCursor = QCursor(Qt::ArrowCursor); - QString newToolTip; - if (dragController_->captured() && !ev->buttons().testFlag(Qt::LeftButton)) - dragController_->interrupt(); - if (dragController_->captured()){ - QPoint pos = QCursor::pos(); - if (dragController_->dragOn(pos)) { - // SetCapture - } - update(); - } - else{ - QPoint point = ev->pos(); - PropertyRow* row = rowByPoint(point); - if (row && dragCheckMode_ && row->widgetRect(this).contains(pointToRootSpace(point))) { - row->onMouseDragCheck(this, dragCheckValue_); - } - else if (capturedRow_){ - onRowMouseMove(capturedRow_, QRect(), pointToRootSpace(point)); - if (config_.sliderUpdateDelay >= 0 && !mouseStillTimer_->isActive()) - mouseStillTimer_->start(config_.sliderUpdateDelay); - - if (cursor().shape() == Qt::BlankCursor) - { - pressDelta_ += pointToRootSpace(ev->pos()) - pressPoint_; - pointerMovedSincePress_ = true; - AzQtComponents::SetCursorPos(mapToGlobal(pointFromRootSpace(pressPoint_))); - } - else - { - pressDelta_ = pointToRootSpace(ev->pos()) - pressPoint_; - } - } - - PropertyRow* hoverRow = row; - if (capturedRow_) - hoverRow = capturedRow_; - PropertyHoverInfo hover; - if (hoverRow) { - QPoint pointInRootSpace = pointToRootSpace(point); - if (hoverRow->getHoverInfo(&hover, pointInRootSpace, this)) { - newCursor = hover.cursor; - newToolTip = hover.toolTip; - - PropertyRow* tooltipRow = hoverRow; - while (newToolTip.isEmpty() && tooltipRow->parent() && (tooltipRow->pulledUp() || tooltipRow->pulledBefore())) { - // check if parent of inlined property has a tooltip instead - tooltipRow = tooltipRow->parent(); - if (tooltipRow->getHoverInfo(&hover, pointInRootSpace, this)) - newToolTip = hover.toolTip; - } - } - - if (hoverRow->validatorWarningIconRect(this).contains(pointToRootSpace(point))) { - newCursor = QCursor(Qt::PointingHandCursor); - newToolTip = "Jump to next warning"; - } - if (hoverRow->validatorErrorIconRect(this).contains(pointToRootSpace(point))) { - newCursor = QCursor(Qt::PointingHandCursor); - newToolTip = "Jump to next error"; - } - } - } - setCursor(newCursor); - if (toolTip() != newToolTip) - setToolTip(newToolTip); - if (newToolTip.isEmpty()) - QToolTip::hideText(); -} - -void QPropertyTree::wheelEvent(QWheelEvent* ev) -{ - QWidget::wheelEvent(ev); - - float delta = ev->angleDelta().ry() / 360.0f; - if (ev->modifiers() & Qt::CTRL) { - if (delta > 0) - zoomLevel_ += 1; - else - zoomLevel_ -= 1; - if (zoomLevel_ < 8) - zoomLevel_ = 8; - if (zoomLevel_ > 30) - zoomLevel_ = 30; - float scale = zoomLevel_ * 0.1f; - QFont font; - font.setPointSizeF(font.pointSizeF() * scale); - setFont(font); - font.setBold(true); - boldFont_ = font; - - updateHeights(true); - } - else { - if (scrollBar_->isVisible() && scrollBar_->isEnabled()) - scrollBar_->setValue(scrollBar_->value() + -ev->angleDelta().y()); - } -} - -bool QPropertyTree::toggleRow(PropertyRow* row) -{ - if (!row->canBeToggled(this)) - return false; - expandRow(row, !row->expanded()); - updateHeights(); - return true; -} - -bool QPropertyTree::_isDragged(const PropertyRow* row) const -{ - if (!dragController_->dragging()) - return false; - if (dragController_->draggedRow() == row) - return true; - return false; -} - -bool QPropertyTree::_isCapturedRow(const PropertyRow* row) const -{ - return capturedRow_ == row; -} - -void QPropertyTree::setValueColumnWidth(float valueColumnWidth) -{ - if (style_->valueColumnWidth != valueColumnWidth) - { - style_->valueColumnWidth = valueColumnWidth; - updateHeights(); - update(); - } -} - -QPropertyTree::QPropertyTree(const QPropertyTree&) -{ -} - - -QPropertyTree& QPropertyTree::operator=(const QPropertyTree&) -{ - return *this; -} - -void QPropertyTree::onAttachedTreeChanged() -{ - revert(); -} - -struct ValidatorIconVisitor -{ - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, int) - { - row->resetValidatorIcons(); - if (row->validatorCount()) { - bool hasErrors = false; - bool hasWarnings = false; - if (const ValidatorEntry* validatorEntries = tree->_validatorBlock()->GetEntry(row->validatorIndex(), row->validatorCount())) { - for (int i = 0; i < row->validatorCount(); ++i) { - const ValidatorEntry* validatorEntry = validatorEntries + i; - if (validatorEntry->type == VALIDATOR_ENTRY_ERROR) - hasErrors = true; - else if (validatorEntry->type == VALIDATOR_ENTRY_WARNING) - hasWarnings = true; - } - } - - if (hasErrors || hasWarnings) - { - PropertyRow* lastClosedParent = 0; - PropertyRow* current = row->parent(); - bool lastWasPulled = row->pulledUp() || row->pulledBefore(); - while (current && current->parent()) { - if (!current->expanded() && !lastWasPulled && current->visible(tree)) - lastClosedParent = current; - lastWasPulled = current->pulledUp() || current->pulledBefore(); - current = current->parent(); - } - if (lastClosedParent) - lastClosedParent->addValidatorIcons(hasWarnings, hasErrors); - } - } - return SCAN_CHILDREN_SIBLINGS; - } -}; - -void QPropertyTree::updateValidatorIcons() -{ - if (!validatorBlock_->IsEnabled()) - return; - ValidatorIconVisitor op; - model()->root()->scanChildren(op, this); - model()->root()->setLabelChangedToChildren(); -} - -void QPropertyTree::setTreeStyle(const QPropertyTreeStyle& style) -{ - *style_ = style; - updateHeights(true); -} - -void QPropertyTree::setPackCheckboxes(bool pack) -{ - style_->packCheckboxes = pack; - updateHeights(true); -} - -bool QPropertyTree::packCheckboxes() const -{ - return style_->packCheckboxes; -} - -void QPropertyTree::setCompact(bool compact) -{ - style_->compact = compact; - update(); -} - -bool QPropertyTree::compact() const -{ - return style_->compact; -} - -void QPropertyTree::setRowSpacing(float rowSpacing) -{ - style_->rowSpacing = rowSpacing; -} - -float QPropertyTree::rowSpacing() const -{ - return style_->rowSpacing; -} - -float QPropertyTree::valueColumnWidth() const -{ - return style_->valueColumnWidth; -} - -void QPropertyTree::setFullRowMode(bool fullRowMode) -{ - style_->fullRowMode = fullRowMode; - update(); -} - -bool QPropertyTree::fullRowMode() const -{ - return style_->fullRowMode; -} - -bool QPropertyTree::containsErrors() const -{ - return validatorBlock_->ContainsErrors(); -} - -void QPropertyTree::focusFirstError() -{ - jumpToNextHiddenValidatorIssue(true, model()->root()); -} - -void QPropertyTree::setBackgroundColor(const QColor& backgroundColor) -{ - backgroundColor_ = backgroundColor; -} - -#include -#include - -// vim:ts=4 sw=4: diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTree.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTree.h deleted file mode 100644 index e5c6caec99..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTree.h +++ /dev/null @@ -1,528 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_QPROPERTYTREE_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_QPROPERTYTREE_H -#pragma once - - - -#if !defined(Q_MOC_RUN) -#include "../EditorCommonAPI.h" -#include "ConstStringList.h" -#include "ValidatorBlock.h" -#include -#include "Serialization/Serializer.h" -#include "Serialization/IArchive.h" -#include "Serialization/Pointers.h" -#include "Serialization/Object.h" -#include "PropertyRow.h" -#include -#include -#endif - -namespace Serialization -{ - struct SContextLink; - class IClassFactory; -} - -class QMenu; -class QLineEdit; -class QScrollBar; - -struct Color; -class TreeImpl; -class PropertyTreeModel; -class PopupMenuItem; -class PropertyTreeModel; -class PropertyRow; -class PropertyRowWidget; -class PropertyTreeOperator; -class Entry; -struct IconXPMCache; - - -// --------------------------------------------------------------------------- -struct QPropertyTreeStyle; -struct PropertyTreeConfig -{ - bool immediateUpdate; - bool hideUntranslated; - bool showContainerIndices; - bool showContainerIndexLabels; - bool containerIndicesZeroBased; - bool filterWhenType; - int filter; - int sliderUpdateDelay; - int expandLevels; - bool undoEnabled; - bool fullUndo; - bool multiSelection; - bool copyPasteEnabled; - - PropertyTreeConfig() - : immediateUpdate(true) - , hideUntranslated(true) - , showContainerIndices(true) - , showContainerIndexLabels(false) - , containerIndicesZeroBased(true) - , filterWhenType(true) - , filter(0) - , sliderUpdateDelay(25) - , undoEnabled(true) - , fullUndo(true) - , multiSelection(true) - , copyPasteEnabled(true) - { - } -}; - -// --------------------------------------------------------------------------- - -struct PropertyRowMenuHandler; - -class DragWindow : public QWidget -{ - Q_OBJECT -public: - DragWindow(QPropertyTree* tree); - - void set(QPropertyTree* tree, PropertyRow* row, const QRect& rowRect); - void setWindowPos(bool visible); - void show(); - void move(int deltaX, int deltaY); - void hide(); - - void drawRow(QPainter& p); - void paintEvent(QPaintEvent* ev); - -protected: - bool useLayeredWindows_; - PropertyRow* row_; - QRect rect_; - QPropertyTree* tree_; - QPoint offset_; -}; - -class EDITOR_COMMON_API QPropertyTree : public QWidget -{ - Q_OBJECT -public: - explicit QPropertyTree(QWidget* parent = nullptr); - ~QPropertyTree(); - - // Used to attach an object to a PropertyTree widget. Attached object should implement - // Serialize method. Example of usage: - // - // struct MyType - // { - // void Serialize(Serialization::IArchive& ar); - // }; - // MyType object; - // - // propertyTree->attach(Serialization::SStruct(object)); - // - // Attached object will be serialized through PropertyOArchive to populate the tree. On - // every input made to the tree attached object will be deserialized through - // PropertyIArchive and serialized back again through PropertyOArchive to make sure that - // tree content is up-to-date. - // Property archives can be identified by calling ar.IsEdit(). - // SStruct stores a pointer to an actual object that should either outlive property tree - // or be detached on destruction. - void attach(const Serialization::SStruct& serializer); - // This form attaches an array of SStruct-s. This is used to edit multiple objects - // simultaneously. Only shared properties will be shown (i.e. intersection of all - // properties). Properties with different values will be shown as "..." or a gray - // checkbox. - bool attach(const Serialization::SStructs& serializers); - // Used for two-trees setup. In this case leader tree acts as an outliner, that shows - // top level of the data (either by using setOutlineMode or setting different filter). - // Attached, follower tree then shows properties ot the item selected in the main tree. - // Temporary structures (e.g. created on the stack) should not be used in this mode - // (except for decorators), as this may cause access to deallocated object when - // selecting it in the tree. - void attachPropertyTree(QPropertyTree* propertyTree); - void detachPropertyTree(); - void setAutoHideAttachedPropertyTree(bool autoHide); - // Effectively clears the tree. - void detach(); - bool attached() const { return !attached_.empty(); } - - // Forces serialization of attached object to update properties. Can be used to update - // property tree when attached object was changed for some reason. - void revert(); - // Same as revert(), except that it will but interrupt editing or mouse action in - // progress. - void revertNoninterrupting(); - // Forces deserialization of attached objects from property items. - void apply(bool continuousUpdate); - // Useful to apply edit boxes that are being edited at the moment. - // May be needed when click on toolbar button doesn't steal the focus, leaving input - // data effectively not saved. - void applyInplaceEditor(); - - // Reduces width of the tree by removing expansion arrow/plus on the first level of the - // tree (first level is always expanded). - void setCompact(bool compact); - bool compact() const; - // Puts checkboxes into two columns when possible. - void setPackCheckboxes(bool pack); - bool packCheckboxes() const; - // Changes distance between rows, multiplier of row height. - void setRowSpacing(float rowSpacing); - float rowSpacing() const; - // Sets default width of the value column, 0..1 (relative to widget width) - void setValueColumnWidth(float valueColumnWidth); - float valueColumnWidth() const; - // Allows to override background color, useful when placing on tabs or panels that have - // have different background. - void setBackgroundColor(const QColor& color); - const QColor& backgroundColor() const { return backgroundColor_; } - // Set number of levels to be expanded by default. Note that this function should be - // invoked before first call to attach attach() to have an effect. - void setExpandLevels(int levels); - // Can be used to control if container(array) elements have numbered labels. - void setShowContainerIndices(bool showContainerIndices) { config_.showContainerIndices = showContainerIndices; } - bool showContainerIndices() const{ return config_.showContainerIndices; } - // Can be used to control if container(array) elements should prepend the number to the existing label - void setShowContainerIndexLabels(bool showContainerIndexLabels) { config_.showContainerIndexLabels = showContainerIndexLabels; } - bool showContainerIndexLabels() const{ return config_.showContainerIndexLabels; } - // Can be used to control if container(array) elements should be zero- (default) or one-based - void setContainerIndicesZeroBased(bool containerIndicesZeroBased) { config_.containerIndicesZeroBased = containerIndicesZeroBased; } - bool containerIndicesZeroBased() const{ return config_.containerIndicesZeroBased; } - // Allows control of copy/paste functionality - void setCopyPasteEnabled(bool copyPasteEnabled) { config_.copyPasteEnabled = copyPasteEnabled; } - bool copyPasteEnabled() const{ return config_.copyPasteEnabled; } - - // Limits the rate at which sliders emit change signal. - void setSliderUpdateDelay(int delayMS) { config_.sliderUpdateDelay = delayMS; } - - // Limit number of mouse-movement updates per-frame. Used to prevent large tree updates - // from draining all the idle time. - void setAggregateMouseEvents(bool aggregate) { aggregateMouseEvents_ = aggregate; } - void flushAggregatedMouseEvents(); - - // Can be used to disable internal undo. - void setUndoEnabled(bool enabled, bool full = false); - // This can be used to disable automatic serialization after each deserialization call. - // May be useful to prevent double-revert when signalChange is connected to some - // external data model, which fires an event that reverts tree automatically. - void setAutoRevert(bool autoRevert) { autoRevert_ = autoRevert; } - // Default size. - void setSizeHint(const QSize& size) { sizeHint_ = size; } - // Sets minimal size of the widget to the size of the visible content of the tree. - void setSizeToContent(bool sizeToContent); - bool sizeToContent() const{ return sizeToContent_; } - // Retrieves size of the content, doesn't require sizeToContent to be set. - QSize contentSize() const{ return contentSize_; } - // When set filtering is started just by typing in the property tree - void setFilterWhenType(bool filterWhenType) { config_.filterWhenType = filterWhenType; } - - // Outline mode hides content of the elements of the container (excepted for - // inlined/pulled-up properties). Can be used together with second property - // tree through attachPropertyTree. - void setOutlineMode(bool outlineMode) { outlineMode_ = outlineMode; } - bool outlineMode() const{ return outlineMode_; } - // Hide selection when widget is out of focus. Disables selection for parent of inline items. - void setHideSelection(bool hideSelection) { hideSelection_ = hideSelection; } - bool hideSelection() const{ return hideSelection_; } - // Can be used to disable selection of multiple properties at the same time. - void setMultiSelection(bool multiSelection) { config_.multiSelection = multiSelection; } - bool multiSelection() const{ return config_.multiSelection; } - - // Sets head of the context-list. Can be used to pass additional data to nested decorators. - void setArchiveContext(Serialization::SContextLink* context) { archiveContext_ = context; } - // Sets archive filter. Filter is a bit mask stored within archive that can be used to - // affect behavior of serialization. For example one can have two trees that shows - // different portions of the same object. - void setFilter(int filter) { config_.filter = filter; } - - // This methods returns array of SStruct-s for all selected properties. - // This is useful for manual implementation of attachPropertyTree behavior - // with type filtering or special logic. - void getSelectionSerializers(Serialization::SStructs* serializers); - // Can be used to select once serialized object(s) in the tree. - bool selectByAddress(const void*, bool keepSelectionIfChildSelected = false); - bool selectByAddresses(const void* const* addresses, size_t addressCount, bool keepSelectionIfChildSelected); - // Can be used to query information about selection in the tree. - bool setSelectedRow(PropertyRow* row); - PropertyRow* selectedRow(); - int selectedRowCount() const; - PropertyRow* selectedRowByIndex(int index); - - // Reports if serialized data contains errors. Errors are reported - // through IArchive::Error() method. - bool containsErrors() const; - void focusFirstError(); - - void ensureVisible(PropertyRow* row, bool update = true, bool considerChildren = true); - void expandRow(PropertyRow* row, bool expanded = true, bool updateHeights = true); - - // PropertyTreeStyle used to customize visual appearance of the property tree - const QPropertyTreeStyle& treeStyle() const{ return *style_; } - void setTreeStyle(const QPropertyTreeStyle& style); - - // Config used to store behavioral settings - const PropertyTreeConfig& config() const{ return config_; } - - // Instance of PropertyTree can be serialized. In this case the expansion state - // of the rows and list of selected rows will be saved (not the property values). - void Serialize(Serialization::IArchive& ar); - - // OBSOLETE: Serialization::Object will be gone - void attach(const Serialization::Object& object); - int revertObjects(vector objectAddresses); - bool revertObject(void* objectAddress); -signals: - // Emited for every finished changed of the value. E.g. when you drag a slider, - // signalChanged will be invoked when you release a mouse button. - void signalChanged(); - // Used fast-pace changes, like movement of the slider before mouse gets released. - void signalContinuousChange(); - // Invoked whenever selection changed. - void signalSelected(); - // Invoked after each revert() call (can be caused by user intput). - void signalReverted(); - // Invoked before any change is going to occur and can be used to store current version - // of data for own undo stack. - void signalPushUndo(); - void signalPushRedo(); - - // Called before and after serialization is invoked. Can be used to update context list - // in archive. - void signalAboutToSerialize(Serialization::IArchive& ar); - void signalSerialized(Serialization::IArchive& ar); - - // OBSOLETE: do not use - void signalObjectChanged(const Serialization::Object& obj); - - // Called when visual size of the tree changes, i.e. when things are deserialized and - // and when rows are expanded/collapsed. - void signalSizeChanged(); - - // Called when undo/redo are triggered via keyboard shortcut - void signalUndo(); - void signalRedo(); -public slots: - void expandAll(PropertyRow* root = 0); - void collapseAll(PropertyRow* root = 0); - void onAttachedTreeChanged(); -public: - // internal methods: - void setFullRowMode(bool fullRowMode); - bool fullRowMode() const; - void setHideUntranslated(bool hideUntranslated) { config_.hideUntranslated = hideUntranslated; } - bool hideUntranslated() const{ return config_.hideUntranslated; } - void setImmediateUpdate(bool immediateUpdate) { config_.immediateUpdate = immediateUpdate; } - bool immediateUpdate() const{ return config_.immediateUpdate; } - int _defaultRowHeight() const { return defaultRowHeight_; } - PropertyTreeModel* model() { return model_.data(); } - const PropertyTreeModel* model() const { return model_.data(); } - - QPoint treeSize() const; - int leftBorder() const { return leftBorder_; } - int rightBorder() const { return rightBorder_; } - bool multiSelectable() const { return attachedPropertyTree_ != 0 || config_.multiSelection; } - void expandParents(PropertyRow* row); - bool spawnWidget(PropertyRow* row, bool ignoreReadOnly); - bool getSelectedObject(Serialization::Object* object); - void onSignalChanged() { signalChanged(); } - - void onRowSelected(const std::vector& row, bool addSelection, bool adjustCursorPos); - const ValidatorBlock* _validatorBlock() const { return validatorBlock_.data(); } - QPoint _toScreen(QPoint point) const; - void _cancelWidget(){ widget_.reset(); } - void _drawRowLabel(QPainter& p, const wchar_t* text, const QFont* font, const QRect& rect, const QColor& color) const; - void _drawRowValue(QPainter& p, const wchar_t* text, const QFont* font, const QRect& rect, const QColor& color, bool pathEllipsis, bool center) const; - QRect _visibleRect() const; - bool _isDragged(const PropertyRow* row) const; - bool _isCapturedRow(const PropertyRow* row) const; - PropertyRow* _pressedRow() const { return pressedRow_; } - void _setPressedRow(PropertyRow* row) { pressedRow_ = row; } - int _applyTime() const{ return applyTime_; } - int _revertTime() const{ return revertTime_; } - int _updateHeightsTime() const{ return updateHeightsTime_; } - int _paintTime() const{ return paintTime_; } - const QFont& _boldFont() const{ return boldFont_; } - bool hasFocusOrInplaceHasFocus() const; - void addMenuHandler(PropertyRowMenuHandler* handler); - IconXPMCache* _iconCache() const{ return iconCache_.data(); } -public slots: - void onFilterChanged(const QString& str); -protected slots: - void onScroll(int pos); - void onModelUpdated(const PropertyRows& rows, bool apply); - void onModelPushUndo(PropertyTreeOperator* op, bool* handled); - void onModelPushRedo(PropertyTreeOperator* op, bool* handled); - void onMouseStillTimeout(); - -private: - QPropertyTree(const QPropertyTree&); - QPropertyTree& operator=(const QPropertyTree&); -protected: - class DragController; - enum HitTest{ - TREE_HIT_PLUS, - TREE_HIT_TEXT, - TREE_HIT_ROW, - TREE_HIT_NONE - }; - PropertyRow* rowByPoint(const QPoint& point); - HitTest hitTest(PropertyRow* row, const QPoint& pointInWindowSpace, const QRect& rowRect); - void onRowMenuDecompose(PropertyRow* row); - void onMouseStill(QPoint point); - - QSize sizeHint() const override; - bool event(QEvent* ev) override; - void paintEvent(QPaintEvent* ev) override; - void moveEvent(QMoveEvent* ev) override; - void resizeEvent(QResizeEvent* ev) override; - void mousePressEvent(QMouseEvent* ev) override; - void mouseReleaseEvent(QMouseEvent* ev) override; - void mouseDoubleClickEvent(QMouseEvent* ev) override; - void mouseMoveEvent(QMouseEvent* ev) override; - void wheelEvent(QWheelEvent* ev) override; - void keyPressEvent(QKeyEvent* ev) override; - void focusInEvent(QFocusEvent* ev) override; - - void updateArea(); - bool toggleRow(PropertyRow* row); - - struct RowFilter { - enum Type { - NAME_VALUE, - NAME, - VALUE, - TYPE, - NUM_TYPES - }; - - string start[NUM_TYPES]; - bool tillEnd[NUM_TYPES]; - std::vector substrings[NUM_TYPES]; - - void parse(const char* filter); - bool match(const char* text, Type type, size_t* matchStart, size_t* matchEnd) const; - bool typeRelevant(Type type) const{ - return !start[type].empty() || !substrings[type].empty(); - } - - RowFilter() - { - for (int i = 0; i < NUM_TYPES; ++i) - tillEnd[i] = false; - } - }; - - QPoint pointToRootSpace(const QPoint& pointInWindowSpace) const; - QPoint pointFromRootSpace(const QPoint& point) const; - - void interruptDrag(); - void updateHeights(bool recalculateTextSize=false); - void updateValidatorIcons(); - bool updateScrollBar(); - void applyValidation(); - void jumpToNextHiddenValidatorIssue(bool isError, PropertyRow* start); - - bool onContextMenu(PropertyRow* row, QMenu& menu); - void clearMenuHandlers(); - bool onRowKeyDown(PropertyRow* row, const QKeyEvent* ev); - bool rowProcessesKey(PropertyRow* row, const QKeyEvent* ev); - // points here are specified in root-row space - bool onRowLMBDown(PropertyRow* row, const QRect& rowRect, QPoint point, bool controlPressed, bool shiftPressed); - void onRowLMBUp(PropertyRow* row, const QRect& rowRect, QPoint point); - void onRowRMBDown(PropertyRow* row, const QRect& rowRect, QPoint point); - void onRowMouseMove(PropertyRow* row, const QRect& rowRect, QPoint point); - - bool canBePasted(PropertyRow* destination); - bool canBePasted(const char* destinationType); - - void setFilterMode(bool inFilterMode); - void startFilter(const char* filter); - void setWidget(PropertyRowWidget* widget); - void _arrangeChildren(); - - void updateAttachedPropertyTree(bool revert); - void drawFilteredString(QPainter& p, const wchar_t* text, RowFilter::Type type, const QFont* font, const QRect& rect, const QColor& color, bool pathEllipsis, bool center) const; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - QScopedPointer model_; - int cursorX_; - - QScopedPointer widget_; // in-place widget - vector menuHandlers_; - - typedef vector Objects; - Objects attached_; - QPropertyTree* attachedPropertyTree_; - bool autoHideAttachedPropertyTree_; - - bool filterMode_; - RowFilter rowFilter_; - QScopedPointer filterEntry_; - QScopedPointer iconCache_; - Serialization::SContextLink* archiveContext_; - QScopedPointer validatorBlock_; - bool outlineMode_; - bool sizeToContent_; - bool hideSelection_; - - bool autoRevert_; - bool needUpdate_; - - QScrollBar* scrollBar_; - QFont boldFont_; - QColor backgroundColor_; - QRect area_; - int leftBorder_; - int rightBorder_; - QPoint size_; - QPoint offset_; - QSize sizeHint_; - QSize contentSize_; - DragController* dragController_; - Serialization::SharedPtr lastSelectedRow_; - QPoint pressPoint_; - QPoint pressDelta_; - bool pointerMovedSincePress_; - QPoint lastStillPosition_; - PropertyRow* capturedRow_; - PropertyRow* pressedRow_; - QTimer* mouseStillTimer_; - - bool aggregateMouseEvents_; - int aggregatedMouseEventCount_; - QScopedPointer lastMouseMoveEvent_; - - PropertyTreeConfig config_; - QScopedPointer style_; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - int defaultRowHeight_; - - int applyTime_; - int revertTime_; - int updateHeightsTime_; - int paintTime_; - int zoomLevel_; - bool dragCheckMode_; - bool dragCheckValue_; - - friend class TreeImpl; - friend class FilterEntry; - friend class DragWindow; - friend struct FilterVisitor; - friend struct PropertyTreeMenuHandler; -}; - -wstring generateDigest(Serialization::SStruct& ser); -// vim: tw=90: - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_QPROPERTYTREE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTreeStyle.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTreeStyle.h deleted file mode 100644 index 82577c1b90..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTreeStyle.h +++ /dev/null @@ -1,90 +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 - -#include "Serialization.h" -#include "Serialization/Decorators/Range.h" - -struct QPropertyTreeStyle -{ - bool compact; - bool packCheckboxes; - bool fullRowMode; - bool showHorizontalLines; - bool doNotIndentSecondLevel; - bool groupShadows; - bool groupRectangle; - bool alignLabelsToRight; - float valueColumnWidth; - float rowSpacing; - unsigned char levelShadowOpacity; - float levelIndent; - float firstLevelIndent; - float groupShade; - float sliderSaturation; - - QPropertyTreeStyle() - : compact(false) - , packCheckboxes(true) - , fullRowMode(false) - , valueColumnWidth(.59f) - , rowSpacing(1.1f) - , showHorizontalLines(false) - , firstLevelIndent(0.75f) - , levelIndent(0.75f) - , levelShadowOpacity(36) - , doNotIndentSecondLevel(false) - , groupShadows(false) - , sliderSaturation(0.0f) - , groupShade(0.15f) - , groupRectangle(false) - , alignLabelsToRight(false) - { - } - - void Serialize(Serialization::IArchive& ar) - { - ar.Doc("Here you can define appearance of QPropertyTree control."); - - ar(valueColumnWidth, "valueColumnWidth", "Value Column Width"); - ar.Doc("Defines a ratio of the value / name columns. Normalized."); - ar(Serialization::Range(rowSpacing, 0.5f, 3.0f), "rowSpacing", "Row Spacing"); - ar.Doc("Height of one row (line) in text-height units."); - ar(alignLabelsToRight, "alignLabelsToRight", "Right Alignment"); - ar(Serialization::Range(levelIndent, 0.0f, 3.0f), "levelIndent", "Level Indent"); - ar.Doc("Indentation of a every next level in text-height units."); - - ar(Serialization::Range(firstLevelIndent, 0.0f, 3.0f), "firstLevelIndent", "First Level Indent"); - ar.Doc("Indentation of a very first level in text-height units."); - ar(Serialization::Range(sliderSaturation, 0.0f, 1.0f), "sliderSaturation", "Slider Saturation"); - ar(levelShadowOpacity, "levelShadowOpacity", "Level Shadow Opacity"); - ar.Doc("Amount of background darkening that gets added to each next nested level."); - - ar(compact, "compact", "Compact"); - ar.Doc("Compact mode removes expansion pluses from the level and reduces inner padding. Useful for narrowing the widget."); - ar(packCheckboxes, "packCheckboxes", "Pack Checkboxes"); - ar.Doc("Arranges checkboxes in two columns, when possible."); - - ar(showHorizontalLines, "showHorizontalLines", "Horizontal Lines"); - ar.Doc("Show thin line that connects row name with its value."); - - ar(doNotIndentSecondLevel, "doNotIndentSecondLevel", "Do not indent second level"); - ar(groupShadows, "groupShadows", "Group Shadows"); - ar(groupRectangle, "groupRectangle", "Group Rectangle"); - - ar(Serialization::Range(groupShade, -1.0f, 1.0f), "groupShade", "Group Shade"); - ar.Doc("Shade of the group."); - } -}; - diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Serialization.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Serialization.h deleted file mode 100644 index 3ce0c2c8f2..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Serialization.h +++ /dev/null @@ -1,29 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_SERIALIZATION_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_SERIALIZATION_H -#pragma once - - -#include "Serialization/STL.h" -#include "Serialization/Pointers.h" -#include "Serialization/ClassFactory.h" -#include "Serialization/StringList.h" - -#include "Serialization/IArchive.h" -#include "Serialization/BinArchive.h" - -using Serialization::IArchive; -using Serialization::SStruct; -using Serialization::TypeID; -using Serialization::SharedPtr; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_SERIALIZATION_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerEdit.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerEdit.cpp deleted file mode 100644 index 640197ca45..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerEdit.cpp +++ /dev/null @@ -1,56 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "SpriteBorderEditorCommon.h" - -SlicerEdit::SlicerEdit( SpriteBorder border, - QSize& unscaledPixmapSize, - ISprite* sprite ) -: QLineEdit() -, m_manipulator( nullptr ) -{ - bool isVertical = IsBorderVertical( border ); - - float totalUnscaledSizeInPixels = aznumeric_cast( isVertical ? unscaledPixmapSize.width() : unscaledPixmapSize.height() ); - - setPixelPosition( GetBorderValueInPixels( sprite, border, totalUnscaledSizeInPixels ) ); - - setValidator( new QDoubleValidator( 0.0f, totalUnscaledSizeInPixels, 1 ) ); - - QObject::connect( this, - &SlicerEdit::editingFinished, this, - [ this, border, sprite, totalUnscaledSizeInPixels ]() - { - float p = text().toFloat(); - - m_manipulator->setPixelPosition( p ); - - SetBorderValue( sprite, border, p, totalUnscaledSizeInPixels ); - } ); -} - -void SlicerEdit::SetManipulator(SlicerManipulator* manipulator) -{ - m_manipulator = manipulator; -} - -void SlicerEdit::setPixelPosition(float p) -{ - setText( QString::number( p ) ); -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerEdit.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerEdit.h deleted file mode 100644 index 88d47d3817..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerEdit.h +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. -#pragma once -#ifndef CRYINCLUDE_EDITORCOMMON_SLICEREDIT_H -#define CRYINCLUDE_EDITORCOMMON_SLICEREDIT_H - -#if !defined(Q_MOC_RUN) -#include - -#include "SpriteBorderEditorCommon.h" -#endif - -class SlicerEdit -: public QLineEdit -{ - Q_OBJECT - -public: - - SlicerEdit( SpriteBorder border, - QSize& unscaledPixmapSize, - ISprite* sprite ); - - void SetManipulator(SlicerManipulator* manipulator); - - void setPixelPosition(float p); - -private: - - SlicerManipulator* m_manipulator; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_SLICEREDIT_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerManipulator.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerManipulator.cpp deleted file mode 100644 index d516f30e7d..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerManipulator.cpp +++ /dev/null @@ -1,143 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "SpriteBorderEditorCommon.h" - -#define CRYINCLUDE_EDITORCOMMON_DRAW_SELECTABLE_AREA_OF_SLICERMANIPULATOR ( 0 ) -#define CRYINCLUDE_EDITORCOMMON_ARBITRARILY_LARGE_NUMBER ( 10000.0f ) -#define CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_WIDTH ( 2.0f ) - -SlicerManipulator::SlicerManipulator( SpriteBorder border, - QSize& unscaledPixmapSize, - QSize& scaledPixmapSize, - float thicknessInPixels, - ISprite* sprite, - QGraphicsScene* scene ) -: QGraphicsRectItem() -, m_border( border ) -, m_isVertical( IsBorderVertical( m_border ) ) -, m_unscaledPixmapSize( unscaledPixmapSize ) -, m_scaledPixmapSize( scaledPixmapSize ) -, m_sprite( sprite ) -, m_unscaledOverScaledFactor( ( (float)m_unscaledPixmapSize.width() / (float)m_scaledPixmapSize.width() ), - ( (float)m_unscaledPixmapSize.height() / (float)m_scaledPixmapSize.height() ) ) -, m_scaledOverUnscaledFactor( ( 1.0f / m_unscaledOverScaledFactor.x() ), - ( 1.0f / m_unscaledOverScaledFactor.y() ) ) -, m_color( Qt::white ) -, m_edit( nullptr ) -{ - setAcceptHoverEvents( true ); - - scene->addItem( this ); - - setRect( ( m_isVertical ? - ( thicknessInPixels * 0.5f ) : - CRYINCLUDE_EDITORCOMMON_ARBITRARILY_LARGE_NUMBER ), - ( m_isVertical ? - CRYINCLUDE_EDITORCOMMON_ARBITRARILY_LARGE_NUMBER : - ( thicknessInPixels * 0.5f ) ), - ( m_isVertical ? thicknessInPixels : ( 3.0f * CRYINCLUDE_EDITORCOMMON_ARBITRARILY_LARGE_NUMBER ) ), - ( m_isVertical ? ( 3.0f * CRYINCLUDE_EDITORCOMMON_ARBITRARILY_LARGE_NUMBER ) : thicknessInPixels ) ); - - setPixelPosition( GetBorderValueInPixels( m_sprite, m_border, aznumeric_cast( m_isVertical ? m_unscaledPixmapSize.width() : m_unscaledPixmapSize.height() ) ) ); - - setFlag( QGraphicsItem::ItemIsMovable, true ); - setFlag( QGraphicsItem::ItemIsSelectable, true ); // This allows using the CTRL key to select multiple manipulators and move them simultaneously. - setFlag( QGraphicsItem::ItemSendsScenePositionChanges, true ); -} - -void SlicerManipulator::SetEdit( SlicerEdit *edit ) -{ - m_edit = edit; -} - -void SlicerManipulator::paint(QPainter* painter, [[maybe_unused]] const QStyleOptionGraphicsItem* option, [[maybe_unused]] QWidget* widget) -{ -#if CRYINCLUDE_EDITORCOMMON_DRAW_SELECTABLE_AREA_OF_SLICERMANIPULATOR - QGraphicsRectItem::paint( painter, option, widget ); -#endif // CRYINCLUDE_EDITORCOMMON_DRAW_SELECTABLE_AREA_OF_SLICERMANIPULATOR - - QPen pen; - pen.setStyle( isSelected() ? Qt::DashLine : Qt::DotLine ); - pen.setWidthF( CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_WIDTH ); - - // Draw a thin line in the middle of the selectable area. - if( m_isVertical ) - { - float x = aznumeric_cast( ( ( rect().left() + rect().right() ) * 0.5f ) - CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_WIDTH ); - - pen.setColor( m_color ); - painter->setPen( pen ); - painter->drawLine(aznumeric_cast(x), aznumeric_cast(rect().top()), aznumeric_cast(x), aznumeric_cast(rect().bottom()) ); - - x += CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_WIDTH; - pen.setColor( Qt::black ); - painter->setPen( pen ); - painter->drawLine(aznumeric_cast(x), aznumeric_cast(rect().top()), aznumeric_cast(x), aznumeric_cast(rect().bottom()) ); - } - else - { - float y = aznumeric_cast( ( ( rect().top() + rect().bottom() ) * 0.5f ) - CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_WIDTH ); - - pen.setColor( m_color ); - painter->setPen( pen ); - painter->drawLine(aznumeric_cast(rect().left()), aznumeric_cast(y), aznumeric_cast(rect().right()), aznumeric_cast(y) ); - - y += CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_WIDTH; - pen.setColor( Qt::black ); - painter->setPen( pen ); - painter->drawLine(aznumeric_cast(rect().left()), aznumeric_cast(y), aznumeric_cast(rect().right()), aznumeric_cast(y) ); - } -} - -void SlicerManipulator::setPixelPosition(float p) -{ - setPos( ( m_isVertical ? ( p * m_scaledOverUnscaledFactor.x() ) : 0.0f ), - ( m_isVertical ? 0.0f : ( p * m_scaledOverUnscaledFactor.y() ) ) ); -} - -QVariant SlicerManipulator::itemChange(GraphicsItemChange change, const QVariant& value) -{ - if( ( change == ItemPositionChange ) && - scene() ) - { - float totalScaledSizeInPixels = aznumeric_cast( m_isVertical ? m_scaledPixmapSize.width() : m_scaledPixmapSize.height() ); - - float p = clamp_tpl(aznumeric_cast( m_isVertical ? value.toPointF().x() : value.toPointF().y() ), - 0.0f, - totalScaledSizeInPixels ); - - m_edit->setPixelPosition( m_isVertical ? aznumeric_cast( p * m_unscaledOverScaledFactor.x() ) : aznumeric_cast( p * m_unscaledOverScaledFactor.y() ) ); - - SetBorderValue( m_sprite, m_border, p, totalScaledSizeInPixels ); - - return QPointF( ( m_isVertical ? p : 0.0f ), - ( m_isVertical ? 0.0f : p ) ); - } - - return QGraphicsItem::itemChange( change, value ); -} - -void SlicerManipulator::hoverEnterEvent([[maybe_unused]] QGraphicsSceneHoverEvent* event) -{ - setCursor( m_isVertical ? Qt::SizeHorCursor : Qt::SizeVerCursor ); - m_color = Qt::yellow; - update(); -} - -void SlicerManipulator::hoverLeaveEvent([[maybe_unused]] QGraphicsSceneHoverEvent* event) -{ - setCursor(Qt::ArrowCursor); - m_color = Qt::white; - update(); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerManipulator.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerManipulator.h deleted file mode 100644 index 7f4f21506e..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerManipulator.h +++ /dev/null @@ -1,58 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_H -#define CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_H - -class SlicerManipulator -: public QGraphicsRectItem -{ -public: - - SlicerManipulator( SpriteBorder border, - QSize& unscaledPixmapSize, - QSize& scaledPixmapSize, - float thicknessInPixels, - ISprite* sprite, - QGraphicsScene* scene ); - - void SetEdit(SlicerEdit* edit); - - void setPixelPosition(float p); - -protected: - - QVariant itemChange(GraphicsItemChange change, const QVariant& value) override; - void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override; - void hoverEnterEvent(QGraphicsSceneHoverEvent* event) override; - void hoverLeaveEvent(QGraphicsSceneHoverEvent* event) override; - -private: - - SpriteBorder m_border; - bool m_isVertical; - QSize m_unscaledPixmapSize; - QSize m_scaledPixmapSize; - ISprite* m_sprite; - QPointF m_unscaledOverScaledFactor; - QPointF m_scaledOverUnscaledFactor; - QColor m_color; - - SlicerEdit* m_edit; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerView.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerView.cpp deleted file mode 100644 index 7ec2ec4c8c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerView.cpp +++ /dev/null @@ -1,25 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "SpriteBorderEditorCommon.h" - -SlicerView::SlicerView(QGraphicsScene* scene, QWidget* parent) -: QGraphicsView( scene, parent ) -{ - setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerView.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerView.h deleted file mode 100644 index f2644123ce..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerView.h +++ /dev/null @@ -1,34 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_EDITORCOMMON_SLICERVIEW_H -#define CRYINCLUDE_EDITORCOMMON_SLICERVIEW_H - -class SlicerView -: public QGraphicsView -{ -public: - - SlicerView(QGraphicsScene* scene, QWidget* parent = nullptr); - -protected: - - // This is intentionally empty. - void scrollContentsBy([[maybe_unused]] int dx, [[maybe_unused]] int dy) override {}; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_SLICERVIEW_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditor.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditor.cpp deleted file mode 100644 index d67936de3f..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditor.cpp +++ /dev/null @@ -1,175 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "SpriteBorderEditorCommon.h" -#include // for Getting the game folder - -//------------------------------------------------------------------------------- - -#define VIEW_WIDTH ( 200 ) -#define VIEW_HEIGHT ( 200 ) -#define MANIPULATOR_THICKNESS_IN_PIXELS ( 24 ) - -//------------------------------------------------------------------------------- - -SpriteBorderEditor::SpriteBorderEditor(const char* path, QWidget* parent) -: QDialog( parent ) -, hasBeenInitializedProperly( true ) -{ - ISprite* sprite = gEnv->pLyShine->LoadSprite( path ); - CRY_ASSERT( sprite ); - - // The layout. - QGridLayout* outerGrid = new QGridLayout(this); - - QGridLayout* innerGrid = new QGridLayout(); - outerGrid->addLayout( innerGrid, 0, 0, 1, 2 ); - - // The scene. - QGraphicsScene* scene( new QGraphicsScene( 0.0f, 0.0f, VIEW_WIDTH, VIEW_HEIGHT, this ) ); - - // The view. - innerGrid->addWidget( new SlicerView( scene, this ), 0, 0, 6, 1 ); - - // The image. - QGraphicsPixmapItem* pixmapItem = nullptr; - QSize unscaledPixmapSize; - QSize scaledPixmapSize; - { - // assets can be in gems as well as in the current project. Qpixmap requires a path to - // the asset and doesn't know about such concepts. So adjust the pathname to something - // that Qpixmap can open. - QString fullPath = Path::GamePathToFullPath(sprite->GetTexturePathname().c_str()); - QPixmap unscaledPixmap(fullPath); - - bool isVertical = ( unscaledPixmap.size().height() > unscaledPixmap.size().width() ); - - // Scale-to-fit, while preserving aspect ratio. - pixmapItem = scene->addPixmap( isVertical ? unscaledPixmap.scaledToHeight( VIEW_HEIGHT ) : unscaledPixmap.scaledToWidth( VIEW_WIDTH ) ); - - unscaledPixmapSize = unscaledPixmap.size(); - scaledPixmapSize = pixmapItem->pixmap().size(); - } - - // Add text fields and manipulators. - { - int row = 0; - - innerGrid->addWidget( new QLabel( QString( "Texture is %1 x %2" ).arg( QString::number( unscaledPixmapSize.width() ), - QString::number( unscaledPixmapSize.height() ) ), - this ), - row++, - 1 ); - - for( SpriteBorder b : SpriteBorder() ) - { - SlicerEdit* edit = new SlicerEdit( b, - unscaledPixmapSize, - sprite ); - - SlicerManipulator* manipulator = new SlicerManipulator( b, - unscaledPixmapSize, - scaledPixmapSize, - MANIPULATOR_THICKNESS_IN_PIXELS, - sprite, - scene ); - - edit->SetManipulator( manipulator ); - manipulator->SetEdit( edit ); - - innerGrid->addWidget( new QLabel( SpriteBorderToString( b ), this ), row, 1 ); - innerGrid->addWidget( edit, row, 2 ); - innerGrid->addWidget( new QLabel( "pixels", this ), row, 3 ); - ++row; - } - } - - // Add buttons. - { - // Save button. - QPushButton* saveButton = new QPushButton( "Save", this ); - QObject::connect( saveButton, - &QPushButton::clicked, this, - [ this, sprite ]([[maybe_unused]] bool checked ) - { - // Sanitize values. - // - // This is the simplest way to sanitize the - // border values. Otherwise, we need to prevent - // flipping the manipulators in the UI. - { - ISprite::Borders b = sprite->GetBorders(); - - if( b.m_top > b.m_bottom ) - { - std::swap( b.m_top, b.m_bottom ); - } - - if( b.m_left > b.m_right ) - { - std::swap( b.m_left, b.m_right ); - } - - sprite->SetBorders( b ); - } - - QString fullPath = Path::GamePathToFullPath(sprite->GetPathname().c_str()); - bool result = sprite->SaveToXml(fullPath.toUtf8().data()); - - if (result) - { - close(); - } - else - { - QMessageBox box(QMessageBox::Critical, - "Error", - "Unable to save file", - QMessageBox::Ok); - box.exec(); - } - } ); - outerGrid->addWidget( saveButton, 1, 0 ); - - // Cancel button. - ISprite::Borders originalBorders = sprite->GetBorders(); - QPushButton* cancelButton = new QPushButton( "Cancel", this ); - QObject::connect( cancelButton, - &QPushButton::clicked, this, - [ this, sprite, originalBorders ]([[maybe_unused]] bool checked ) - { - // Restore original borders. - sprite->SetBorders( originalBorders ); - - close(); - } ); - outerGrid->addWidget( cancelButton, 1, 1 ); - } - - setWindowTitle( "SpriteBorderEditor" ); - setModal( true ); - setWindowModality( Qt::ApplicationModal ); - - layout()->setSizeConstraint( QLayout::SetFixedSize ); -} - -bool SpriteBorderEditor::GetHasBeenInitializedProperly() -{ - return hasBeenInitializedProperly; -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditor.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditor.h deleted file mode 100644 index b670d75af8..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditor.h +++ /dev/null @@ -1,41 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_EDITORCOMMON_SPRITEBORDEREDITOR_H -#define CRYINCLUDE_EDITORCOMMON_SPRITEBORDEREDITOR_H - -#if !defined(Q_MOC_RUN) -#include -#endif - -class SpriteBorderEditor -: public QDialog -{ - Q_OBJECT - -public: - - SpriteBorderEditor(const char* path, QWidget* parent = nullptr); - - bool GetHasBeenInitializedProperly(); - -private: - - bool hasBeenInitializedProperly; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_SPRITEBORDEREDITOR_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditorCommon.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditorCommon.cpp deleted file mode 100644 index 305f9dafa7..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditorCommon.cpp +++ /dev/null @@ -1,120 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "SpriteBorderEditorCommon.h" - -bool IsBorderVertical(SpriteBorder border) -{ - return ( ( border == SpriteBorder::Left ) || - ( border == SpriteBorder::Right ) ); -} - -float GetBorderValueInPixels(ISprite* sprite, SpriteBorder b, float totalSizeInPixels) -{ - // IMPORTANT: We CAN'T replace totalSizeInPixels with - // sprite->GetTexture()->GetWidth()/GetHeight() because - // it DOESN'T return the original texture file's size. - - ISprite::Borders sb = sprite->GetBorders(); - - float *f = nullptr; - - if( b == SpriteBorder::Top ) - { - f = &sb.m_top; - } - else if( b == SpriteBorder::Bottom ) - { - f = &sb.m_bottom; - } - else if( b == SpriteBorder::Left ) - { - f = &sb.m_left; - } - else if( b == SpriteBorder::Right ) - { - f = &sb.m_right; - } - else - { - CRY_ASSERT( 0 ); - f = nullptr; - } - - return ( *f * totalSizeInPixels ); -} - -void SetBorderValue(ISprite* sprite, SpriteBorder b, float pixelPosition, float totalSizeInPixels) -{ - // IMPORTANT: We CAN'T replace totalSizeInPixels with - // sprite->GetTexture()->GetWidth()/GetHeight() because - // it DOESN'T return the original texture file's size. - - ISprite::Borders sb = sprite->GetBorders(); - - float *f = nullptr; - - if( b == SpriteBorder::Top ) - { - f = &sb.m_top; - } - else if( b == SpriteBorder::Bottom ) - { - f = &sb.m_bottom; - } - else if( b == SpriteBorder::Left ) - { - f = &sb.m_left; - } - else if( b == SpriteBorder::Right ) - { - f = &sb.m_right; - } - else - { - CRY_ASSERT( 0 ); - f = nullptr; - } - - *f = ( pixelPosition / totalSizeInPixels ); - sprite->SetBorders( sb ); -} - -const char* SpriteBorderToString(SpriteBorder b) -{ - if( b == SpriteBorder::Top ) - { - return "Top"; - } - else if( b == SpriteBorder::Bottom ) - { - return "Bottom"; - } - else if( b == SpriteBorder::Left ) - { - return "Left"; - } - else if( b == SpriteBorder::Right ) - { - return "Right"; - } - else - { - CRY_ASSERT( 0 ); - return "UNKNOWN"; - } -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditorCommon.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditorCommon.h deleted file mode 100644 index de85c71e5a..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditorCommon.h +++ /dev/null @@ -1,78 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_EDITORCOMMON_SPRITEBORDEREDITORCOMMON_H -#define CRYINCLUDE_EDITORCOMMON_SPRITEBORDEREDITORCOMMON_H - -#include // required to be included before platform.h -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class SlicerEdit; -class SlicerManipulator; -class SlicerView; -class SpriteBorderEditor; - -enum class SpriteBorder -{ - Top, - Bottom, - Left, - Right -}; - -// This allows iterating over an enum class. -#define ADD_ENUM_CLASS_ITERATION_OPERATORS( CLASS_NAME, FIRST_VALUE, LAST_VALUE ) \ - \ - inline CLASS_NAME operator++(CLASS_NAME &m){ return m = (CLASS_NAME)(std::underlying_type::type(m) + 1); } \ - inline CLASS_NAME operator*(CLASS_NAME m){ return m; } \ - inline CLASS_NAME begin([[maybe_unused]] CLASS_NAME m){ return FIRST_VALUE; } \ - inline CLASS_NAME end([[maybe_unused]] CLASS_NAME m){ return (CLASS_NAME)(std::underlying_type::type(LAST_VALUE) + 1); } - -ADD_ENUM_CLASS_ITERATION_OPERATORS( SpriteBorder, - SpriteBorder::Top, - SpriteBorder::Right ); - -#include "SlicerEdit.h" -#include "SlicerManipulator.h" -#include "SlicerView.h" -#include "SpriteBorderEditor.h" - -bool IsBorderVertical(SpriteBorder border); -float GetBorderValueInPixels(ISprite* sprite, SpriteBorder b, float totalSizeInPixels); -void SetBorderValue(ISprite* sprite, SpriteBorder b, float pixelPosition, float totalSizeInPixels); -const char* SpriteBorderToString(SpriteBorder b); - -#endif // CRYINCLUDE_EDITORCOMMON_SPRITEBORDEREDITORCOMMON_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Strings.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Strings.h deleted file mode 100644 index 5f52145f41..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Strings.h +++ /dev/null @@ -1,29 +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_EDITORCOMMON_QPROPERTYTREE_STRINGS_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_STRINGS_H -#pragma once - -#ifndef SERIALIZATION_STANDALONE -#include - -typedef CryStringT string; -typedef CryStringT wstring; -#else -#include -using std::string; -using std::wstring; -#endif - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_STRINGS_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Unicode.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Unicode.h deleted file mode 100644 index 71f9830d0e..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Unicode.h +++ /dev/null @@ -1,24 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_UNICODE_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_UNICODE_H -#pragma once - -#include "Strings.h" -#include - -string fromWideChar(const wchar_t* wideCharString); -wstring toWideChar(const char* multiByteString); -wstring fromANSIToWide(const char* ansiString); -string toANSIFromWide(const wchar_t* wstr); - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_UNICODE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ValidatorBlock.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ValidatorBlock.h deleted file mode 100644 index db1480225c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ValidatorBlock.h +++ /dev/null @@ -1,172 +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 - -#include "Strings.h" -#include -#include -#include - -enum ValidatorEntryType -{ - VALIDATOR_ENTRY_WARNING, - VALIDATOR_ENTRY_ERROR -}; - -struct ValidatorEntry -{ - const void* handle; - Serialization::TypeID typeId; - - ValidatorEntryType type; - string message; - - bool operator<(const ValidatorEntry& rhs) const - { - if (handle != rhs.handle) - { - return handle < rhs.handle; - } - return typeId < rhs.typeId; - } - - ValidatorEntry(ValidatorEntryType type, const void* handle, const Serialization::TypeID& typeId, const char* message) - : type(type) - , handle(handle) - , message(message) - , typeId(typeId) - { - } - - ValidatorEntry() - : handle() - , type(VALIDATOR_ENTRY_WARNING) - { - } -}; -typedef std::vector ValidatorEntries; - -class ValidatorBlock -{ -public: - ValidatorBlock() - : m_enabled(false) - { - } - - void Clear() - { - m_entries.clear(); - m_used.clear(); - } - - void AddEntry(const ValidatorEntry& entry) - { - ValidatorEntries::iterator it = std::upper_bound(m_entries.begin(), m_entries.end(), entry); - m_used.insert(m_used.begin() + (it - m_entries.begin()), false); - m_entries.insert(it, entry); - m_enabled = true; - } - - bool IsEnabled() const { return m_enabled; } - - const ValidatorEntry* GetEntry(int index, int count) const - { - if (size_t(index) >= m_entries.size()) - { - return 0; - } - if (size_t(index + count) > m_entries.size()) - { - return 0; - } - return &m_entries[index]; - } - - bool FindHandleEntries(int* outIndex, int* outCount, const void* handle, Serialization::TypeID& typeId) - { - if (handle == 0) - { - return false; - } - ValidatorEntry e; - e.handle = handle; - e.typeId = typeId; - ValidatorEntries::iterator begin = std::lower_bound(m_entries.begin(), m_entries.end(), e); - ValidatorEntries::iterator end = std::upper_bound(m_entries.begin(), m_entries.end(), e); - if (begin != end) - { - *outIndex = int(begin - m_entries.begin()); - *outCount = int(end - begin); - return true; - } - return false; - } - - void MarkAsUsed(int start, int count) - { - if (start < 0) - { - return; - } - if (start + count > m_entries.size()) - { - return; - } - for (int i = start; i < start + count; ++i) - { - m_used[i] = true; - } - } - - void MergeUnusedItemsWithRootItems(int* firstUnusedItem, int* count, const void* newHandle, Serialization::TypeID& typeId) - { - size_t numItems = m_used.size(); - for (size_t i = 0; i < numItems; ++i) - { - if (m_entries[i].handle == newHandle) - { - m_entries.push_back(m_entries[i]); - m_used.push_back(true); - m_entries[i].typeId = Serialization::TypeID(); - } - if (!m_used[i]) - { - m_entries.push_back(m_entries[i]); - m_used.push_back(true); - m_entries.back().handle = newHandle; - m_entries.back().typeId = typeId; - } - } - *firstUnusedItem = (int)numItems; - *count = int(m_entries.size() - numItems); - } - - bool ContainsErrors() const - { - for (size_t i = 0; i < m_entries.size(); ++i) - { - if (m_entries[i].type == VALIDATOR_ENTRY_ERROR) - { - return true; - } - } - return false; - } - -private: - ValidatorEntries m_entries; - std::vector m_used; - bool m_enabled; -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/error.xpm b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/error.xpm deleted file mode 100644 index c26942bda9..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/error.xpm +++ /dev/null @@ -1,126 +0,0 @@ -/* XPM */ -static const char * error_xpm[] = { -"16 16 107 2", -" c None", -". c #F98267", -"+ c #F78065", -"@ c #F57E63", -"# c #F37C61", -"$ c #F98268", -"% c #EE836E", -"& c #F4A692", -"* c #F8B4A0", -"= c #F3A691", -"- c #E97D68", -"; c #EB7359", -"> c #F88166", -", c #F19784", -"' c #FBBDA9", -") c #F8A38A", -"! c #F6896B", -"~ c #F8A289", -"{ c #FABCA8", -"] c #EC927F", -"^ c #E46C52", -"/ c #F67F65", -"( c #F09783", -"_ c #F58263", -": c #FFFFFF", -"< c #F37E61", -"[ c #F37C60", -"} c #F9B9A6", -"| c #EA8D7B", -"1 c #DE644A", -"2 c #EC816C", -"3 c #F58162", -"4 c #F48062", -"5 c #F17A5F", -"6 c #F0785F", -"7 c #EF765D", -"8 c #F8B5A5", -"9 c #DD705D", -"0 c #F8A188", -"a c #EE735C", -"b c #EC705B", -"c c #F19382", -"d c #EC9889", -"e c #D2583E", -"f c #ED765B", -"g c #F8B6A1", -"h c #F48467", -"i c #EB6E5A", -"j c #EA6C59", -"k c #E96F5F", -"l c #F1A89B", -"m c #CE533A", -"n c #E97157", -"o c #F7B3A0", -"p c #F28065", -"q c #FAD9D3", -"r c #E86958", -"s c #E76757", -"t c #E76C5D", -"u c #F1A599", -"v c #CA4F35", -"w c #E56D52", -"x c #F09F8E", -"y c #F49984", -"z c #F19D90", -"A c #F3AFA6", -"B c #E66556", -"C c #E56255", -"D c #EB897D", -"E c #E79185", -"F c #C64A31", -"G c #E07360", -"H c #F7B3A4", -"I c #E36154", -"J c #E25F53", -"K c #F2A99F", -"L c #D16150", -"M c #DA6046", -"N c #E68878", -"O c #F5B0A3", -"P c #ED9289", -"Q c #EC9288", -"R c #E15D52", -"S c #DD7D6F", -"T c #C0442B", -"U c #D3593F", -"V c #E38475", -"W c #F4ACA1", -"X c #EC8B7F", -"Y c #E4675C", -"Z c #E3665B", -"` c #EA877D", -" . c #F1A89F", -".. c #DD7C6F", -"+. c #BF4329", -"@. c #CC5238", -"#. c #D46452", -"$. c #E79084", -"%. c #EEA095", -"&. c #ED9F95", -"*. c #E58E83", -"=. c #CE5D4C", -"-. c #BD4128", -";. c #C4482F", -">. c #C2462C", -",. c #C0442A", -"'. c #BE4228", -" ", -" . + @ # ", -" $ % & * * = - ; ", -" > , ' ) ! ! ~ { ] ^ ", -" / ( ' _ _ : : < [ } | 1 ", -" 2 ' _ 3 4 : : 5 6 7 8 9 ", -" 5 = 0 4 < [ : : 7 a b c d e ", -" f g h [ 5 6 : : b i j k l m ", -" n o p 6 7 a q : j r s t u v ", -" w x y a b i z A s B C D E F ", -" G H i j r : : C I J K L ", -" M N O s B P Q J R K S T ", -" U V W X Y Z ` ...+. ", -" @.#.$.%.&.*.=.-. ", -" ;.>.,.'. ", -" "}; diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/file_open.xpm b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/file_open.xpm deleted file mode 100644 index cd355e8dd4..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/file_open.xpm +++ /dev/null @@ -1,142 +0,0 @@ -/* XPM */ -static const char * file_open_xpm[] = { -"16 16 123 2", -" c None", -". c #E0C259", -"+ c #E2C361", -"@ c #E3C463", -"# c #E3C462", -"$ c #E0C056", -"% c #DBB53C", -"& c #FEFEFD", -"* c #FFFFFE", -"= c #FFFEFE", -"- c #FFFEFD", -"; c #FBF7EA", -"> c #E5C86E", -", c #E4C96F", -"' c #E7CF7D", -") c #E8D084", -"! c #DCB441", -"~ c #FEFCF7", -"{ c #F8E48E", -"] c #F5DE91", -"^ c #F5E09F", -"/ c #F6E1AC", -"( c #FEFBEF", -"_ c #FEFDF4", -": c #FEFCF3", -"< c #FEFCF1", -"[ c #FEFBEE", -"} c #FFFDFA", -"| c #E0BC58", -"1 c #DCAE40", -"2 c #FDFAF1", -"3 c #F5DE94", -"4 c #F4DC93", -"5 c #F2D581", -"6 c #EDCA6A", -"7 c #EACB6C", -"8 c #EFD385", -"9 c #EFD280", -"0 c #EFD07A", -"a c #EECF76", -"b c #EECF72", -"c c #FBF7E9", -"d c #DCB23E", -"e c #DBAD39", -"f c #FBF6E8", -"g c #EFD494", -"h c #EECE88", -"i c #E9C173", -"j c #F6E9C9", -"k c #FEFCF2", -"l c #FEFCF0", -"m c #DBAE3C", -"n c #DBA83B", -"o c #FFFDF8", -"p c #FFFDF6", -"q c #FFFCF5", -"r c #FCF6D8", -"s c #F8E694", -"t c #F7E385", -"u c #F6DF76", -"v c #F5DB68", -"w c #F4D85C", -"x c #FCF4D7", -"y c #DBA73B", -"z c #DBA33B", -"A c #FEFCF6", -"B c #FCF2C8", -"C c #FBEFB9", -"D c #FAECAC", -"E c #F9E89C", -"F c #F7E38B", -"G c #F6E07C", -"H c #F6DC6C", -"I c #F5D95D", -"J c #F4D64F", -"K c #F3D344", -"L c #FCF3D0", -"M c #DBA23B", -"N c #DB9D3C", -"O c #FDFAF2", -"P c #FAEDB3", -"Q c #F9E9A4", -"R c #F8E695", -"S c #F7E285", -"T c #F6DE76", -"U c #F5DB65", -"V c #F4D757", -"W c #F3D449", -"X c #F2D13B", -"Y c #F1CE30", -"Z c #FBF2CC", -"` c #DB9B3B", -" . c #DB973B", -".. c #FEFAEF", -"+. c #F9E9A1", -"@. c #F8E591", -"#. c #F7E181", -"$. c #F6DE72", -"%. c #F5DA63", -"&. c #F4D754", -"*. c #F3D347", -"=. c #F2D039", -"-. c #F1CD2E", -";. c #F0CB26", -">. c #FBF2CA", -",. c #DD9947", -"'. c #FAF1DE", -"). c #F4DDA8", -"!. c #F4DB9E", -"~. c #F3DA96", -"{. c #F3D88E", -"]. c #F3D786", -"^. c #F2D47F", -"/. c #F2D379", -"(. c #F1D272", -"_. c #F1D06C", -":. c #F1CF69", -"<. c #F8EAC2", -"[. c #DB953F", -"}. c #DB913E", -"|. c #D98C34", -"1. c #D98B34", -"2. c #DA8F39", -" ", -" ", -" . + @ @ @ # $ ", -" % & * = - * ; > , , , ' ) ", -" ! ~ { ] ^ / ( _ : < ( [ } | ", -" 1 2 3 4 5 6 7 8 9 0 a b c d ", -" e f g h i j k : k l ( [ * m ", -" n * o p q : r s t u v w x y ", -" z A B C D E F G H I J K L M ", -" N O P Q R S T U V W X Y Z ` ", -" N O P Q R S T U V W X Y Z ` ", -" ...+.@.#.$.%.&.*.=.-.;.>. . ", -" ,.'.).!.~.{.].^./.(._.:.<.[. ", -" ,.}.|.|.|.|.|.|.|.|.1.2. ", -" ", -" "}; diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/file_save.xpm b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/file_save.xpm deleted file mode 100644 index 0f44467069..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/file_save.xpm +++ /dev/null @@ -1,168 +0,0 @@ -/* XPM */ -static const char * file_save_xpm[] = { -"16 16 149 2", -" c None", -". c #8DABD9", -"+ c #5E89C9", -"@ c #4375C0", -"# c #3A6EBD", -"$ c #376CBB", -"% c #366BBB", -"& c #366ABB", -"* c #396CBC", -"= c #3B6EBD", -"- c #3A6DBB", -"; c #4474BF", -"> c #658DC9", -", c #85A5D6", -"' c #D1E0F6", -") c #D1E0F7", -"! c #F8FBFE", -"~ c #F7FBFE", -"{ c #F6F9FD", -"] c #F0F5FC", -"^ c #EDF2FB", -"/ c #F7FAFD", -"( c #EBF1FB", -"_ c #DFE9F8", -": c #BED1EC", -"< c #6A92CD", -"[ c #5582C6", -"} c #D1DFF6", -"| c #80AAE9", -"1 c #F6FAFE", -"2 c #F6FAFD", -"3 c #648CC8", -"4 c #EEF3FB", -"5 c #F2F6FC", -"6 c #F1F6FC", -"7 c #E2ECF9", -"8 c #DBE7F8", -"9 c #BAD0EE", -"0 c #BDD0EC", -"a c #4374BD", -"b c #4274C0", -"c c #D0DFF6", -"d c #7EA8E8", -"e c #E9F1FA", -"f c #E8F0FA", -"g c #DDE8F8", -"h c #DBE6F7", -"i c #7AA3E1", -"j c #C3D5EF", -"k c #366AB7", -"l c #CCDDF5", -"m c #7EA8E7", -"n c #668DC9", -"o c #E9F0FA", -"p c #F8FAFE", -"q c #EFF4FC", -"r c #DFE9F9", -"s c #DBE7F7", -"t c #D9E5F7", -"u c #78A2E0", -"v c #A9C2E7", -"w c #3568B6", -"x c #C9DCF4", -"y c #7DA7E7", -"z c #E1ECF9", -"A c #E3EDF9", -"B c #EEF4FC", -"C c #F3F7FD", -"D c #E5EDFA", -"E c #D8E5F6", -"F c #77A0DE", -"G c #A4BEE4", -"H c #3467B4", -"I c #C7D9F4", -"J c #7DA6E6", -"K c #678EC9", -"L c #6C92CB", -"M c #6990CA", -"N c #658CC8", -"O c #749CDA", -"P c #9FBAE1", -"Q c #3466B3", -"R c #C5D8F2", -"S c #7BA4E3", -"T c #7AA3E3", -"U c #7AA4E3", -"V c #7BA4E2", -"W c #7BA3E2", -"X c #79A2E1", -"Y c #77A0DF", -"Z c #769FDE", -"` c #749EDD", -" . c #729CDB", -".. c #749DDC", -"+. c #9AB5DD", -"@. c #3465B1", -"#. c #BED2F0", -"$. c #7AA3E2", -"%. c #7BA3E1", -"&. c #779FDE", -"*. c #769FDD", -"=. c #729BD9", -"-. c #7199D8", -";. c #7099D6", -">. c #8EABD5", -",. c #3363AD", -"'. c #366ABA", -"). c #BBD0EF", -"!. c #7AA2E2", -"~. c #6D96D3", -"{. c #8AA7D2", -"]. c #3262AB", -"^. c #386BBB", -"/. c #B8CEEF", -"(. c #F7FAFE", -"_. c #88C062", -":. c #6A93CF", -"<. c #84A3CE", -"[. c #3261AA", -"}. c #386CBB", -"|. c #B6CCEE", -"1. c #7AA2E1", -"2. c #C2DCBF", -"3. c #6890CD", -"4. c #819ECC", -"5. c #3261A8", -"6. c #386CBA", -"7. c #B3CAED", -"8. c #7AA2E0", -"9. c #658DCA", -"0. c #7C9BC9", -"a. c #3261A7", -"b. c #4F7DC3", -"c. c #ADC6EB", -"d. c #ADC5EA", -"e. c #7C9AC8", -"f. c #7998C7", -"g. c #406BAD", -"h. c #7095CD", -"i. c #4273BD", -"j. c #3568B7", -"k. c #3568B5", -"l. c #3466B2", -"m. c #3364AE", -"n. c #3263AC", -"o. c #3262AA", -"p. c #3261A9", -"q. c #3160A8", -"r. c #3C69AB", -" . + @ # $ % & * = - ; > ", -" , ' ) ! ~ { ] ^ { / ( _ : < ", -" [ } | 1 2 3 4 5 ! 6 7 8 9 0 a ", -" b c d 6 6 3 e / { f g h i j k ", -" # l m f f n o p q r s t u v w ", -" $ x y z z A B C D s t E F G H ", -" % I J 3 > K L M N 3 3 3 O P Q ", -" & R S T U V W X Y Z ` ...+.@.", -" & #.$.$.i W %.&.*...=.-.;.>.,.", -" '.).!.! ! ! ! ! ! ! ! ! ~.{.].", -" ^./.X (._._._._._._._.{ :.<.[.", -" }.|.1.(.2.2.2.2.2.2.2.{ 3.4.5.", -" 6.7.8.(._._._._._._._.{ 9.0.a.", -" b.c.d.! ! ! ! ! ! ! ! ! e.f.g.", -" h.i.j.k.H l.m.n.o.p.q.a.r. ", -" "}; diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/gear.xpm b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/gear.xpm deleted file mode 100644 index edebbc4367..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/gear.xpm +++ /dev/null @@ -1,24 +0,0 @@ -/* XPM */ -static const char * gear_xpm[] = { -/* columns rows colors chars-per-pixel */ -"16 16 2 1", -" c #000000", -". c None", -/* pixels */ -"....... .......", -"....... .......", -".. .. .. ..", -".. ..", -"... .... ...", -"... ...... ...", -".. ........ ..", -" ........ ", -" ........ ", -".. ........ ..", -"... ...... ...", -"... .... ...", -".. ..", -".. .. .. ..", -"....... .......", -"....... ......." -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/wWidgets_NOTICES.txt b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/wWidgets_NOTICES.txt deleted file mode 100644 index 5e8ea4b43e..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/wWidgets_NOTICES.txt +++ /dev/null @@ -1,49 +0,0 @@ -Portions based on WWidgets and Yasli Serialization Library - -wWidgets - Lightweight UI Toolkit. -Copyright (C) 2009-2011 Evgeny Andreeshchev - Alexander Kotliar - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - - -Yasli Serialization Library -Copyright (c) 2007 Eugene Andreeshchev - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/warning.xpm b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/warning.xpm deleted file mode 100644 index 84626cbd9c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/warning.xpm +++ /dev/null @@ -1,134 +0,0 @@ -/* XPM */ -static const char * warning_xpm[] = { -"16 16 115 2", -" c None", -". c #EBBC3C", -"+ c #EABA3A", -"@ c #F1D485", -"# c #F0D182", -"$ c #E7B537", -"% c #E9BA3A", -"& c #FDFAF1", -"* c #FAEFD5", -"= c #E6B235", -"- c #E9B93A", -"; c #F2D894", -"> c #FEFCF3", -", c #FEFAE7", -"' c #F0D38F", -") c #E3AC31", -"! c #E8B738", -"~ c #FFFDF9", -"{ c #F9E994", -"] c #FAEB9E", -"^ c #FEFAEC", -"/ c #E1A92F", -"( c #F4DFA9", -"_ c #FDF9ED", -": c #D6A33E", -"< c #FCF5D4", -"[ c #F1D7A2", -"} c #DEA32B", -"| c #E6B436", -"1 c #EDC871", -"2 c #FFFEF9", -"3 c #F4DC5E", -"4 c #D5A23E", -"5 c #F4D95C", -"6 c #FEFBED", -"7 c #E5BB68", -"8 c #D99924", -"9 c #F7EAC8", -"0 c #FDFAE6", -"a c #F4DA5D", -"b c #D5A13D", -"c c #F2D757", -"d c #FCF3C7", -"e c #F4E3C0", -"f c #E6B336", -"g c #F0D28C", -"h c #FEFBEA", -"i c #F8E694", -"j c #F4DA5C", -"k c #DDB147", -"l c #F2D756", -"m c #F5DB5C", -"n c #FDF8DE", -"o c #E7C07D", -"p c #D48E1D", -"q c #E5B134", -"r c #FEFBF3", -"s c #FBF2C3", -"t c #F6DC5C", -"u c #F6DF64", -"v c #EBCB57", -"w c #F2D655", -"x c #F5D954", -"y c #F8E794", -"z c #FBF4E3", -"A c #D08717", -"B c #E5B034", -"C c #F1D79D", -"D c #FDF9E7", -"E c #F8E58B", -"F c #F6DB5A", -"G c #F4DA5B", -"H c #F2D654", -"I c #F5D852", -"J c #F4D650", -"K c #FCF6D8", -"L c #E5BF88", -"M c #C9790E", -"N c #E3AD31", -"O c #E8BF62", -"P c #FEFCF4", -"Q c #FAEFB5", -"R c #F5DA58", -"S c #F3D857", -"T c #F2D758", -"U c #F2D658", -"V c #F4D957", -"W c #F5D851", -"X c #F4D74E", -"Y c #F6DA62", -"Z c #D29344", -"` c #C36D06", -" . c #F5E3BE", -".. c #FEFBEF", -"+. c #FEFBEE", -"@. c #FEFCEF", -"#. c #FEFBEC", -"$. c #FEFCF2", -"%. c #EBCEAB", -"&. c #C16803", -"*. c #E2AA2F", -"=. c #E0A72D", -"-. c #DFA42B", -";. c #DDA129", -">. c #DC9E27", -",. c #DA9B25", -"'. c #D99823", -"). c #D69320", -"!. c #D38C1B", -"~. c #CF8516", -"{. c #CC7E11", -"]. c #C9770D", -"^. c #C67109", -"/. c #C36C06", -"(. c #BF6400", -" ", -" . + ", -" . @ # $ ", -" % & * = ", -" - ; > , ' ) ", -" ! ~ { ] ^ / ", -" ! ( _ : : < [ } ", -" | 1 2 3 4 4 5 6 7 8 ", -" | 9 0 a b b c d e 8 ", -" f g h i j k b l m n o p ", -" q r s t j u v w x y z A ", -" B C D E F G b b H I J K L M ", -"N O P Q R R S T U V W X Y h Z ` ", -"N .P ..+.+.@.@...+.6 6 #.$.%.&.", -"*.=.-.;.>.,.'.).!.~.{.].^./.&.(.", -" "}; diff --git a/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp b/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp deleted file mode 100644 index 36f9511e60..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp +++ /dev/null @@ -1,913 +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 "EditorCommon_precompiled.h" - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "QViewport.h" -#include "QViewportEvents.h" -#include "QViewportConsumer.h" -#include "QViewportSettings.h" -#include "Serialization.h" - -#include -#include -#include - -#include - -// Class to implement the WindowRequestBus::Handler instead of the QViewport class. -// This is to bypass a link warning that occurs in unity builds if EditorCommon dll -// is linked along with a gem that also implements WindowRequestBus::Handler. The -// issue is that QViewport has a dllexport so it causes duplicate code to be linked -// in and a warning that there will be two of the same symbol in memory -class QViewportRequests - : public AzFramework::WindowRequestBus::Handler -{ -public: - QViewportRequests(QViewport& viewport) - : m_viewport(viewport) - { - } - - ~QViewportRequests() override - { - AzFramework::WindowRequestBus::Handler::BusDisconnect(); - } - - // WindowRequestBus::Handler... - void SetWindowTitle(const AZStd::string& title) override - { - m_viewport.SetWindowTitle(title); - } - - AzFramework::WindowSize GetClientAreaSize() const override - { - return m_viewport.GetClientAreaSize(); - } - - void ResizeClientArea(AzFramework::WindowSize clientAreaSize) override - { - m_viewport.ResizeClientArea(clientAreaSize); - } - - bool GetFullScreenState() const override - { - return m_viewport.GetFullScreenState(); - } - - void SetFullScreenState(bool fullScreenState) override - { - m_viewport.SetFullScreenState(fullScreenState); - } - - bool CanToggleFullScreenState() const override - { - return m_viewport.CanToggleFullScreenState(); - } - - void ToggleFullScreenState() override - { - m_viewport.ToggleFullScreenState(); - } - -private: - QViewport& m_viewport; -}; - -struct QViewport::SPreviousContext -{ - CCamera renderCamera; - CCamera systemCamera; - int width; - int height; - HWND window; - bool isMainViewport; -}; - -struct QViewport::SPrivate -{ - CDLight m_VPLight0; - CDLight m_sun; -}; - -QViewport::QViewport(QWidget* parent, StartupMode startupMode) - : QWidget(parent) - , m_renderContextCreated(false) - , m_updating(false) - , m_width(0) - , m_height(0) - , m_fastMode(false) - , m_slowMode(false) - , m_lastTime(0) - , m_lastFrameTime(0.0f) - , m_averageFrameTime(0.0f) - , m_sceneDimensions(1.0f, 1.0f, 1.0f) - , m_creatingRenderContext(false) - , m_timer(0) - , m_cameraSmoothPosRate(0) - , m_cameraSmoothRotRate(0) - , m_settings(new SViewportSettings()) - , m_state(new SViewportState()) - , m_useArrowsForNavigation(true) - , m_mouseMovementsSinceLastFrame(0) - , m_private(new SPrivate()) - , m_cameraControlMode(CameraControlMode::NONE) -{ - m_viewportRequests = AZStd::make_unique(*this); - - if (startupMode & StartupMode_Immediate) - Startup(); -} - -void QViewport::Startup() -{ - m_frameTimer = new QElapsedTimer(); - - m_camera.reset(new CCamera()); - ResetCamera(); - - m_mousePressPos = QCursor::pos(); - - UpdateBackgroundColor(); - - setUpdatesEnabled(false); - setMouseTracking(true); - m_LightRotationRadian = 0; - m_frameTimer->start(); -} - -QViewport::~QViewport() -{ - m_viewportRequests.reset(); -} - -void QViewport::UpdateBackgroundColor() -{ - QPalette pal(palette()); - pal.setColor(QPalette::Window, QColor(m_settings->background.topColor.r, - m_settings->background.topColor.g, - m_settings->background.topColor.b, - m_settings->background.topColor.a)); - setPalette(pal); - setAutoFillBackground(true); -} - -bool QViewport::ScreenToWorldRay(Ray* ray, int x, int y) -{ - AZ_UNUSED(ray); - AZ_UNUSED(x); - AZ_UNUSED(y); - return false; -} - -QPoint QViewport::ProjectToScreen(const Vec3&) -{ - return QPoint(0, 0); -} - -void QViewport::LookAt(const Vec3& target, float radius, bool snap) -{ - QuatT cameraTarget = m_state->cameraTarget; - CreateLookAt(target, radius, cameraTarget); - CameraMoved(cameraTarget, snap); -} - -int QViewport::Width() const -{ - return rect().width(); -} - -int QViewport::Height() const -{ - return rect().height(); -} - -void QViewport::Serialize(IArchive& ar) -{ - if (!ar.IsEdit()) - { - ar(m_state->cameraTarget, "cameraTarget", "Camera Target"); - } -} - -struct AutoBool -{ - AutoBool(bool* value) - : m_value(value) - { - * m_value = true; - } - - ~AutoBool() - { - * m_value = false; - } - - bool* m_value; -}; - -void QViewport::Update() -{ - int64 time = m_frameTimer->elapsed(); - if (m_lastTime == 0) - { - m_lastTime = time; - } - m_lastFrameTime = (time - m_lastTime) * 0.001f; - m_lastTime = time; - if (m_averageFrameTime == 0.0f) - { - m_averageFrameTime = m_lastFrameTime; - } - else - { - m_averageFrameTime = 0.01f * m_lastFrameTime + 0.99f * m_averageFrameTime; - } -} - -void QViewport::CaptureMouse() -{ - grabMouse(); -} - -void QViewport::ReleaseMouse() -{ - releaseMouse(); -} - -void QViewport::SetForegroundUpdateMode([[maybe_unused]] bool foregroundUpdate) -{ - //m_timer->setInterval(foregroundUpdate ? 2 : 50); -} - -CCamera* QViewport::Camera() const -{ - return m_camera.get(); -} - -void QViewport::SetSceneDimensions(const Vec3& size) -{ - m_sceneDimensions = size; -} - -const SViewportSettings& QViewport::GetSettings() const -{ - return *m_settings; -} - -const SViewportState& QViewport::GetState() const -{ - return *m_state; -} - -void QViewport::SetSize(const QSize& size) -{ - m_width = size.width(); - m_height = size.height(); -} - -float QViewport::GetLastFrameTime() -{ - return m_lastFrameTime; -} - - -void QViewport::ProcessMouse() -{ - QPoint point = mapFromGlobal(QCursor::pos()); - - if (point == m_mousePressPos) - { - return; - } - - if (m_cameraControlMode == CameraControlMode::ZOOM) - { - if (!(m_settings->camera.transformRestraint & eCameraTransformRestraint_Zoom)) - { - float speedScale = CalculateMoveSpeed(m_fastMode, m_slowMode, true); - - // Zoom. - QuatT qt = m_state->cameraTarget; - Vec3 ydir = qt.GetColumn1().GetNormalized(); - Vec3 pos = qt.t; - pos = pos - 0.2f * ydir * aznumeric_cast(m_mousePressPos.y() - point.y()) * speedScale; - qt.t = pos; - CameraMoved(qt, false); - - // Check to see if the orbit target is behind the camera's view - // position - Vec3 target = m_state->orbitTarget; - Vec3 at = target - pos; - float isAlmostBehind = at * ydir; - if (isAlmostBehind < 0.01f) - { - // Force the orbit target to be slightly in front of the view - // position - m_state->orbitRadius = 0.01f; - m_state->orbitTarget = qt.t + ydir * 0.01f; - } - else - { - m_state->orbitRadius = at.GetLength(); - } - - AzQtComponents::SetCursorPos(mapToGlobal(m_mousePressPos)); - } - } - else if (m_cameraControlMode == CameraControlMode::ROTATE) - { - if (!(m_settings->camera.transformRestraint & eCameraTransformRestraint_Rotation)) - { - Ang3 angles(aznumeric_cast(-point.y() + m_mousePressPos.y()), 0, aznumeric_cast(-point.x() + m_mousePressPos.x())); - angles = angles * 0.001f * m_settings->camera.rotationSpeed; - - QuatT qt = m_state->cameraTarget; - Ang3 ypr = CCamera::CreateAnglesYPR(Matrix33(qt.q)); - ypr.x += angles.z; - ypr.y += angles.x; - ypr.y = clamp_tpl(ypr.y, -1.5f, 1.5f); - - qt.q = Quat(CCamera::CreateOrientationYPR(ypr)); - - // Move the orbit target with the rotate operation. - float distanceFromTarget = (qt.t - m_state->orbitTarget).GetLength(); - Vec3 ydir = qt.GetColumn1().GetNormalized(); - m_state->orbitTarget = qt.t + ydir * distanceFromTarget; - - CameraMoved(qt, false); - - AzQtComponents::SetCursorPos(mapToGlobal(m_mousePressPos)); - } - } - else if (m_cameraControlMode == CameraControlMode::PAN) - { - if (!(m_settings->camera.transformRestraint & eCameraTransformRestraint_Panning)) - { - float speedScale = CalculateMoveSpeed(m_fastMode, m_slowMode, true) * 3; - speedScale = max(0.1f, speedScale); - - // Slide. - QuatT qt = m_state->cameraTarget; - Vec3 xdir = qt.GetColumn0().GetNormalized(); - Vec3 zdir = qt.GetColumn2().GetNormalized(); - - Vec3 delta = 0.0025f * xdir * aznumeric_cast(point.x() - m_mousePressPos.x()) * speedScale + 0.0025f * zdir * aznumeric_cast(m_mousePressPos.y() - point.y()) * speedScale; - qt.t += delta; - - // Move the orbit target with the pan operation. This ensures the - // center of the orbit moves with the camera as it pans. - m_state->orbitTarget += delta; - - CameraMoved(qt, false); - - AzQtComponents::SetCursorPos(mapToGlobal(m_mousePressPos)); - } - } - else if (m_cameraControlMode == CameraControlMode::ORBIT) - { - // Rotate around orbit target. - QuatT cameraTarget = m_state->cameraTarget; - Vec3 at = cameraTarget.t - m_state->orbitTarget; - float distanceFromTarget = at.GetLength(); - if (distanceFromTarget > 0.001f) - { - at /= distanceFromTarget; - } - else - { - at = Vec3(0.0f, m_state->orbitRadius, 0.0f); - distanceFromTarget = m_state->orbitRadius; - } - - Vec3 up = Vec3(0.0f, 0.0f, 1.0f); - const Vec3 right = at.Cross(up).GetNormalized(); - up = right.Cross(at).GetNormalized(); - - Ang3 angles = CCamera::CreateAnglesYPR(Matrix33::CreateFromVectors(right, at, up)); - const Ang3 delta = Ang3(aznumeric_cast(-point.y() + m_mousePressPos.y()), 0.0f, aznumeric_cast(-point.x() + m_mousePressPos.x())) * 0.002f * m_settings->camera.rotationSpeed; - angles.x += delta.z; - angles.y -= delta.x; - angles.y = clamp_tpl(angles.y, -1.5f, 1.5f); - - cameraTarget.t = m_state->orbitTarget + CCamera::CreateOrientationYPR(angles).TransformVector(Vec3(0.0f, distanceFromTarget, 0.0f)); - m_state->orbitRadius = distanceFromTarget; - - CameraMoved(cameraTarget, true); - - AzQtComponents::SetCursorPos(mapToGlobal(m_mousePressPos)); - } -} - -void QViewport::ProcessKeys() -{ - if (!m_renderContextCreated) - { - return; - } - - float deltaTime = m_lastFrameTime; - - if (deltaTime > 0.1f) - { - deltaTime = 0.1f; - } - - QuatT qt = m_state->cameraTarget; - Vec3 ydir = qt.GetColumn1().GetNormalized(); - Vec3 xdir = qt.GetColumn0().GetNormalized(); - Vec3 pos = qt.t; - - float moveSpeed = CalculateMoveSpeed(m_fastMode, m_slowMode); - bool hasPressedKey = false; - - if ((m_useArrowsForNavigation && CheckVirtualKey(Qt::Key_Up)) || CheckVirtualKey(Qt::Key_W)) - { - hasPressedKey = true; - Vec3 delta = deltaTime * moveSpeed * ydir; - qt.t += delta; - m_state->orbitTarget += delta; - CameraMoved(qt, false); - } - - if ((m_useArrowsForNavigation && CheckVirtualKey(Qt::Key_Down)) || CheckVirtualKey(Qt::Key_S)) - { - hasPressedKey = true; - Vec3 delta = deltaTime * moveSpeed * ydir; - qt.t -= delta; - m_state->orbitTarget -= delta; - CameraMoved(qt, false); - } - - if (m_cameraControlMode != CameraControlMode::ORBIT && ((m_useArrowsForNavigation && CheckVirtualKey(Qt::Key_Left)) || CheckVirtualKey(Qt::Key_A))) - { - hasPressedKey = true; - Vec3 delta = deltaTime * moveSpeed * xdir; - qt.t -= delta; - m_state->orbitTarget -= delta; - CameraMoved(qt, false); - } - - if (m_cameraControlMode != CameraControlMode::ORBIT && ((m_useArrowsForNavigation && CheckVirtualKey(Qt::Key_Right)) || CheckVirtualKey(Qt::Key_D))) - { - hasPressedKey = true; - Vec3 delta = deltaTime * moveSpeed * xdir; - qt.t += delta; - m_state->orbitTarget += delta; - CameraMoved(qt, false); - } - - if (CheckVirtualKey(Qt::RightButton) | CheckVirtualKey(Qt::MiddleButton)) - { - hasPressedKey = true; - } -} - -void QViewport::CameraMoved(QuatT qt, bool snap) -{ - if (m_cameraControlMode == CameraControlMode::ORBIT) - { - CreateLookAt(m_state->orbitTarget, m_state->orbitRadius, qt); - } - m_state->cameraTarget = qt; - if (snap) - { - m_state->lastCameraTarget = qt; - } - SignalCameraMoved(qt); -} - -void QViewport::OnKeyEvent(const SKeyEvent& ev) -{ - for (size_t i = 0; i < m_consumers.size(); ++i) - { - m_consumers[i]->OnViewportKey(ev); - } - SignalKey(ev); -} - -void QViewport::OnMouseEvent(const SMouseEvent& ev) -{ - if (ev.type == SMouseEvent::EType::TYPE_MOVE) - { - // Make sure we don't process more than one mouse event per frame, so we don't - // end up consuming all the "idle" time - ++m_mouseMovementsSinceLastFrame; - - if (m_mouseMovementsSinceLastFrame > 1) - { - // we can't discard all movement events, the last one should be delivered. - m_pendingMouseMoveEvent = ev; - return; - } - } - - for (size_t i = 0; i < m_consumers.size(); ++i) - { - m_consumers[i]->OnViewportMouse(ev); - } - SignalMouse(ev); -} - -void QViewport::PreRender() -{ - SRenderContext rc; - rc.camera = m_camera.get(); - rc.viewport = this; - - SignalPreRender(rc); - - - const float fov = DEG2RAD(m_settings->camera.fov); - const float fTime = m_lastFrameTime; - float lastRotWeight = 0.0f; - - QuatT targetTM = m_state->cameraTarget; - QuatT currentTM = m_state->lastCameraTarget; - - if ((targetTM.t - currentTM.t).len() > 0.0001f) - { - SmoothCD(currentTM.t, m_cameraSmoothPosRate, fTime, targetTM.t, m_settings->camera.smoothPos); - } - else - { - m_cameraSmoothPosRate = Vec3(0); - } - - SmoothCD(lastRotWeight, m_cameraSmoothRotRate, fTime, 1.0f, m_settings->camera.smoothRot); - - if (lastRotWeight >= 1.0f) - { - m_cameraSmoothRotRate = 0.0f; - } - - currentTM = QuatT(Quat::CreateNlerp(currentTM.q, targetTM.q, lastRotWeight), currentTM.t); - - m_state->lastCameraParentFrame = m_state->cameraParentFrame; - m_state->lastCameraTarget = currentTM; - - m_camera->SetFrustum(m_width, m_height, fov, m_settings->camera.nearClip); - m_camera->SetMatrix(Matrix34(m_state->cameraParentFrame * currentTM)); -} - -void QViewport::Render() -{ -} - -void QViewport::RenderInternal() -{ -} - -void QViewport::SetWindowTitle(const AZStd::string& title) -{ - // Do not support the WindowRequestBus changing the editor window title - AZ_UNUSED(title); -} - -AzFramework::WindowSize QViewport::GetClientAreaSize() const -{ - const QWidget* window = this->window(); - QSize windowSize = window->size(); - return AzFramework::WindowSize(windowSize.width(), windowSize.height()); -} - -void QViewport::ResizeClientArea(AzFramework::WindowSize clientAreaSize) -{ - QWidget* window = this->window(); - window->resize(aznumeric_cast(clientAreaSize.m_width), aznumeric_cast(clientAreaSize.m_height)); -} - -bool QViewport::GetFullScreenState() const -{ - // QViewport does not currently support full screen. - return false; -} - -void QViewport::SetFullScreenState([[maybe_unused]]bool fullScreenState) -{ - // QViewport does not currently support full screen. -} - -bool QViewport::CanToggleFullScreenState() const -{ - // QViewport does not currently support full screen. - return false; -} - -void QViewport::ToggleFullScreenState() -{ - // QViewport does not currently support full screen. -} - -void QViewport::ResetCamera() -{ - *m_state = SViewportState(); - m_camera->SetMatrix(Matrix34(m_state->cameraTarget)); -} - -void QViewport::SetSettings(const SViewportSettings& settings) -{ - *m_settings = settings; -} - -void QViewport::SetState(const SViewportState& state) -{ - *m_state = state; -} - -float QViewport::CalculateMoveSpeed(bool shiftPressed, bool ctrlPressed, bool scaleWithOrbitDistance) const -{ - // The value used to caculate speedScale respects the value used in RenderViewPort. - // Please refer to the function: CRenderViewport::ProcessKeys().-- Vera, Confetti - float speedScale = 20; - - speedScale *= m_settings->camera.moveSpeed; - - float moveSpeed = speedScale; - - if (shiftPressed) - { - moveSpeed *= m_settings->camera.fastMoveMultiplier; - } - if (ctrlPressed) - { - moveSpeed *= m_settings->camera.slowMoveMultiplier; - } - if (scaleWithOrbitDistance) - { - // Slow the movement down as we get closer to the orbit target - QuatT qt = m_state->cameraTarget; - float distanceFromTarget = (qt.t - m_state->orbitTarget).GetLength(); - moveSpeed *= distanceFromTarget * 0.01f; - // Prevent the speed from going too close to 0, which would prevent movement - moveSpeed = max(0.001f, moveSpeed); - } - - return moveSpeed; -} - -void QViewport::CreateLookAt(const Vec3& target, float radius, QuatT& cameraTarget) const -{ - Vec3 at = target - cameraTarget.t; - float distanceFromTarget = at.GetLength(); - if (distanceFromTarget > 0.001f) - { - at /= distanceFromTarget; - } - else - { - at = Vec3(0.0f, radius, 0.0f); - distanceFromTarget = radius; - } - if (distanceFromTarget < radius) - { - distanceFromTarget = radius; - cameraTarget.t = target - (at * radius); - } - Vec3 up = Vec3(0.0f, 0.0f, 1.0f); - const Vec3 right = at.Cross(up).GetNormalized(); - up = right.Cross(at).GetNormalized(); - cameraTarget.q = Quat(Matrix33::CreateFromVectors(right, at, up)); -} - -void QViewport::UpdateCameraControlMode(QMouseEvent* ev) -{ - Qt::MouseButton mouseButton = ev->button(); - Qt::KeyboardModifiers modifiers = ev->modifiers(); - if (mouseButton & Qt::RightButton && mouseButton & Qt::MiddleButton) - { - m_cameraControlMode = CameraControlMode::ZOOM; - } - else if (mouseButton == Qt::MiddleButton) - { - if (modifiers & Qt::ALT) - { - m_cameraControlMode = CameraControlMode::ORBIT; - } - else - { - if (m_cameraControlMode == CameraControlMode::ROTATE) - { - m_cameraControlMode = CameraControlMode::ZOOM; - } - else - { - m_cameraControlMode = CameraControlMode::PAN; - } - } - } - else if (mouseButton == Qt::RightButton) - { - if (m_cameraControlMode == CameraControlMode::PAN || (modifiers & Qt::ALT)) - { - m_cameraControlMode = CameraControlMode::ZOOM; - } - else - { - m_cameraControlMode = CameraControlMode::ROTATE; - } - } - else - { - m_cameraControlMode = CameraControlMode::NONE; - } -} - -void QViewport::mousePressEvent(QMouseEvent* ev) -{ - SMouseEvent me; - me.type = SMouseEvent::TYPE_PRESS; - me.button = SMouseEvent::EButton(ev->button()); - me.x = ev->x(); - me.y = ev->y(); - me.viewport = this; - me.shift = (ev->modifiers() & Qt::SHIFT) != 0; - me.control = (ev->modifiers() & Qt::CTRL) != 0; - OnMouseEvent(me); - - QWidget::mousePressEvent(ev); - setFocus(); - - m_mousePressPos = ev->pos(); - - UpdateCameraControlMode(ev); - if (m_cameraControlMode != CameraControlMode::NONE) - { - QApplication::setOverrideCursor(Qt::BlankCursor); - } -} - -void QViewport::mouseReleaseEvent(QMouseEvent* ev) -{ - SMouseEvent me; - me.type = SMouseEvent::TYPE_RELEASE; - me.button = SMouseEvent::EButton(ev->button()); - me.x = ev->x(); - me.y = ev->y(); - me.viewport = this; - OnMouseEvent(me); - - m_cameraControlMode = CameraControlMode::NONE; - QWidget::mouseReleaseEvent(ev); - QApplication::restoreOverrideCursor(); -} - -void QViewport::wheelEvent(QWheelEvent* ev) -{ - QuatT qt = m_state->cameraTarget; - Vec3 ydir = qt.GetColumn1().GetNormalized(); - Vec3 pos = qt.t; - const float wheelSpeed = m_settings->camera.zoomSpeed * (m_fastMode ? m_settings->camera.fastMoveMultiplier : 1.0f) * (m_slowMode ? m_settings->camera.slowMoveMultiplier : 1.0f); - pos += 0.01f * ydir * aznumeric_cast(ev->angleDelta().y()) * wheelSpeed; - qt.t = pos; - CameraMoved(qt, false); -} - -void QViewport::mouseMoveEvent(QMouseEvent* ev) -{ - SMouseEvent me; - me.type = SMouseEvent::TYPE_MOVE; - me.button = SMouseEvent::EButton(ev->button()); - me.x = ev->x(); - me.y = ev->y(); - me.viewport = this; - m_fastMode = (ev->modifiers() & Qt::SHIFT) != 0; - m_slowMode = (ev->modifiers() & Qt::CTRL) != 0; - OnMouseEvent(me); - - QWidget::mouseMoveEvent(ev); -} - -void QViewport::keyPressEvent(QKeyEvent* ev) -{ - SKeyEvent event; - event.type = SKeyEvent::TYPE_PRESS; - event.key = ev->key() | ev->modifiers(); - m_fastMode = (ev->modifiers() & Qt::SHIFT) != 0; - m_slowMode = (ev->modifiers() & Qt::CTRL) != 0; - OnKeyEvent(event); - - QWidget::keyPressEvent(ev); -} - -void QViewport::keyReleaseEvent(QKeyEvent* ev) -{ - SKeyEvent event; - event.type = SKeyEvent::TYPE_RELEASE; - event.key = ev->key() | ev->modifiers(); - m_fastMode = (ev->modifiers() & Qt::SHIFT) != 0; - m_slowMode = (ev->modifiers() & Qt::CTRL) != 0; - OnKeyEvent(event); - QWidget::keyReleaseEvent(ev); -} - -void QViewport::resizeEvent(QResizeEvent* ev) -{ - QWidget::resizeEvent(ev); - -#if defined(AZ_PLATFORM_WINDOWS) - // Needed for high DPI mode on windows - const qreal ratio = devicePixelRatioF(); -#else - const qreal ratio = 1.0f; -#endif - int cx = aznumeric_cast(ev->size().width() * ratio); - int cy = aznumeric_cast(ev->size().height() * ratio); - if (cx == 0 || cy == 0) - { - return; - } - - m_width = cx; - m_height = cy; - - GetIEditor()->GetEnv()->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_RESIZE, cx, cy); - SignalUpdate(); - Update(); -} - -void QViewport::showEvent(QShowEvent* ev) -{ - QWidget::showEvent(ev); -} - -void QViewport::moveEvent(QMoveEvent* ev) -{ - QWidget::moveEvent(ev); - - GetIEditor()->GetEnv()->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_MOVE, ev->pos().x(), ev->pos().y()); -} - -bool QViewport::event(QEvent* ev) -{ - bool result = QWidget::event(ev); - - if (ev->type() == QEvent::ShortcutOverride) - { - // When a shortcut is matched, Qt's event processing sends out a shortcut override event - // to allow other systems to override it. If it's not overridden, then the key events - // get processed as a shortcut, even if the widget that's the target has a keyPress event - // handler. So, we need to communicate that we've processed the shortcut override - // which will tell Qt not to process it as a shortcut and instead pass along the - // keyPressEvent. - - QKeyEvent* keyEvent = static_cast(ev); - QKeySequence key(keyEvent->key() | keyEvent->modifiers()); - - for (size_t i = 0; i < m_consumers.size(); ++i) - { - if (m_consumers[i]->ProcessesViewportKey(key)) - { - ev->accept(); - return true; - } - } - } - - return result; -} - -void QViewport::paintEvent(QPaintEvent* ev) -{ - QWidget::paintEvent(ev); -} - -void QViewport::AddConsumer(QViewportConsumer* consumer) -{ - RemoveConsumer(consumer); - m_consumers.push_back(consumer); -} - -void QViewport::RemoveConsumer(QViewportConsumer* consumer) -{ - m_consumers.erase(std::remove(m_consumers.begin(), m_consumers.end(), consumer), m_consumers.end()); -} - -void QViewport::SetUseArrowsForNavigation(bool useArrowsForNavigation) -{ - m_useArrowsForNavigation = useArrowsForNavigation; -} - diff --git a/Code/Sandbox/Plugins/EditorCommon/QViewport.h b/Code/Sandbox/Plugins/EditorCommon/QViewport.h deleted file mode 100644 index 5566edc126..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QViewport.h +++ /dev/null @@ -1,193 +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 -#include - -#include -#include -#include "EditorCommonAPI.h" -#include "QViewportEvents.h" - -#include - -class CImageEx; -struct DisplayContext; -class CCamera; -struct SRenderingPassInfo; -struct SRendParams; -struct Ray; -struct IRenderer; -struct SSystemGlobalEnvironment; -namespace Serialization { - class IArchive; -} -using Serialization::IArchive; -using std::unique_ptr; - -struct SKeyEvent; -struct SMouseEvent; -struct SViewportSettings; -struct SViewportState; -class QElapsedTimer; -class QViewportRequests; - -class EDITOR_COMMON_API QViewport; -struct SRenderContext -{ - CCamera* camera; - QViewport* viewport; - SRendParams* renderParams; - SRenderingPassInfo* passInfo; -}; - -enum class CameraControlMode -{ - NONE, - PAN, - ROTATE, - ZOOM, - ORBIT -}; - - -class QViewportConsumer; -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING -class EDITOR_COMMON_API QViewport - : public QWidget -{ - Q_OBJECT -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING -public: - - enum StartupMode { - StartupMode_Immediate = 1, // Startup() will be called by QViewport's CTOR - StartupMode_Manual // Startup() will be called by the derived class - }; - - explicit QViewport(QWidget* parent, StartupMode startupMode = StartupMode_Immediate); - virtual ~QViewport(); - void Startup(); - - void AddConsumer(QViewportConsumer* consumer); - void RemoveConsumer(QViewportConsumer* consumer); - - void CaptureMouse(); - void ReleaseMouse(); - void SetForegroundUpdateMode(bool foregroundUpdate); - CCamera* Camera() const; - void ResetCamera(); - void Serialize(IArchive& ar); - - void SetUseArrowsForNavigation(bool useArrowsForNavigation); - void SetSceneDimensions(const Vec3& size); - void SetSettings(const SViewportSettings& settings); - const SViewportSettings& GetSettings() const; - void SetState(const SViewportState& state); - const SViewportState& GetState() const; - bool ScreenToWorldRay(Ray* ray, int x, int y); - QPoint ProjectToScreen(const Vec3& point); - void LookAt(const Vec3& target, float radius, bool snap); - - int Width() const; - int Height() const; - void SetSize(const QSize& size); - - // WindowRequestBus::Handler... (handler moved to cpp to resolve link issues in unity builds) - void SetWindowTitle(const AZStd::string& title); - AzFramework::WindowSize GetClientAreaSize() const; - void ResizeClientArea(AzFramework::WindowSize clientAreaSize); - bool GetFullScreenState() const; - void SetFullScreenState(bool fullScreenState); - bool CanToggleFullScreenState() const; - void ToggleFullScreenState(); - -public slots: - void Update(); -protected slots: - void RenderInternal(); -signals: - void SignalPreRender(const SRenderContext&); - void SignalRender(const SRenderContext&); - void SignalKey(const SKeyEvent&); - void SignalMouse(const SMouseEvent&); - void SignalUpdate(); - void SignalCameraMoved(const QuatT& qt); -protected: - void mousePressEvent(QMouseEvent* ev) override; - void mouseReleaseEvent(QMouseEvent* ev) override; - void wheelEvent(QWheelEvent* ev) override; - void mouseMoveEvent(QMouseEvent* ev) override; - void keyPressEvent(QKeyEvent* ev) override; - void keyReleaseEvent(QKeyEvent* ev) override; - void resizeEvent(QResizeEvent* ev) override; - void showEvent(QShowEvent* ev) override; - void moveEvent(QMoveEvent* ev) override; - void paintEvent(QPaintEvent* ev) override; - bool event(QEvent* ev) override; - - void CameraMoved(QuatT qt, bool snap); //Confetti: Jurecka ... making this protected so can adjust camera to focus on items in derived class. - - float GetLastFrameTime(); -private: - struct SPrivate; - -private: - void UpdateBackgroundColor(); - - void ProcessMouse(); - void ProcessKeys(); - void PreRender(); - void Render(); - void OnMouseEvent(const SMouseEvent& ev); - void OnKeyEvent(const SKeyEvent& ev); - float CalculateMoveSpeed(bool shiftPressed, bool ctrlPressed, bool scaleWithOrbitDistance = false) const; - void CreateLookAt(const Vec3& target, float radius, QuatT& cameraTarget) const; - void UpdateCameraControlMode(QMouseEvent* ev); - - struct SPreviousContext; - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - std::vector m_previousContexts; - std::unique_ptr m_camera; - QElapsedTimer* m_frameTimer; - QTimer* m_timer; - int m_width; - int m_height; - QPoint m_mousePressPos; - int64 m_lastTime; - float m_lastFrameTime; - float m_averageFrameTime; - bool m_useArrowsForNavigation; - bool m_renderContextCreated; - bool m_creatingRenderContext; - bool m_updating; - bool m_fastMode; - bool m_slowMode; - CameraControlMode m_cameraControlMode; - - Vec3 m_cameraSmoothPosRate; - float m_cameraSmoothRotRate; - int m_mouseMovementsSinceLastFrame; - f32 m_LightRotationRadian; - SMouseEvent m_pendingMouseMoveEvent; - - Vec3 m_sceneDimensions; - std::unique_ptr m_private; - std::unique_ptr m_settings; - std::unique_ptr m_state; - std::vector m_consumers; - AZStd::unique_ptr m_viewportRequests; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/QViewportConsumer.h b/Code/Sandbox/Plugins/EditorCommon/QViewportConsumer.h deleted file mode 100644 index 61d81b8dbf..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QViewportConsumer.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_EDITORCOMMON_QVIEWPORTCONSUMER_H -#define CRYINCLUDE_EDITORCOMMON_QVIEWPORTCONSUMER_H - -struct SRenderContext; -struct SKeyEvent; -struct SMouseEvent; -class QKeySequence; - -class QViewportConsumer -{ -public: - virtual ~QViewportConsumer() = default; - virtual void OnViewportRender([[maybe_unused]] const SRenderContext& rc) {} - - // If you're overriding OnViewportKey, you should also override ProcessesViewportKey and return true if you're interested in a particular key. - // If you don't, then registered shortcuts get keyPressed events first, and in many cases will never get passed to OnViewportKey - virtual void OnViewportKey([[maybe_unused]] const SKeyEvent& ev) {} - virtual bool ProcessesViewportKey([[maybe_unused]] const QKeySequence& key) { return false; } - - virtual void OnViewportMouse([[maybe_unused]] const SMouseEvent& ev) {} -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QVIEWPORTCONSUMER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QViewportEvents.h b/Code/Sandbox/Plugins/EditorCommon/QViewportEvents.h deleted file mode 100644 index 8e6e96c62d..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QViewportEvents.h +++ /dev/null @@ -1,96 +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_EDITORCOMMON_QVIEWPORTEVENTS_H -#define CRYINCLUDE_EDITORCOMMON_QVIEWPORTEVENTS_H -#pragma once - -#include "EditorCommonAPI.h" -class EDITOR_COMMON_API QViewport; - -struct SMouseEvent -{ - enum EType - { - TYPE_NONE, - TYPE_PRESS, - TYPE_RELEASE, - TYPE_MOVE - }; - - enum EButton - { - BUTTON_NONE, - BUTTON_LEFT, - BUTTON_RIGHT, - BUTTON_MIDDLE - }; - - EType type; - int x; - int y; - EButton button; - bool shift; - bool control; - QViewport* viewport; - - SMouseEvent() - : type(TYPE_NONE) - , x(INT_MIN) - , y(INT_MIN) - , button(BUTTON_NONE) - , viewport(0) - , shift(false) - , control(false) - { - } -}; - -struct SSelectionID -{ -}; - -struct SInteractionEvent -{ - enum EType - { - TYPE_NONE, - TYPE_ENTER, - TYPE_LEAVE, - TYPE_DRAG - }; - - SSelectionID selection; - Vec3 start; - Vec3 end; -}; - -struct SKeyEvent -{ - enum EType - { - TYPE_NONE, - TYPE_PRESS, - TYPE_RELEASE - }; - - EType type; - int key; - - SKeyEvent() - : type(TYPE_NONE) - { - } -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QVIEWPORTEVENTS_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QViewportSettings.h b/Code/Sandbox/Plugins/EditorCommon/QViewportSettings.h deleted file mode 100644 index 2a2111144e..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QViewportSettings.h +++ /dev/null @@ -1,269 +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_EDITORCOMMON_QVIEWPORTSETTINGS_H -#define CRYINCLUDE_EDITORCOMMON_QVIEWPORTSETTINGS_H -#pragma once - -#include -#include -#include "EditorCommonAPI.h" -#include "Serialization.h" -#include - -namespace Serialization -{ - class IArchive; -}; - -enum ECameraTransformRestraint -{ - eCameraTransformRestraint_Rotation = 0x01, - eCameraTransformRestraint_Panning = 0x02, - eCameraTransformRestraint_Zoom = 0x04 -}; - -struct SViewportState -{ - QuatT cameraTarget; - QuatT cameraParentFrame; - QuatT gridOrigin; - Vec3 gridCellOffset; - QuatT lastCameraTarget; - QuatT lastCameraParentFrame; - - Vec3 orbitTarget; - float orbitRadius; - - - SViewportState() - : cameraParentFrame(IDENTITY) - , gridOrigin(IDENTITY) - , gridCellOffset(0) - , lastCameraTarget(IDENTITY) - , lastCameraParentFrame(IDENTITY) - , orbitTarget(ZERO) - { - // This eye position is similar to Maya's initial camera position - AZ::Transform transform = AZ::Transform::CreateLookAt( - AZ::Vector3(-3.5f, 3.625f, 2.635f), // Eye position - AZ::Vector3(LYVec3ToAZVec3(orbitTarget)) - ); - cameraTarget = AZTransformToLYQuatT(transform); - orbitRadius = cameraTarget.t.GetLength(); - - lastCameraTarget = cameraTarget; - } -}; - -struct SViewportRenderingSettings -{ - bool wireframe; - bool sunlight; // Add setting for time of day feature - Vera, Confetti - bool fps; - - SViewportRenderingSettings() - : wireframe(false) - , fps(true) - , sunlight(false) - { - } - - void Serialize(Serialization::IArchive& ar) - { - ar(wireframe, "wireframe", "Wireframe"); - ar(fps, "fps", "Framerate"); - ar(sunlight, "sunlight", "Sunlight"); - } -}; - -struct SViewportCameraSettings -{ - bool showViewportOrientation; - - float fov; - float nearClip; - float smoothPos; - float smoothRot; - - float moveSpeed; - float rotationSpeed; - float zoomSpeed; - float fastMoveMultiplier; - float slowMoveMultiplier; - - int transformRestraint; - - SViewportCameraSettings() - : showViewportOrientation(true) - , fov(60) - , nearClip(0.01f) - , smoothPos(0.07f) - , smoothRot(0.05f) - , moveSpeed(0.7f) - , rotationSpeed(2.0f) - , zoomSpeed(0.1f) - , fastMoveMultiplier(3.0f) - , slowMoveMultiplier(0.1f) - , transformRestraint(0) - { - } - - void Serialize(Serialization::IArchive& ar) - { - ar(showViewportOrientation, "showViewportOrientation", "Show Viewport Orientation"); - ar(Serialization::Range(fov, 20.0f, 120.0f), "fov", "FOV"); - ar(Serialization::Range(nearClip, 0.01f, 0.5f), "nearClip", "Near Clip"); - ar(Serialization::Range(moveSpeed, 0.1f, 3.0f), "moveSpeed", "Move Speed"); - ar(transformRestraint, "TransformRestraint", "Transform Restraint"); - ar.Doc("Relative to the scene size"); - ar(Serialization::Range(rotationSpeed, 0.1f, 4.0f), "rotationSpeed", "Rotation Speed"); - ar.Doc("Degrees per 1000 px"); - if (ar.OpenBlock("movementSmoothing", "+Movement Smoothing")) - { - ar(smoothPos, "smoothPos", "Position"); - ar(smoothRot, "smoothRot", "Rotation"); - ar.CloseBlock(); - } - } -}; - - -struct SViewportGridSettings -{ - bool showGrid; - bool circular; - ColorB mainColor; - ColorB middleColor; - int alphaFalloff; - float spacing; - uint16 count; - uint16 interCount; - bool origin; - ColorB originColor; - - SViewportGridSettings() - : showGrid(true) - , circular(true) - , mainColor(255, 255, 255, 50) - , middleColor(255, 255, 255, 10) - , alphaFalloff(100) - , spacing(1.0f) - , count(10) - , interCount(10) - , origin(false) - , originColor(10, 10, 10, 255) - { - } - - void Serialize(Serialization::IArchive& ar) - { - ar(showGrid, "showGrid", "Show Grid"); - if (showGrid) - { - ar(circular, "circular", 0); - } - ar(mainColor, "mainColor", "Main Color"); - ar(middleColor, "middleColor", "Middle Color"); - ar(Serialization::Range(alphaFalloff, 0, 100), "alphaFalloff", 0); - ar(spacing, "spacing", "Spacing"); - ar(count, "count", "Main Lines"); - ar(interCount, "interCount", "Middle Lines"); - ar(origin, "origin", "Origin"); - ar(originColor, "originColor", origin ? "Origin Color" : 0); - } -}; - -struct SViewportLightingSettings -{ - f32 m_brightness; - ColorB m_ambientColor; - - bool m_useLightRotation; - f32 m_lightMultiplier; - f32 m_lightSpecMultiplier; - - ColorB m_directionalLightColor; - - SViewportLightingSettings() - { - m_brightness = 1.0f; - m_ambientColor = ColorB(128, 128, 128, 255); - - m_useLightRotation = 0; - m_lightMultiplier = 3.0; - m_lightSpecMultiplier = 2.0f; - - m_directionalLightColor = ColorB(255, 255, 255, 255); - } - - void Serialize(Serialization::IArchive& ar) - { - ar(Serialization::Range(m_brightness, 0.0f, 200.0f), "brightness", "Brightness"); - ar(m_ambientColor, "ambientColor", "Ambient Color"); - - ar(m_useLightRotation, "rotatelight", "Rotate Light"); - ar(m_lightMultiplier, "lightMultiplier", "Light Multiplier"); - ar(m_lightSpecMultiplier, "lightSpecMultiplier", "Light Spec Multiplier"); - - ar(m_directionalLightColor, "directionalLightColor", "Directional Light Color"); - } -}; - -struct SViewportBackgroundSettings -{ - bool useGradient; - ColorB topColor; - ColorB bottomColor; - - SViewportBackgroundSettings() - : useGradient(true) - , topColor(128, 128, 128, 255) - , bottomColor(32, 32, 32, 255) - { - } - - void Serialize(Serialization::IArchive& ar) - { - ar(useGradient, "useGradient", "Use Gradient"); - if (useGradient) - { - ar(topColor, "topColor", "Top Color"); - ar(bottomColor, "bottomColor", "Bottom Color"); - } - else - { - ar(topColor, "topColor", "Color"); - } - } -}; - -struct SViewportSettings -{ - SViewportRenderingSettings rendering; - SViewportCameraSettings camera; - SViewportGridSettings grid; - SViewportLightingSettings lighting; - SViewportBackgroundSettings background; - - void Serialize(Serialization::IArchive& ar) - { - ar(rendering, "debug", "Debug"); - ar(camera, "camera", "Camera"); - ar(grid, "grid", "Grid"); - ar(lighting, "lighting", "Lighting"); - ar(background, "background", "Background"); - } -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QVIEWPORTSETTINGS_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization.cpp b/Code/Sandbox/Plugins/EditorCommon/Serialization.cpp deleted file mode 100644 index 6d3db713c5..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization.cpp +++ /dev/null @@ -1,15 +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 "EditorCommon_precompiled.h" -#include "Serialization.h" diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization.h b/Code/Sandbox/Plugins/EditorCommon/Serialization.h deleted file mode 100644 index b017376355..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization.h +++ /dev/null @@ -1,44 +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 -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_H - -#include -#include - -namespace Serialization { - class IArchive; -} - -struct SkeletonAlias; -bool Serialize(Serialization::IArchive& ar, SkeletonAlias& value, const char* name, const char* label); - -#include -#include -#include -#include -using Serialization::BitFlags; -#include -#include -#include "Serialization/Decorators/ToggleButton.h" -#include "Serialization/Qt.h" -#include -#include - -#include - -using Serialization::IArchive; - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/BinArchive.cpp b/Code/Sandbox/Plugins/EditorCommon/Serialization/BinArchive.cpp deleted file mode 100644 index 9ee929ec55..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/BinArchive.cpp +++ /dev/null @@ -1,839 +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 "EditorCommon_precompiled.h" -#include "BinArchive.h" -#include -#include "Serialization/ClassFactory.h" - -namespace Serialization { - static const unsigned char SIZE16 = 254; - static const unsigned char SIZE32 = 255; - - static const unsigned int BIN_MAGIC = 0xb1a4c17f; - - //#ifdef _DEBUG - //typedef std::map HashMap; - //static HashMap hashMap; - //#endif - - BinOArchive::BinOArchive() - : IArchive(OUTPUT | BINARY) - { - clear(); - } - - void BinOArchive::clear() - { - stream_.clear(); - stream_.write((const char*)&BIN_MAGIC, sizeof(BIN_MAGIC)); - } - - size_t BinOArchive::length() const - { - return stream_.position(); - } - - bool BinOArchive::save(const char* filename) - { - FILE* f = nullptr; - azfopen(&f, filename, "wb"); - if (!f) - { - return false; - } - - if (fwrite(buffer(), 1, length(), f) != length()) - { - fclose(f); - return false; - } - - fclose(f); - return true; - } - - inline void BinOArchive::openNode(const char* name, bool size8) - { - if (!strlen(name)) - { - return; - } - - unsigned short hash = calcHash(name); - stream_.write(hash); - - blockSizeOffsets_.push_back(int(stream_.position())); - stream_.write((unsigned char)0); - if (!size8) - { - stream_.write((unsigned short)0); - } - -#ifdef _DEBUG - // HashMap::iterator i = hashMap.find(hash); - // if(i != hashMap.end() && i->second != name) - // ASSERT_STR(0, name); - // hashMap[hash] = name; -#endif - } - - inline void BinOArchive::closeNode(const char* name, bool size8) - { - if (!strlen(name)) - { - return; - } - - unsigned int offset = blockSizeOffsets_.back(); - unsigned int size = (unsigned int)(stream_.position() - offset - sizeof(unsigned char) - (size8 ? 0 : sizeof(unsigned short))); - blockSizeOffsets_.pop_back(); - unsigned char* sizePtr = (unsigned char*)(stream_.buffer() + offset); - - if (size < SIZE16) - { - *sizePtr = size; - if (!size8) - { - unsigned char* buffer = sizePtr + 3; - memmove(buffer - 2, buffer, size); - stream_.setPosition(stream_.position() - 2); - } - } - else - { - YASLI_ASSERT(!size8); - if (size < 0x10000) - { - *sizePtr = SIZE16; - *((unsigned short*)(sizePtr + 1)) = size; - } - else - { - unsigned char* buffer = sizePtr + 3; - stream_.write((unsigned short)0); - *sizePtr = SIZE32; - memmove(buffer + 2, buffer, size); - *((unsigned int*)(sizePtr + 1)) = size; - } - } - } - - bool BinOArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) - { - bool size8 = strlen(value.get()) + 1 < SIZE16; - openNode(name, size8); - stream_ << value.get(); - stream_.write(char(0)); - closeNode(name, size8); - return true; - } - - bool BinOArchive::operator()(IWString& value, const char* name, [[maybe_unused]] const char* label) - { - bool size8 = (wcslen(value.get()) + 1) * 2 < SIZE16; - openNode(name, size8); - stream_ << value.get(); - stream_.write(short(0)); - closeNode(name, size8); - return true; - } - - bool BinOArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) - { - openNode(name, false); - ser(*this); - closeNode(name, false); - return true; - } - - bool BinOArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) - { - openNode(name, false); - - unsigned int size = (unsigned int)ser.size(); - if (size < SIZE16) - { - stream_.write((unsigned char)size); - } - else if (size < 0x10000) - { - stream_.write(SIZE16); - stream_.write((unsigned short)size); - } - else - { - stream_.write(SIZE32); - stream_.write(size); - } - - if (strlen(name)) - { - if (size > 0) - { - int i = 0; - do - { - char elementName[16]; - azitoa(i++, elementName, AZ_ARRAY_SIZE(elementName), 10); - ser(*this, elementName, ""); - } while (ser.next()); - } - - closeNode(name, false); - } - else - { - if (size > 0) - { - do - { - ser(*this, "", ""); - } - while (ser.next()); - } - } - - return true; - } - - bool BinOArchive::operator()(IPointer& ptr, const char* name, [[maybe_unused]] const char* label) - { - openNode(name, false); - - const char* typeName = ptr.registeredTypeName(); - if (!typeName) - { - typeName = ""; - } - if (ptr.get() && typeName[0] == '\0') - { - CRY_ASSERT_MESSAGE(0, "Writing unregistered class. Use SERIALIZATION_CLASS_NAME macro for registration."); - } - - TypeID baseType = ptr.baseType(); - - if (ptr.get()) - { - stream_ << typeName; - stream_.write(char(0)); - ptr.serializer()(*this); - } - else - { - stream_.write(char(0)); - } - - closeNode(name, false); - return true; - } - - - ////////////////////////////////////////////////////////////////////////// - - BinIArchive::BinIArchive() - : IArchive(INPUT | BINARY) - , loadedData_(0) - { - } - - BinIArchive::~BinIArchive() - { - close(); - } - - bool BinIArchive::load(const char* filename) - { - close(); - - FILE* f = nullptr; - azfopen(&f, filename, "rb"); - if (!f) - { - return false; - } - fseek(f, 0, SEEK_END); - size_t length = ftell(f); - fseek(f, 0, SEEK_SET); - if (length == 0) - { - fclose(f); - return false; - } - loadedData_ = new char[length]; - if (fread((void*)loadedData_, 1, length, f) != length || !open(loadedData_, length)) - { - close(); - fclose(f); - return false; - } - fclose(f); - return true; - } - - bool BinIArchive::open(const char* buffer, size_t size) - { - if (size < sizeof(int)) - { - return false; - } - if (*(unsigned*)(buffer) != BIN_MAGIC) - { - return false; - } - buffer += sizeof(unsigned int); - size -= sizeof(unsigned int); - - blocks_.push_back(Block(buffer, (unsigned int)size)); - return true; - } - - void BinIArchive::close() - { - if (loadedData_) - { - delete [] loadedData_; - } - loadedData_ = 0; - } - - bool BinIArchive::openNode(const char* name) - { - Block block(0, 0); - if (currentBlock().get(name, block)) - { - blocks_.push_back(block); - return true; - } - return false; - } - - void BinIArchive::closeNode([[maybe_unused]] const char* name, [[maybe_unused]] bool check) - { - YASLI_ASSERT(!check || currentBlock().validToClose()); - blocks_.pop_back(); - } - - bool BinIArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - string str; - read(str); - value.set(str.c_str()); - return true; - } - - if (!openNode(name)) - { - return false; - } - - string str; - read(str); - value.set(str.c_str()); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(IWString& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - wstring str; - read(str); - value.set(str.c_str()); - return true; - } - - if (!openNode(name)) - { - return false; - } - - wstring str; - read(str); - value.set(str.c_str()); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - - bool BinIArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - ser(*this); - return true; - } - - if (!openNode(name)) - { - return false; - } - - ser(*this); - closeNode(name, false); - return true; - } - - bool BinIArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) - { - if (strlen(name)) - { - if (!openNode(name)) - { - return false; - } - - size_t size = currentBlock().readPackedSize(); - ser.resize(size); - - if (size > 0) - { - int i = 0; - do - { - char elementName[16]; - azitoa(i++, elementName, AZ_ARRAY_SIZE(elementName), 10); - ser(*this, elementName, ""); - } - while (ser.next()); - } - closeNode(name); - return true; - } - else - { - size_t size = currentBlock().readPackedSize(); - ser.resize(size); - if (size > 0) - { - do - { - ser(*this, "", ""); - } - while (ser.next()); - } - return true; - } - } - - bool BinIArchive::operator()(IPointer& ptr, const char* name, [[maybe_unused]] const char* label) - { - if (strlen(name) && !openNode(name)) - { - return false; - } - - string typeName; - read(typeName); - if (ptr.get() && (typeName.empty() || (typeName != ptr.registeredTypeName()))) - { - ptr.create(""); // 0 - } - if (!typeName.empty() && !ptr.get()) - { - ptr.create(typeName.c_str()); - } - - if (SStruct ser = ptr.serializer()) - { - ser(*this); - } - - if (strlen(name)) - { - closeNode(name); - } - return true; - } - - unsigned int BinIArchive::Block::readPackedSize() - { - unsigned char size8; - read(size8); - if (size8 < SIZE16) - { - return size8; - } - if (size8 == SIZE16) - { - unsigned short size16; - read(size16); - return size16; - } - unsigned int size32; - read(size32); - return size32; - } - - bool BinIArchive::Block::get(const char* name, Block& block) - { - if (begin_ == end_) - { - return false; - } - complex_ = true; - unsigned short hashName = calcHash(name); - const char* currInitial = curr_; - bool restarted = false; - for (;; ) - { - if (curr_ >= end_) - { - return false; - } - - unsigned short hash; - read(hash); - unsigned int size = readPackedSize(); - - const char* currPrev = curr_; - if ((curr_ += size) == end_) - { - if (restarted) - { - return false; - } - curr_ = begin_; - restarted = true; - } - - //ASSERT(curr_ < end_); - - if (hash == hashName) - { - block = Block(currPrev, size); - return true; - } - - if (curr_ == currInitial) - { - return false; - } - } - } -} diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/BinArchive.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/BinArchive.h deleted file mode 100644 index 09285bf2fc..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/BinArchive.h +++ /dev/null @@ -1,183 +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. - -// For tags 16-bit xor-hash is used, with check for uniquness in debug -// Block size is automatic: 8, 16 or 32 bits - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_BINARCHIVE_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_BINARCHIVE_H -#pragma once - -#include "Serialization/IArchive.h" -#include "MemoryWriter.h" -#include "EditorCommonAPI.h" - -namespace Serialization { - inline unsigned short calcHash(const char* str) - { - unsigned short hash = 0; - const unsigned short* p = (const unsigned short*)(str); - for (;; ) - { - unsigned short w = *p++; - if (!(w & 0xff)) - { - break; - } - hash ^= w; - if (!(w & 0xff00)) - { - break; - } - } - return hash; - } - - class BinOArchive - : public IArchive - { - public: - BinOArchive(); - ~BinOArchive() {} - - void clear(); - size_t length() const; - const char* buffer() const { return stream_.buffer(); } - bool save(const char* fileName); - - bool operator()(bool& value, const char* name, const char* label); - bool operator()(IString& value, const char* name, const char* label); - bool operator()(IWString& value, const char* name, const char* label); - bool operator()(float& value, const char* name, const char* label); - bool operator()(double& value, const char* name, const char* label); - bool operator()(int32& value, const char* name, const char* label); - bool operator()(uint32& value, const char* name, const char* label); - bool operator()(int16& value, const char* name, const char* label); - bool operator()(uint16& value, const char* name, const char* label); - bool operator()(int64& value, const char* name, const char* label); - bool operator()(uint64& value, const char* name, const char* label); - - bool operator()(int8& value, const char* name, const char* label); - bool operator()(uint8& value, const char* name, const char* label); - bool operator()(char& value, const char* name, const char* label); - - bool operator()(const SStruct& ser, const char* name, const char* label); - bool operator()(IContainer& ser, const char* name, const char* label); - bool operator()(IPointer& ptr, const char* name, const char* label); - - using IArchive::operator(); - - private: - void openContainer(const char* name, int size, const char* typeName); - void openNode(const char* name, bool size8 = true); - void closeNode(const char* name, bool size8 = true); - - std::vector blockSizeOffsets_; - MemoryWriter stream_; - }; - - ////////////////////////////////////////////////////////////////////////// - - class BinIArchive - : public IArchive - { - public: - BinIArchive(); - ~BinIArchive(); - - bool load(const char* fileName); - bool open(const char* buffer, size_t length); // doesn't copy the buffer - bool open(const BinOArchive& ar) { return open(ar.buffer(), ar.length()); } - void close(); - - bool operator()(bool& value, const char* name, const char* label); - bool operator()(IString& value, const char* name, const char* label); - bool operator()(IWString& value, const char* name, const char* label); - bool operator()(float& value, const char* name, const char* label); - bool operator()(double& value, const char* name, const char* label); - bool operator()(int16& value, const char* name, const char* label); - bool operator()(uint16& value, const char* name, const char* label); - bool operator()(int32& value, const char* name, const char* label); - bool operator()(uint32& value, const char* name, const char* label); - bool operator()(int64& value, const char* name, const char* label); - bool operator()(uint64& value, const char* name, const char* label); - - bool operator()(int8& value, const char* name, const char* label); - bool operator()(uint8& value, const char* name, const char* label); - bool operator()(char& value, const char* name, const char* label); - - bool operator()(const SStruct& ser, const char* name, const char* label); - bool operator()(IContainer& ser, const char* name, const char* label); - bool operator()(IPointer& ptr, const char* name, const char* label); - - using IArchive::operator(); - - private: - class Block - { - public: - Block(const char* data, int size) - : begin_(data) - , curr_(data) - , end_(data + size) - , complex_(false) {} - - bool get(const char* name, Block& block); - - void read(void* data, int size) - { - YASLI_ASSERT(curr_ + size <= end_); - memcpy(data, curr_, size); - curr_ += size; - } - - template - void read(T& x){ read(&x, sizeof(x)); } - - void read(string& s) - { - YASLI_ASSERT(curr_ + strlen(curr_) < end_); - s = curr_; - curr_ += strlen(curr_) + 1; - } - void read(wstring& s) - { - YASLI_ASSERT(curr_ + sizeof(wchar_t) * wcslen((wchar_t*)curr_) < end_); - s = (wchar_t*)curr_; - curr_ += (wcslen((wchar_t*)curr_) + 1) * sizeof(wchar_t); - } - - unsigned int readPackedSize(); - - bool validToClose() const { return complex_ || curr_ == end_; } - - private: - const char* begin_; - const char* end_; - const char* curr_; - bool complex_; - }; - - typedef std::vector Blocks; - Blocks blocks_; - const char* loadedData_; - - bool openNode(const char* name); - void closeNode(const char* name, bool check = true); - Block& currentBlock() { return blocks_.back(); } - template - void read(T& t) { currentBlock().read(t); } - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_BINARCHIVE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/EditorActionButton.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/EditorActionButton.h deleted file mode 100644 index 77d064203b..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/EditorActionButton.h +++ /dev/null @@ -1,76 +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 - -#include -#include -#include - -namespace Serialization -{ - typedef AZStd::function StdFunctionActionButtonCalback; - - struct StdFunctionActionButton - : public IActionButton - { - StdFunctionActionButtonCalback callback; - string icon; - - explicit StdFunctionActionButton(const StdFunctionActionButtonCalback& callback, const char* icon = "") - : callback(callback) - , icon(icon) - { - } - - // IActionButton - - virtual void Callback() const override - { - if (callback) - { - callback(); - } - } - - virtual const char* Icon() const override - { - return icon.c_str(); - } - - virtual IActionButtonPtr Clone() const override - { - return IActionButtonPtr(new StdFunctionActionButton(callback, icon.c_str())); - } - - // ~IActionButton - }; - - inline bool Serialize(Serialization::IArchive& ar, StdFunctionActionButton& button, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(static_cast(button)), name, label); - } - else - { - return false; - } - } - - inline StdFunctionActionButton ActionButton(const StdFunctionActionButtonCalback& callback, const char* icon = "") - { - return StdFunctionActionButton(callback, icon); - } -} - diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/IGizmoSink.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/IGizmoSink.h deleted file mode 100644 index c0d402e484..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/IGizmoSink.h +++ /dev/null @@ -1,49 +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_EDITORCOMMON_SERIALIZATION_DECORATORS_IGIZMOSINK_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_IGIZMOSINK_H -#pragma once - - -namespace Serialization { - struct LocalPosition; - struct LocalFrame; - struct LocalOrientation; - - struct GizmoFlags - { - bool visible; - bool selected; - - GizmoFlags() - : visible(true) - , selected(false) {} - }; - - struct IGizmoSink - { - virtual ~IGizmoSink() = default; - virtual int CurrentGizmoIndex() const = 0; - virtual int Write(const LocalPosition&, const GizmoFlags& flags, const void* handle) = 0; - virtual int Write(const LocalOrientation&, const GizmoFlags& flags, const void* handle) = 0; - virtual int Write(const LocalFrame&, const GizmoFlags& flags, const void* handle) = 0; - virtual void SkipRead() = 0; - virtual bool Read(LocalPosition* position, GizmoFlags* flags, const void* handle) = 0; - virtual bool Read(LocalOrientation* position, GizmoFlags* flags, const void* handle) = 0; - virtual bool Read(LocalFrame* position, GizmoFlags* flags, const void* handle) = 0; - virtual void Reset(const void* handle) = 0; - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_IGIZMOSINK_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/INavigationProvider.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/INavigationProvider.h deleted file mode 100644 index 8efe913c03..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/INavigationProvider.h +++ /dev/null @@ -1,43 +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_EDITORCOMMON_SERIALIZATION_DECORATORS_INAVIGATIONPROVIDER_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_INAVIGATIONPROVIDER_H -#pragma once - -namespace Serialization -{ - struct SNavigationContext - { - string path; - }; - - struct INavigationProvider - { - virtual ~INavigationProvider() = default; - virtual const char* GetIcon(const char* type, const char* path) const = 0; - virtual const char* GetFileSelectorMaskForType(const char* type) const = 0; - virtual const char* GetEngineTypeForInputType(const char* extension) const { return extension; } - virtual bool IsSelected(const char* type, const char* path, int index) const = 0; - virtual bool IsActive(const char* type, const char* path, int index) const = 0; - virtual bool IsModified(const char* type, const char* path, int index) const = 0; - virtual bool Select(const char* type, const char* path, int index) const = 0; - virtual bool CanSelect([[maybe_unused]] const char* type, [[maybe_unused]] const char* path, [[maybe_unused]] int index) const { return false; } - virtual bool CanPickFile([[maybe_unused]] const char* type, [[maybe_unused]] int index) const { return true; } - virtual bool CanCreate([[maybe_unused]] const char* type, [[maybe_unused]] int index) const { return false; } - virtual bool Create([[maybe_unused]] const char* type, [[maybe_unused]] const char* path, [[maybe_unused]] int index) const { return false; } - virtual bool IsRegistered([[maybe_unused]] const char* type) const { return false; } - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_INAVIGATIONPROVIDER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/IconXPM.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/IconXPM.h deleted file mode 100644 index 17154e3c6f..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/IconXPM.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_ICONXPM_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_ICONXPM_H -#pragma once - -namespace Serialization { - class IArchive; - - // Icon, stored in XPM format - struct IconXPM - { - const char* const* source; - int lineCount; - - IconXPM() - : source(0) - , lineCount(0) - { - } - template - explicit IconXPM(const char* (&xpm)[Size]) - { - source = xpm; - lineCount = Size; - } - - void Serialize([[maybe_unused]] Serialization::IArchive& ar) {} - bool operator<(const IconXPM& rhs) const { return source < rhs.source; } - }; - - struct IconXPMToggle - { - bool* variable_; - bool value_; - IconXPM iconTrue_; - IconXPM iconFalse_; - - template - IconXPMToggle(bool& variable, char* (&xpmTrue)[Size1], char* (&xpmFalse)[Size2]) - : iconTrue_(xpmTrue) - , iconFalse_(xpmFalse) - , variable_(&variable) - , value_(variable) - { - } - - IconXPMToggle(bool& variable, const IconXPM& iconTrue, const IconXPM& iconFalse) - : iconTrue_(iconTrue) - , iconFalse_(iconFalse) - , variable_(&variable) - , value_(variable) - { - } - - IconXPMToggle(const IconXPMToggle& orig) - : variable_(0) - , value_(orig.value_) - , iconTrue_(orig.iconTrue_) - , iconFalse_(orig.iconFalse_) - { - } - - IconXPMToggle() - : variable_(0) - { - } - IconXPMToggle& operator=(const IconXPMToggle& rhs) - { - value_ = rhs.value_; - return *this; - } - ~IconXPMToggle() - { - if (variable_) - { - * variable_ = value_; - } - } - - template - void Serialize(TArchive& ar) - { - ar(value_, "value", "Value"); - } - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_ICONXPM_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/ToggleButton.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/ToggleButton.h deleted file mode 100644 index dfbc210f87..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/ToggleButton.h +++ /dev/null @@ -1,50 +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_EDITORCOMMON_SERIALIZATION_DECORATORS_TOGGLEBUTTON_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_TOGGLEBUTTON_H -#pragma once - -namespace Serialization -{ - class IArchive; - - struct ToggleButton - { - bool* value; - - ToggleButton(bool& value) - : value(&value) - { - } - }; - - struct RadioButton - { - int* value; - int buttonValue; - - RadioButton(int& value, int buttonValue) - : value(&value) - , buttonValue(buttonValue) - { - } - }; - - bool Serialize(Serialization::IArchive& ar, Serialization::ToggleButton& button, const char* name, const char* label); - bool Serialize(Serialization::IArchive& ar, Serialization::RadioButton& button, const char* name, const char* label); -} - -#include "ToggleButtonImpl.h" - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_TOGGLEBUTTON_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/ToggleButtonImpl.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/ToggleButtonImpl.h deleted file mode 100644 index a691d1a33a..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/ToggleButtonImpl.h +++ /dev/null @@ -1,44 +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_EDITORCOMMON_SERIALIZATION_DECORATORS_TOGGLEBUTTONIMPL_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_TOGGLEBUTTONIMPL_H -#pragma once - -namespace Serialization -{ - inline bool Serialize(Serialization::IArchive& ar, Serialization::ToggleButton& button, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(button), name, label); - } - else - { - return ar(*button.value, name, label); - } - } - - inline bool Serialize(Serialization::IArchive& ar, Serialization::RadioButton& button, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(button), name, label); - } - else - { - return false; - } - } -} -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_TOGGLEBUTTONIMPL_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONIArchive.cpp b/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONIArchive.cpp deleted file mode 100644 index 874f70f581..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONIArchive.cpp +++ /dev/null @@ -1,1522 +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 "EditorCommon_precompiled.h" -#include -#include -#include -#include "Serialization/ClassFactory.h" -#include "Serialization/STL.h" -#include "JSONIArchive.h" -#include "Serialization/BlackBox.h" -#include "MemoryReader.h" -#include "MemoryWriter.h" - -#if 0 -# define DEBUG_TRACE(fmt, ...) printf(fmt "\n", __VA_ARGS__) -# define DEBUG_TRACE_TOKENIZER(fmt, ...) printf(fmt "\n", __VA_ARGS__) -#else -# define DEBUG_TRACE(...) -# define DEBUG_TRACE_TOKENIZER(...) -#endif - -namespace Serialization { - static char hexValueTable[256] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, - - 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - - static void unescapeString(std::vector& buf, string& out, const char* begin, const char* end) - { - if (begin >= end) - { - out.clear(); - return; - } - // TODO: use stack string - buf.resize(end - begin); - char* ptr = &buf[0]; - while (begin != end) - { - if (*begin != '\\') - { - *ptr = *begin; - ++ptr; - } - else - { - ++begin; - if (begin == end) - { - break; - } - - switch (*begin) - { - case '0': - *ptr = '\0'; - ++ptr; - break; - case 't': - *ptr = '\t'; - ++ptr; - break; - case 'n': - *ptr = '\n'; - ++ptr; - break; - case 'r': - *ptr = '\r'; - ++ptr; - break; - case '\\': - *ptr = '\\'; - ++ptr; - break; - case '\"': - *ptr = '\"'; - ++ptr; - break; - case '\'': - *ptr = '\''; - ++ptr; - break; - case 'x': - if (begin + 2 < end) - { - *ptr = (hexValueTable[int(begin[1])] << 4) + hexValueTable[int(begin[2])]; - ++ptr; - begin += 2; - break; - } - default: - *ptr = *begin; - ++ptr; - break; - } - } - ++begin; - } - buf.resize(ptr - &buf[0]); - if (!buf.empty()) - { - out.assign(&buf[0], &buf[0] + buf.size()); - } - else - { - out.clear(); - } - } - - // --------------------------------------------------------------------------- - - class JSONTokenizer - { - public: - JSONTokenizer(); - - Token operator()(const char* text) const; - private: - inline bool isSpace(char c) const; - inline bool isWordPart(unsigned char c) const; - inline bool isComment(char c) const; - inline bool isQuoteOpen(int& quoteIndex, char c) const; - inline bool isQuoteClose(int quoteIndex, char c) const; - inline bool isQuote(char c) const; - }; - - JSONTokenizer::JSONTokenizer() - { - } - - inline bool JSONTokenizer::isSpace(char c) const - { - return c == ' ' || c == '\t' || c == '\n' || c == '\r'; - } - - inline bool JSONTokenizer::isComment(char c) const - { - return c == '#'; - } - - - inline bool JSONTokenizer::isQuote(char c) const - { - return c == '\"'; - } - - static const char charTypes[256] = { - 0 /* 0x00: */, - 0 /* 0x01: */, - 0 /* 0x02: */, - 0 /* 0x03: */, - 0 /* 0x04: */, - 0 /* 0x05: */, - 0 /* 0x06: */, - 0 /* 0x07: */, - 0 /* 0x08: */, - 0 /* 0x09: \t */, - 0 /* 0x0A: \n */, - 0 /* 0x0B: */, - 0 /* 0x0C: */, - 0 /* 0x0D: */, - 0 /* 0x0E: */, - 0 /* 0x0F: */, - - - 0 /* 0x10: */, - 0 /* 0x11: */, - 0 /* 0x12: */, - 0 /* 0x13: */, - 0 /* 0x14: */, - 0 /* 0x15: */, - 0 /* 0x16: */, - 0 /* 0x17: */, - 0 /* 0x18: */, - 0 /* 0x19: */, - 0 /* 0x1A: */, - 0 /* 0x1B: */, - 0 /* 0x1C: */, - 0 /* 0x1D: */, - 0 /* 0x1E: */, - 0 /* 0x1F: */, - - - 0 /* 0x20: */, - 0 /* 0x21: ! */, - 0 /* 0x22: " */, - 0 /* 0x23: # */, - 0 /* 0x24: $ */, - 0 /* 0x25: % */, - 0 /* 0x26: & */, - 0 /* 0x27: ' */, - 0 /* 0x28: ( */, - 0 /* 0x29: ) */, - 0 /* 0x2A: * */, - 0 /* 0x2B: + */, - 0 /* 0x2C: , */, - 1 /* 0x2D: - */, - 1 /* 0x2E: . */, - 0 /* 0x2F: / */, - - - 1 /* 0x30: 0 */, - 1 /* 0x31: 1 */, - 1 /* 0x32: 2 */, - 1 /* 0x33: 3 */, - 1 /* 0x34: 4 */, - 1 /* 0x35: 5 */, - 1 /* 0x36: 6 */, - 1 /* 0x37: 7 */, - 1 /* 0x38: 8 */, - 1 /* 0x39: 9 */, - 0 /* 0x3A: : */, - 0 /* 0x3B: ; */, - 0 /* 0x3C: < */, - 0 /* 0x3D: = */, - 0 /* 0x3E: > */, - 0 /* 0x3F: ? */, - - - 0 /* 0x40: @ */, - 1 /* 0x41: A */, - 1 /* 0x42: B */, - 1 /* 0x43: C */, - 1 /* 0x44: D */, - 1 /* 0x45: E */, - 1 /* 0x46: F */, - 1 /* 0x47: G */, - 1 /* 0x48: H */, - 1 /* 0x49: I */, - 1 /* 0x4A: J */, - 1 /* 0x4B: K */, - 1 /* 0x4C: L */, - 1 /* 0x4D: M */, - 1 /* 0x4E: N */, - 1 /* 0x4F: O */, - - - 1 /* 0x50: P */, - 1 /* 0x51: Q */, - 1 /* 0x52: R */, - 1 /* 0x53: S */, - 1 /* 0x54: T */, - 1 /* 0x55: U */, - 1 /* 0x56: V */, - 1 /* 0x57: W */, - 1 /* 0x58: X */, - 1 /* 0x59: Y */, - 1 /* 0x5A: Z */, - 0 /* 0x5B: [ */, - 0 /* 0x5C: \ */, - 0 /* 0x5D: ] */, - 0 /* 0x5E: ^ */, - 1 /* 0x5F: _ */, - - - 0 /* 0x60: ` */, - 1 /* 0x61: a */, - 1 /* 0x62: b */, - 1 /* 0x63: c */, - 1 /* 0x64: d */, - 1 /* 0x65: e */, - 1 /* 0x66: f */, - 1 /* 0x67: g */, - 1 /* 0x68: h */, - 1 /* 0x69: i */, - 1 /* 0x6A: j */, - 1 /* 0x6B: k */, - 1 /* 0x6C: l */, - 1 /* 0x6D: m */, - 1 /* 0x6E: n */, - 1 /* 0x6F: o */, - - - 1 /* 0x70: p */, - 1 /* 0x71: q */, - 1 /* 0x72: r */, - 1 /* 0x73: s */, - 1 /* 0x74: t */, - 1 /* 0x75: u */, - 1 /* 0x76: v */, - 1 /* 0x77: w */, - 1 /* 0x78: x */, - 1 /* 0x79: y */, - 1 /* 0x7A: z */, - 0 /* 0x7B: { */, - 0 /* 0x7C: | */, - 0 /* 0x7D: } */, - 0 /* 0x7E: ~ */, - 0 /* 0x7F: */, - - - 0 /* 0x80: */, - 0 /* 0x81: */, - 0 /* 0x82: */, - 0 /* 0x83: */, - 0 /* 0x84: */, - 0 /* 0x85: */, - 0 /* 0x86: */, - 0 /* 0x87: */, - 0 /* 0x88: */, - 0 /* 0x89: */, - 0 /* 0x8A: */, - 0 /* 0x8B: */, - 0 /* 0x8C: */, - 0 /* 0x8D: */, - 0 /* 0x8E: */, - 0 /* 0x8F: */, - - - 0 /* 0x90: */, - 0 /* 0x91: */, - 0 /* 0x92: */, - 0 /* 0x93: */, - 0 /* 0x94: */, - 0 /* 0x95: */, - 0 /* 0x96: */, - 0 /* 0x97: */, - 0 /* 0x98: */, - 0 /* 0x99: */, - 0 /* 0x9A: */, - 0 /* 0x9B: */, - 0 /* 0x9C: */, - 0 /* 0x9D: */, - 0 /* 0x9E: */, - 0 /* 0x9F: */, - - - 0 /* 0xA0: */, - 0 /* 0xA1: */, - 0 /* 0xA2: */, - 0 /* 0xA3: */, - 0 /* 0xA4: */, - 0 /* 0xA5: */, - 0 /* 0xA6: */, - 0 /* 0xA7: */, - 0 /* 0xA8: */, - 0 /* 0xA9: */, - 0 /* 0xAA: */, - 0 /* 0xAB: */, - 0 /* 0xAC: */, - 0 /* 0xAD: */, - 0 /* 0xAE: */, - 0 /* 0xAF: */, - - - 0 /* 0xB0: */, - 0 /* 0xB1: */, - 0 /* 0xB2: */, - 0 /* 0xB3: */, - 0 /* 0xB4: */, - 0 /* 0xB5: */, - 0 /* 0xB6: */, - 0 /* 0xB7: */, - 0 /* 0xB8: */, - 0 /* 0xB9: */, - 0 /* 0xBA: */, - 0 /* 0xBB: */, - 0 /* 0xBC: */, - 0 /* 0xBD: */, - 0 /* 0xBE: */, - 0 /* 0xBF: */, - - - 0 /* 0xC0: */, - 0 /* 0xC1: */, - 0 /* 0xC2: */, - 0 /* 0xC3: */, - 0 /* 0xC4: */, - 0 /* 0xC5: */, - 0 /* 0xC6: */, - 0 /* 0xC7: */, - 0 /* 0xC8: */, - 0 /* 0xC9: */, - 0 /* 0xCA: */, - 0 /* 0xCB: */, - 0 /* 0xCC: */, - 0 /* 0xCD: */, - 0 /* 0xCE: */, - 0 /* 0xCF: */, - - - 0 /* 0xD0: */, - 0 /* 0xD1: */, - 0 /* 0xD2: */, - 0 /* 0xD3: */, - 0 /* 0xD4: */, - 0 /* 0xD5: */, - 0 /* 0xD6: */, - 0 /* 0xD7: */, - 0 /* 0xD8: */, - 0 /* 0xD9: */, - 0 /* 0xDA: */, - 0 /* 0xDB: */, - 0 /* 0xDC: */, - 0 /* 0xDD: */, - 0 /* 0xDE: */, - 0 /* 0xDF: */, - - - 0 /* 0xE0: */, - 0 /* 0xE1: */, - 0 /* 0xE2: */, - 0 /* 0xE3: */, - 0 /* 0xE4: */, - 0 /* 0xE5: */, - 0 /* 0xE6: */, - 0 /* 0xE7: */, - 0 /* 0xE8: */, - 0 /* 0xE9: */, - 0 /* 0xEA: */, - 0 /* 0xEB: */, - 0 /* 0xEC: */, - 0 /* 0xED: */, - 0 /* 0xEE: */, - 0 /* 0xEF: */, - - - 0 /* 0xF0: */, - 0 /* 0xF1: */, - 0 /* 0xF2: */, - 0 /* 0xF3: */, - 0 /* 0xF4: */, - 0 /* 0xF5: */, - 0 /* 0xF6: */, - 0 /* 0xF7: */, - 0 /* 0xF8: */, - 0 /* 0xF9: */, - 0 /* 0xFA: */, - 0 /* 0xFB: */, - 0 /* 0xFC: */, - 0 /* 0xFD: */, - 0 /* 0xFE: */, - 0 /* 0xFF: */ - }; - - inline bool JSONTokenizer::isWordPart(unsigned char c) const - { - return charTypes[c] != 0; - } - - Token JSONTokenizer::operator()(const char* ptr) const - { - while (isSpace(*ptr)) - { - ++ptr; - } - Token cur(ptr, ptr); - while (!cur && *ptr != '\0') - { - while (isComment(*cur.end)) - { - while (*cur.end && *cur.end != '\n') - { - ++cur.end; - } - while (isSpace(*cur.end)) - { - ++cur.end; - } - DEBUG_TRACE_TOKENIZER("Got comment: '%s'", string(commentStart, cur.end).c_str()); - cur.start = cur.end; - } - CRY_ASSERT(!isSpace(*cur.end)); - if (isQuote(*cur.end)) - { - ++cur.end; - while (*cur.end) - { - if (*cur.end == '\\') - { - ++cur.end; - if (*cur.end) - { - if (*cur.end != 'x' && *cur.end != 'X') - { - ++cur.end; - } - else - { - ++cur.end; - if (*cur.end) - { - ++cur.end; - } - } - continue; - } - } - if (isQuote(*cur.end)) - { - ++cur.end; - DEBUG_TRACE_TOKENIZER("Tokenizer result: '%s'", cur.str().c_str()); - return cur; - } - else - { - ++cur.end; - } - } - } - else - { - if (!*cur.end) - { - return cur; - } - - DEBUG_TRACE_TOKENIZER("%c", *cur.end); - if (isWordPart(*cur.end)) - { - do - { - ++cur.end; - } while (isWordPart(*cur.end) != 0); - } - else - { - ++cur.end; - return cur; - } - DEBUG_TRACE_TOKENIZER("Tokenizer result: '%s'", cur.str().c_str()); - return cur; - } - } - DEBUG_TRACE_TOKENIZER("Tokenizer result: '%s'", cur.str().c_str()); - return cur; - } - - - // --------------------------------------------------------------------------- - - JSONIArchive::JSONIArchive() - : IArchive(INPUT | TEXT) - , buffer_(0) - { - } - - JSONIArchive::~JSONIArchive() - { - if (buffer_) - { - free(buffer_); - buffer_ = 0; - } - stack_.clear(); - reader_.reset(); - } - - bool JSONIArchive::open(const char* buffer, size_t length, bool free) - { - if (!length) - { - return false; - } - - if (buffer) - { - reader_.reset(new MemoryReader(buffer, length, free)); - } - buffer_ = 0; - - token_ = Token(reader_->begin(), reader_->begin()); - stack_.clear(); - - stack_.push_back(Level()); - readToken(); - putToken(); - stack_.back().start = token_.end; - return true; - } - - - bool JSONIArchive::load(const char* filename) - { - FILE* file = nullptr; - azfopen(&file, filename, "rb"); - if (file) - { - fseek(file, 0, SEEK_END); - long fileSize = ftell(file); - fseek(file, 0, SEEK_SET); - - void* buffer = 0; - if (fileSize > 0) - { - buffer = malloc(fileSize + 1); - CRY_ASSERT(buffer != 0); - memset(buffer, 0, fileSize + 1); - size_t elementsRead = fread(buffer, fileSize, 1, file); - CRY_ASSERT(((char*)(buffer))[fileSize] == '\0'); - if (elementsRead != 1) - { - free(buffer); - return false; - } - } - fclose(file); - - filename_ = filename; - buffer_ = buffer; - if (fileSize > 0) - { - return open((char*)buffer, fileSize, false); - } - else - { - return false; - } - } - else - { - return false; - } - } - - void JSONIArchive::readToken() - { - JSONTokenizer tokenizer; - token_ = tokenizer(token_.end); - DEBUG_TRACE(" ~ read token '%s' at %i", token_.str().c_str(), token_.start - reader_->begin()); - } - - void JSONIArchive::putToken() - { - DEBUG_TRACE(" putToken: '%s'", token_.str().c_str()); - token_ = Token(token_.start, token_.start); - } - - int JSONIArchive::line(const char* position) const - { - return int(std::count(reader_->begin(), position, '\n') + 1); - } - - bool JSONIArchive::isName(Token token) const - { - if (!token) - { - return false; - } - char firstChar = token.start[0]; - if (firstChar == '"') - { - return true; - } - return false; - } - - - bool JSONIArchive::expect(char token) - { - if (token_ != token) - { - const char* lineEnd = token_.start; - while (lineEnd && *lineEnd != '\0' && *lineEnd != '\r' && *lineEnd != '\n') - { - ++lineEnd; - } - - MemoryWriter msg; - msg << "Error parsing file, expected ':' at line " << line(token_.start) << ":\n" - << string(token_.start, lineEnd).c_str(); - CRY_ASSERT_MESSAGE(0, msg.c_str()); - return false; - } - return true; - } - - void JSONIArchive::skipBlock() - { - DEBUG_TRACE("Skipping block from %i ...", token_.end - reader_->begin()); - if (openBracket() || openContainerBracket()) - { - closeBracket(); // Skipping entire block - } - else - { - readToken(); // Skipping value - } - readToken(); - if (token_ != ',') - { - putToken(); - } - DEBUG_TRACE(" ...till %i", token_.end - reader_->begin()); - } - - bool JSONIArchive::findName(const char* name, Token* outName) - { - DEBUG_TRACE(" * finding name '%s'", name); - DEBUG_TRACE(" started at byte %i", int(token_.start - reader_->begin())); - if (stack_.empty()) - { - // TODO: diagnose - return false; - } - if (stack_.back().isKeyValue) - { - return true; - } - const char* start = 0; - const char* blockBegin = stack_.back().start; - if (*blockBegin == '\0') - { - return false; - } - - readToken(); - if (token_ == ',') - { - readToken(); - } - if (!token_) - { - start = blockBegin; - token_.set(blockBegin, blockBegin); - readToken(); - } - - if (stack_.size() == 1 || stack_.back().isContainer || outName != 0) - { - if (token_ == ']' || token_ == '}') - { - DEBUG_TRACE("Got close bracket..."); - putToken(); - return false; - } - else - { - DEBUG_TRACE("Got unnamed value: '%s'", token_.str().c_str()); - putToken(); - return true; - } - } - else - { - if (isName(token_)) - { - DEBUG_TRACE("Seems to be a name '%s'", token_.str().c_str()); - Token nameContent(token_.start + 1, token_.end - 1); - if (nameContent == name) - { - readToken(); - expect(':'); - DEBUG_TRACE("Got one"); - return true; - } - else - { - start = token_.start; - - readToken(); - expect(':'); - skipBlock(); - } - } - else - { - start = token_.start; - if (token_ == ']' || token_ == '}') - { - token_ = Token(blockBegin, blockBegin); - } - else - { - putToken(); - skipBlock(); - } - } - } - - while (true) - { - readToken(); - if (!token_) - { - token_.set(blockBegin, blockBegin); - continue; - } - //return false; // Reached end of file while searching for name - DEBUG_TRACE("'%s'", token_.str().c_str()); - DEBUG_TRACE("Checking for loop: %i and %i", token_.start - reader_->begin(), start - reader_->begin()); - CRY_ASSERT(start != 0); - if (token_.start == start) - { - putToken(); - DEBUG_TRACE("unable to find..."); - return false; // Reached a full circle: unable to find name - } - - if (token_ == '}' || token_ == ']') // CONVERSION - { - DEBUG_TRACE("Going to begin of block, from %i", token_.start - reader_->begin()); - token_ = Token(blockBegin, blockBegin); - DEBUG_TRACE(" to %i", token_.start - reader_->begin()); - continue; // Reached '}' or ']' while searching for name, continue from begin of block - } - - if (name[0] == '\0') - { - if (isName(token_)) - { - readToken(); - if (!token_) - { - return false; // Reached end of file while searching for name - } - expect(':'); - skipBlock(); - } - else - { - putToken(); // Not a name - put it back - return true; - } - } - else - { - if (isName(token_)) - { - Token nameContent(token_.start + 1, token_.end - 1); - readToken(); - expect(':'); - if (nameContent == name) - { - return true; - } - else - { - skipBlock(); - } - } - else - { - putToken(); - skipBlock(); - } - } - } - - return false; - } - - bool JSONIArchive::openBracket() - { - readToken(); - if (token_ == '{') - { - return true; - } - putToken(); - return false; - } - - bool JSONIArchive::closeBracket() - { - int relativeLevel = 0; - while (true) - { - readToken(); - if (token_ == ',') - { - readToken(); - } - if (!token_) - { - MemoryWriter msg; - CRY_ASSERT(!stack_.empty()); - const char* start = stack_.back().start; - msg << filename_.c_str() << ": " << line(start) << " line"; - msg << ": End of file while no matching bracket found"; - CRY_ASSERT_MESSAGE(0, msg.c_str()); - return false; - } - else if (token_ == '}' || token_ == ']') // CONVERSION - { - if (relativeLevel == 0) - { - return true; - } - else - { - --relativeLevel; - } - } - else if (token_ == '{' || token_ == '[') // CONVERSION - { - ++relativeLevel; - } - } - return false; - } - - bool JSONIArchive::openContainerBracket() - { - readToken(); - if (token_ == '[') - { - return true; - } - putToken(); - return false; - } - - bool JSONIArchive::closeContainerBracket() - { - readToken(); - if (token_ == ']') - { - DEBUG_TRACE("closeContainerBracket(): ok"); - return true; - } - else - { - DEBUG_TRACE("closeContainerBracket(): failed ('%s')", token_.str().c_str()); - putToken(); - return false; - } - } - - bool JSONIArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - if (openBracket()) - { - stack_.push_back(Level()); - stack_.back().start = token_.end; - } - else if (openContainerBracket()) - { - stack_.push_back(Level()); - stack_.back().start = token_.end; - stack_.back().isContainer = true; - } - else - { - return false; - } - - ser(*this); - CRY_ASSERT(!stack_.empty()); - stack_.pop_back(); -#if !defined(NDEBUG) - bool closed = -#endif - closeBracket(); - CRY_ASSERT(closed); - return true; - } - return false; - } - - bool JSONIArchive::operator()(const SBlackBox& box, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - if (openBracket() || openContainerBracket()) - { - const char* start = token_.start; - putToken(); - skipBlock(); - const char* end = token_.start; - if (end < start) - { - CRY_ASSERT(0); - return false; - } - while (end > start && - (*(end - 1) == ' ' - || *(end - 1) == '\r' - || *(end - 1) == '\n' - || *(end - 1) == '\t')) - { - --end; - } - // box has to be const in the interface so we can serialize - // temporary variables (i.e. function call result or structures - // constructed on the stack) - const_cast(box).set("json", (void*)start, end - start); - return true; - } - } - return false; - } - - bool JSONIArchive::operator()(IKeyValue& keyValue, [[maybe_unused]] const char* name, [[maybe_unused]] const char* label) - { - Token nextName; - if (!stack_.empty() && stack_.back().isContainer) - { - readToken(); - if (isName(token_) && checkStringValueToken()) - { - string key; - unescapeString(unescapeBuffer_, key, token_.start + 1, token_.end - 1); - keyValue.set(key.c_str()); - readToken(); - if (!expect(':')) - { - return false; - } - if (!keyValue.serializeValue(*this, "", 0)) - { - return false; - } - return true; - } - else - { - putToken(); - return false; - } - } - else if (findName("", &nextName)) - { - string key; - unescapeString(unescapeBuffer_, key, nextName.start + 1, nextName.end - 1); - keyValue.set(key.c_str()); - stack_.push_back(Level()); - stack_.back().isKeyValue = true; - - bool result = keyValue.serializeValue(*this, "", 0); - if (stack_.empty()) - { - // TODO: diagnose - return false; - } - stack_.pop_back(); - return result; - } - return false; - } - - - bool JSONIArchive::operator()(IPointer& ser, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - if (openBracket()) - { - stack_.push_back(Level()); - stack_.back().start = token_.end; - stack_.back().isKeyValue = true; - - readToken(); - if (isName(token_)) - { - if (checkStringValueToken()) - { - string typeName; - unescapeString(unescapeBuffer_, typeName, token_.start + 1, token_.end - 1); - if (strcmp(ser.registeredTypeName(), typeName.c_str()) != 0) - { - ser.create(typeName.c_str()); - } - readToken(); - expect(':'); - operator()(ser.serializer(), "", 0); - } - } - else - { - putToken(); - - ser.create(""); - } - closeBracket(); - stack_.pop_back(); - return true; - } - } - return false; - } - - - bool JSONIArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - bool containerBracket = openContainerBracket(); - bool dictionaryBracket = false; - if (!containerBracket) - { - dictionaryBracket = openBracket(); - } - if (containerBracket || dictionaryBracket) - { - stack_.push_back(Level()); - stack_.back().isContainer = true; - stack_.back().start = token_.end; - - std::size_t size = ser.size(); - std::size_t index = 0; - - while (true) - { - readToken(); - if (token_ == ',') - { - readToken(); - } - if (token_ == '}' || token_ == ']') - { - break; - } - else if (!token_) - { - CRY_ASSERT(0 && "Reached end of file while reading container!"); - return false; - } - putToken(); - if (index == size) - { - size = index + 1; - } - if (index < size) - { - if (!ser(*this, "", "")) - { - // We've got a named item within a container, - // i.e. looks like a dictionary but not a container. - // Bail out, it is nothing we can do here. - closeBracket(); - break; - } - } - else - { - skipBlock(); - } - ser.next(); - ++index; - } - if (size > index) - { - ser.resize(index); - } - - CRY_ASSERT(!stack_.empty()); - stack_.pop_back(); - return true; - } - } - return false; - } - - void JSONIArchive::checkValueToken() - { - if (!token_) - { - CRY_ASSERT(!stack_.empty()); - MemoryWriter msg; - const char* start = stack_.back().start; - msg << filename_.c_str() << ": " << line(start) << " line"; - msg << ": End of file while reading element's value"; - CRY_ASSERT_MESSAGE(0, msg.c_str()); - } - } - - bool JSONIArchive::checkStringValueToken() - { - if (!token_) - { - return false; - MemoryWriter msg; - const char* start = stack_.back().start; - msg << filename_.c_str() << ": " << line(start) << " line"; - msg << ": End of file while reading element's value"; - CRY_ASSERT_MESSAGE(0, msg.c_str()); - return false; - } - if (token_.start[0] != '"' || token_.end[-1] != '"') - { - return false; - MemoryWriter msg; - const char* start = stack_.back().start; - msg << filename_.c_str() << ": " << line(start) << " line"; - msg << ": Expected string"; - CRY_ASSERT_MESSAGE(0, msg.c_str()); - return false; - } - return true; - } - - bool JSONIArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = strtol(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = strtoul(token_.start, 0, 10); - return true; - } - return false; - } - - - bool JSONIArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (int16)strtol(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (uint16)strtoul(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); -#ifdef _MSC_VER - value = _strtoi64(token_.start, 0, 10); -#else - value = strtoll(token_.start, 0, 10); -#endif - return true; - } - return false; - } - - bool JSONIArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); -#ifdef _MSC_VER - value = _strtoui64(token_.start, 0, 10); -#else - value = strtoull(token_.start, 0, 10); -#endif - return true; - } - return false; - } - - bool JSONIArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); -#ifdef _MSC_VER - value = float(std::atof(token_.str().c_str())); -#else - value = strtof(token_.start, 0); -#endif - return true; - } - return false; - } - - bool JSONIArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); -#ifdef _MSC_VER - value = std::atof(token_.str().c_str()); -#else - value = strtod(token_.start, 0); -#endif - return true; - } - return false; - } - - bool JSONIArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - if (checkStringValueToken()) - { - string buf; - unescapeString(unescapeBuffer_, buf, token_.start + 1, token_.end - 1); - value.set(buf.c_str()); - } - else - { - return false; - } - return true; - } - return false; - } - - - inline size_t utf8InUtf16Len(const char* p) - { - size_t result = 0; - - for (; *p; ++p) - { - unsigned char ch = (unsigned char)(*p); - - if (ch < 0x80 || (ch >= 0xC0 && ch < 0xFC)) - { - ++result; - } - } - - return result; - } - - inline const char* readUtf16FromUtf8(unsigned int* ch, const char* s) - { - const unsigned char byteMark = 0x80; - const unsigned char byteMaskRead = 0x3F; - - const unsigned char* str = (const unsigned char*)s; - - size_t len; - if (*str < byteMark) - { - *ch = *str; - return s + 1; - } - else if (*str < 0xC0) - { - *ch = ' '; - return s + 1; - } - else if (*str < 0xE0) - { - len = 2; - } - else if (*str < 0xF0) - { - len = 3; - } - else if (*str < 0xF8) - { - len = 4; - } - else if (*str < 0xFC) - { - len = 5; - } - else - { - *ch = ' '; - return s + 1; - } - - const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - *ch = (*str++ & ~firstByteMark[len]); - - switch (len) - { - case 5: - (*ch) <<= 6; - (*ch) += (*str++ & byteMaskRead); - case 4: - (*ch) <<= 6; - (*ch) += (*str++ & byteMaskRead); - case 3: - (*ch) <<= 6; - (*ch) += (*str++ & byteMaskRead); - case 2: - (*ch) <<= 6; - (*ch) += (*str++ & byteMaskRead); - } - - return (const char*)str; - } - - - inline void utf8ToUtf16(wstring* out, const char* in) - { - out->clear(); - out->reserve(utf8InUtf16Len(in)); - - for (; *in; ) - { - unsigned int character; - in = readUtf16FromUtf8(&character, in); - (*out) += (wchar_t)character; - } - } - - - bool JSONIArchive::operator()(IWString& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - if (checkStringValueToken()) - { - string buf; - unescapeString(unescapeBuffer_, buf, token_.start + 1, token_.end - 1); - wstring wbuf; - utf8ToUtf16(&wbuf, buf.c_str()); - value.set(wbuf.c_str()); - } - else - { - return false; - } - return true; - } - return false; - } - - bool JSONIArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - if (token_ == "true") - { - value = true; - } - else if (token_ == "false") - { - value = false; - } - else - { - CRY_ASSERT(0 && "Invalid boolean value"); - } - return true; - } - return false; - } - - bool JSONIArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (int8)strtol(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (uint8)strtol(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (char)strtol(token_.start, 0, 10); - return true; - } - return false; - } -} -// vim:ts=4 sw=4: diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONIArchive.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONIArchive.h deleted file mode 100644 index 60ce90672c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONIArchive.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_JSONIARCHIVE_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_JSONIARCHIVE_H -#pragma once - -#include "Pointers.h" -#include "Serialization/IArchive.h" -#include "Serialization/MemoryReader.h" -#include "Token.h" -#include "EditorCommonAPI.h" -#include -#include - -namespace Serialization { - class MemoryReader; - - class JSONIArchive - : public IArchive - { - public: - JSONIArchive(); - ~JSONIArchive(); - - bool load(const char* filename); - bool open(const char* buffer, size_t length, bool free = false); - - // virtuals: - bool operator()(bool& value, const char* name = "", const char* label = 0); - bool operator()(IString& value, const char* name = "", const char* label = 0); - bool operator()(IWString& value, const char* name = "", const char* label = 0); - bool operator()(float& value, const char* name = "", const char* label = 0); - bool operator()(double& value, const char* name = "", const char* label = 0); - bool operator()(int16& value, const char* name = "", const char* label = 0); - bool operator()(uint16& value, const char* name = "", const char* label = 0); - bool operator()(int32& value, const char* name = "", const char* label = 0); - bool operator()(uint32& value, const char* name = "", const char* label = 0); - bool operator()(int64& value, const char* name = "", const char* label = 0); - bool operator()(uint64& value, const char* name = "", const char* label = 0); - - bool operator()(int8& value, const char* name = "", const char* label = 0); - bool operator()(uint8& value, const char* name = "", const char* label = 0); - bool operator()(char& value, const char* name = "", const char* label = 0); - - bool operator()(const SStruct& ser, const char* name = "", const char* label = 0); - bool operator()(const SBlackBox& ser, const char* name = "", const char* label = 0); - bool operator()(IContainer& ser, const char* name = "", const char* label = 0); - bool operator()(IKeyValue& ser, const char* name = "", const char* label = 0); - bool operator()(IPointer& ser, const char* name = "", const char* label = 0); - - using IArchive::operator(); - - private: - bool findName(const char* name, Token* outName = 0); - bool openBracket(); - bool closeBracket(); - - bool openContainerBracket(); - bool closeContainerBracket(); - - void checkValueToken(); - bool checkStringValueToken(); - void readToken(); - void putToken(); - int line(const char* position) const; - bool isName(Token token) const; - - bool expect(char token); - void skipBlock(); - - struct Level - { - const char* start; - const char* firstToken; - bool isContainer; - bool isKeyValue; - Level() - : isContainer(false) - , isKeyValue(false) {} - }; - typedef std::vector Stack; - Stack stack_; - - std::unique_ptr reader_; - Token token_; - std::vector unescapeBuffer_; - AZStd::string filename_; - void* buffer_; - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_JSONIARCHIVE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONOArchive.cpp b/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONOArchive.cpp deleted file mode 100644 index fa71eee245..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONOArchive.cpp +++ /dev/null @@ -1,828 +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 "EditorCommon_precompiled.h" -#include "JSONOArchive.h" -#include "MemoryWriter.h" -#include "Serialization/KeyValue.h" -#include "Serialization/ClassFactory.h" -#include "Serialization/BlackBox.h" -#include - -namespace Serialization { - // Some of non-latin1 characters here are not escaped to - // keep compatibility with 8-bit local encoding (e.g. windows-1251) - static const char* escapeTable[256] = { - "\\0" /* 0x00: */, - "\\x01" /* 0x01: */, - "\\x02" /* 0x02: */, - "\\x03" /* 0x03: */, - "\\x04" /* 0x04: */, - "\\x05" /* 0x05: */, - "\\x06" /* 0x06: */, - "\\x07" /* 0x07: */, - "\\x08" /* 0x08: */, - "\\t" /* 0x09: \t */, - "\\n" /* 0x0A: \n */, - "\\x0B" /* 0x0B: */, - "\\x0C" /* 0x0C: */, - "\\r" /* 0x0D: */, - "\\x0E" /* 0x0E: */, - "\\x0F" /* 0x0F: */, - - - "\\x10" /* 0x10: */, - "\\x11" /* 0x11: */, - "\\x12" /* 0x12: */, - "\\x13" /* 0x13: */, - "\\x14" /* 0x14: */, - "\\x15" /* 0x15: */, - "\\x16" /* 0x16: */, - "\\x17" /* 0x17: */, - "\\x18" /* 0x18: */, - "\\x19" /* 0x19: */, - "\\x1A" /* 0x1A: */, - "\\x1B" /* 0x1B: */, - "\\x1C" /* 0x1C: */, - "\\x1D" /* 0x1D: */, - "\\x1E" /* 0x1E: */, - "\\x1F" /* 0x1F: */, - - - " " /* 0x20: */, - "!" /* 0x21: ! */, - "\\\"" /* 0x22: " */, - "#" /* 0x23: # */, - "$" /* 0x24: $ */, - "%" /* 0x25: % */, - "&" /* 0x26: & */, - "'" /* 0x27: ' */, - "(" /* 0x28: ( */, - ")" /* 0x29: ) */, - "*" /* 0x2A: * */, - "+" /* 0x2B: + */, - "," /* 0x2C: , */, - "-" /* 0x2D: - */, - "." /* 0x2E: . */, - "/" /* 0x2F: / */, - - - "0" /* 0x30: 0 */, - "1" /* 0x31: 1 */, - "2" /* 0x32: 2 */, - "3" /* 0x33: 3 */, - "4" /* 0x34: 4 */, - "5" /* 0x35: 5 */, - "6" /* 0x36: 6 */, - "7" /* 0x37: 7 */, - "8" /* 0x38: 8 */, - "9" /* 0x39: 9 */, - ":" /* 0x3A: : */, - ";" /* 0x3B: ; */, - "<" /* 0x3C: < */, - "=" /* 0x3D: = */, - ">" /* 0x3E: > */, - "?" /* 0x3F: ? */, - - - "@" /* 0x40: @ */, - "A" /* 0x41: A */, - "B" /* 0x42: B */, - "C" /* 0x43: C */, - "D" /* 0x44: D */, - "E" /* 0x45: E */, - "F" /* 0x46: F */, - "G" /* 0x47: G */, - "H" /* 0x48: H */, - "I" /* 0x49: I */, - "J" /* 0x4A: J */, - "K" /* 0x4B: K */, - "L" /* 0x4C: L */, - "M" /* 0x4D: M */, - "N" /* 0x4E: N */, - "O" /* 0x4F: O */, - - - "P" /* 0x50: P */, - "Q" /* 0x51: Q */, - "R" /* 0x52: R */, - "S" /* 0x53: S */, - "T" /* 0x54: T */, - "U" /* 0x55: U */, - "V" /* 0x56: V */, - "W" /* 0x57: W */, - "X" /* 0x58: X */, - "Y" /* 0x59: Y */, - "Z" /* 0x5A: Z */, - "[" /* 0x5B: [ */, - "\\\\" /* 0x5C: \ */, - "]" /* 0x5D: ] */, - "^" /* 0x5E: ^ */, - "_" /* 0x5F: _ */, - - - "`" /* 0x60: ` */, - "a" /* 0x61: a */, - "b" /* 0x62: b */, - "c" /* 0x63: c */, - "d" /* 0x64: d */, - "e" /* 0x65: e */, - "f" /* 0x66: f */, - "g" /* 0x67: g */, - "h" /* 0x68: h */, - "i" /* 0x69: i */, - "j" /* 0x6A: j */, - "k" /* 0x6B: k */, - "l" /* 0x6C: l */, - "m" /* 0x6D: m */, - "n" /* 0x6E: n */, - "o" /* 0x6F: o */, - - - "p" /* 0x70: p */, - "q" /* 0x71: q */, - "r" /* 0x72: r */, - "s" /* 0x73: s */, - "t" /* 0x74: t */, - "u" /* 0x75: u */, - "v" /* 0x76: v */, - "w" /* 0x77: w */, - "x" /* 0x78: x */, - "y" /* 0x79: y */, - "z" /* 0x7A: z */, - "{" /* 0x7B: { */, - "|" /* 0x7C: | */, - "}" /* 0x7D: } */, - "~" /* 0x7E: ~ */, - "\x7F" /* 0x7F: */, // for utf-8 - - - "\x80" /* 0x80: */, - "\x81" /* 0x81: */, - "\x82" /* 0x82: */, - "\x83" /* 0x83: */, - "\x84" /* 0x84: */, - "\x85" /* 0x85: */, - "\x86" /* 0x86: */, - "\x87" /* 0x87: */, - "\x88" /* 0x88: */, - "\x89" /* 0x89: */, - "\x8A" /* 0x8A: */, - "\x8B" /* 0x8B: */, - "\x8C" /* 0x8C: */, - "\x8D" /* 0x8D: */, - "\x8E" /* 0x8E: */, - "\x8F" /* 0x8F: */, - - - "\x90" /* 0x90: */, - "\x91" /* 0x91: */, - "\x92" /* 0x92: */, - "\x93" /* 0x93: */, - "\x94" /* 0x94: */, - "\x95" /* 0x95: */, - "\x96" /* 0x96: */, - "\x97" /* 0x97: */, - "\x98" /* 0x98: */, - "\x99" /* 0x99: */, - "\x9A" /* 0x9A: */, - "\x9B" /* 0x9B: */, - "\x9C" /* 0x9C: */, - "\x9D" /* 0x9D: */, - "\x9E" /* 0x9E: */, - "\x9F" /* 0x9F: */, - - - "\xA0" /* 0xA0: */, - "\xA1" /* 0xA1: */, - "\xA2" /* 0xA2: */, - "\xA3" /* 0xA3: */, - "\xA4" /* 0xA4: */, - "\xA5" /* 0xA5: */, - "\xA6" /* 0xA6: */, - "\xA7" /* 0xA7: */, - "\xA8" /* 0xA8: */, - "\xA9" /* 0xA9: */, - "\xAA" /* 0xAA: */, - "\xAB" /* 0xAB: */, - "\xAC" /* 0xAC: */, - "\xAD" /* 0xAD: */, - "\xAE" /* 0xAE: */, - "\xAF" /* 0xAF: */, - - - "\xB0" /* 0xB0: */, - "\xB1" /* 0xB1: */, - "\xB2" /* 0xB2: */, - "\xB3" /* 0xB3: */, - "\xB4" /* 0xB4: */, - "\xB5" /* 0xB5: */, - "\xB6" /* 0xB6: */, - "\xB7" /* 0xB7: */, - "\xB8" /* 0xB8: */, - "\xB9" /* 0xB9: */, - "\xBA" /* 0xBA: */, - "\xBB" /* 0xBB: */, - "\xBC" /* 0xBC: */, - "\xBD" /* 0xBD: */, - "\xBE" /* 0xBE: */, - "\xBF" /* 0xBF: */, - - - "\xC0" /* 0xC0: */, - "\xC1" /* 0xC1: */, - "\xC2" /* 0xC2: */, - "\xC3" /* 0xC3: */, - "\xC4" /* 0xC4: */, - "\xC5" /* 0xC5: */, - "\xC6" /* 0xC6: */, - "\xC7" /* 0xC7: */, - "\xC8" /* 0xC8: */, - "\xC9" /* 0xC9: */, - "\xCA" /* 0xCA: */, - "\xCB" /* 0xCB: */, - "\xCC" /* 0xCC: */, - "\xCD" /* 0xCD: */, - "\xCE" /* 0xCE: */, - "\xCF" /* 0xCF: */, - - - "\xD0" /* 0xD0: */, - "\xD1" /* 0xD1: */, - "\xD2" /* 0xD2: */, - "\xD3" /* 0xD3: */, - "\xD4" /* 0xD4: */, - "\xD5" /* 0xD5: */, - "\xD6" /* 0xD6: */, - "\xD7" /* 0xD7: */, - "\xD8" /* 0xD8: */, - "\xD9" /* 0xD9: */, - "\xDA" /* 0xDA: */, - "\xDB" /* 0xDB: */, - "\xDC" /* 0xDC: */, - "\xDD" /* 0xDD: */, - "\xDE" /* 0xDE: */, - "\xDF" /* 0xDF: */, - - - "\xE0" /* 0xE0: */, - "\xE1" /* 0xE1: */, - "\xE2" /* 0xE2: */, - "\xE3" /* 0xE3: */, - "\xE4" /* 0xE4: */, - "\xE5" /* 0xE5: */, - "\xE6" /* 0xE6: */, - "\xE7" /* 0xE7: */, - "\xE8" /* 0xE8: */, - "\xE9" /* 0xE9: */, - "\xEA" /* 0xEA: */, - "\xEB" /* 0xEB: */, - "\xEC" /* 0xEC: */, - "\xED" /* 0xED: */, - "\xEE" /* 0xEE: */, - "\xEF" /* 0xEF: */, - - - "\xF0" /* 0xF0: */, - "\xF1" /* 0xF1: */, - "\xF2" /* 0xF2: */, - "\xF3" /* 0xF3: */, - "\xF4" /* 0xF4: */, - "\xF5" /* 0xF5: */, - "\xF6" /* 0xF6: */, - "\xF7" /* 0xF7: */, - "\xF8" /* 0xF8: */, - "\xF9" /* 0xF9: */, - "\xFA" /* 0xFA: */, - "\xFB" /* 0xFB: */, - "\xFC" /* 0xFC: */, - "\xFD" /* 0xFD: */, - "\xFE" /* 0xFE: */, - "\xFF" /* 0xFF: */ - }; - - static void escapeString(MemoryWriter& dest, const char* begin, const char* end) - { - while (begin != end) - { - const char* str = escapeTable[(unsigned char)(*begin)]; - dest.write(str); - ++begin; - } - } - - // --------------------------------------------------------------------------- - - static const int TAB_WIDTH = 2; - - JSONOArchive::JSONOArchive(int textWidth, const char* header) - : IArchive(OUTPUT | TEXT) - , header_(header) - , textWidth_(textWidth) - , compactOffset_(0) - { - buffer_.reset(new MemoryWriter(1024, true)); - if (header_) - { - (*buffer_) << header_; - } - - YASLI_ASSERT(stack_.empty()); - stack_.push_back(Level(false, 0, 0)); - } - - JSONOArchive::~JSONOArchive() - { - } - - bool JSONOArchive::save(const char* fileName) - { - YASLI_ESCAPE(fileName && strlen(fileName) > 0, return false); - YASLI_ESCAPE(stack_.size() == 1, return false); - YASLI_ESCAPE(buffer_.get() != 0, return false); - YASLI_ESCAPE(buffer_->position() <= buffer_->size(), return false); - stack_.pop_back(); - FILE* file = nullptr; - azfopen(&file, fileName, "wb"); - if (file) - { - if (fwrite(buffer_->c_str(), 1, buffer_->position(), file) != buffer_->position()) - { - fclose(file); - return false; - } - fclose(file); - return true; - } - else - { - return false; - } - } - - const char* JSONOArchive::c_str() const - { - return buffer_->c_str(); - } - - size_t JSONOArchive::length() const - { - return buffer_->position(); - } - - void JSONOArchive::openBracket() - { - *buffer_ << "{"; - } - - void JSONOArchive::closeBracket() - { - *buffer_ << "}"; - } - - void JSONOArchive::openContainerBracket() - { - *buffer_ << "["; - } - - void JSONOArchive::closeContainerBracket() - { - *buffer_ << "]"; - } - - void JSONOArchive::placeName(const char* name) - { - if (stack_.back().isKeyValue) - { - return; - } - if ((name[0] != '\0' || !stack_.back().isContainer) && stack_.size() > 1) - { - *buffer_ << "\""; - *buffer_ << name; - *buffer_ << "\": "; - stack_.back().nameIndex += 1; - } - } - - void JSONOArchive::placeIndent(bool putComma) - { - if (stack_.back().isKeyValue) - { - return; - } - if (putComma && stack_.back().elementIndex > 0) - { - *buffer_ << ","; - } - if (buffer_->position() > 0) - { - *buffer_ << "\n"; - } - int count = int(stack_.size() - 1); - stack_.back().indentCount += count; - stack_.back().elementIndex += 1; - for (int i = 0; i < count; ++i) - { - *buffer_ << "\t"; - } - compactOffset_ = 0; - } - - void JSONOArchive::placeIndentCompact(bool putComma) - { - if (stack_.back().isKeyValue) - { - return; - } - if (putComma && stack_.back().elementIndex > 0) - { - *buffer_ << ","; - } - if ((compactOffset_ % 32) != 0 && stack_.back().isContainer) - { - *buffer_ << " "; - compactOffset_ += 1; - stack_.back().elementIndex += 1; - } - else if (buffer_->size()) - { - *buffer_ << "\n"; - int count = int(stack_.size() - 1); - stack_.back().indentCount += count /* * TAB_WIDTH*/; - stack_.back().elementIndex += 1; - for (int i = 0; i < count; ++i) - { - *buffer_ << "\t"; - } - compactOffset_ = 1; - } - } - - bool JSONOArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - *buffer_ << (value ? "true" : "false"); - return true; - } - - - bool JSONOArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - (*buffer_) << "\""; - const char* str = value.get(); - escapeString(*buffer_, str, str + strlen(value.get())); - (*buffer_) << "\""; - return true; - } - - inline char* writeUtf16ToUtf8(char* s, unsigned int ch) - { - const unsigned char byteMark = 0x80; - const unsigned char byteMask = 0xBF; - - size_t len; - - if (ch < 0x80) - { - len = 1; - } - else if (ch < 0x800) - { - len = 2; - } - else if (ch < 0x10000) - { - len = 3; - } - else if (ch < 0x200000) - { - len = 4; - } - else - { - return s; - } - - s += len; - - const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - switch (len) - { - case 4: - *--s = (char)((ch | byteMark) & byteMask); - ch >>= 6; - case 3: - *--s = (char)((ch | byteMark) & byteMask); - ch >>= 6; - case 2: - *--s = (char)((ch | byteMark) & byteMask); - ch >>= 6; - case 1: - *--s = (char)(ch | firstByteMark[len]); - } - - return s + len; - } - - bool JSONOArchive::operator()(IWString& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - (*buffer_) << "\""; - - const wchar_t* in = value.get(); - for (; *in; ++in) - { - char buf[6]; - escapeString(*buffer_, buf, writeUtf16ToUtf8(buf, *in)); - } - - (*buffer_) << "\""; - return true; - } - - bool JSONOArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - std::size_t position = buffer_->position(); - openBracket(); - stack_.push_back(Level(false, position, int(strlen(name) + 2 * (name[0] & 1) + (stack_.size() - 1) * TAB_WIDTH + 2))); - - YASLI_ASSERT(ser); - ser(*this); - - bool joined = joinLinesIfPossible(); - bool noNames = stack_.back().nameIndex == 0; - if (noNames) - { - if (stack_.size() != 2) - { - buffer_->buffer()[stack_.back().startPosition] = '['; - } - } - stack_.pop_back(); - if (!joined) - { - placeIndent(false); - } - else - { - *buffer_ << " "; - } - if (noNames) - { - closeContainerBracket(); - } - else - { - closeBracket(); - } - return true; - } - - bool JSONOArchive::operator()(const SBlackBox& box, const char* name, [[maybe_unused]] const char* label) - { - if (strcmp(box.format, "json") != 0) - { - return false; - } - if (box.size == 0) - { - return false; - } - - placeIndent(); - placeName(name); - return buffer_->write(box.data, box.size); - } - - bool JSONOArchive::operator()(IKeyValue& keyValue, [[maybe_unused]] const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - - *buffer_ << "\""; - *buffer_ << keyValue.get(); - *buffer_ << "\": "; - stack_.back().nameIndex += 1; - - stack_.back().isKeyValue = true; - keyValue.serializeValue(*this, "", 0); - stack_.back().isKeyValue = false; - if (stack_.back().isContainer) - { - stack_.back().isDictionary = true; - } - return true; - } - - bool JSONOArchive::operator()(IPointer& ser, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - openBracket(); - const char* registeredTypeName = ser.registeredTypeName(); - if (registeredTypeName && registeredTypeName[0] != '\0') - { - *buffer_ << " "; - placeName(registeredTypeName); - stack_.back().isKeyValue = true; - operator()(ser.serializer(), ""); - stack_.back().isKeyValue = false; - *buffer_ << " "; - } - closeBracket(); - return true; - } - - bool JSONOArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - std::size_t position = buffer_->position(); - openContainerBracket(); - stack_.push_back(Level(true, position, int(strlen(name) + 2 * (name[0] & 1) + stack_.size() - 1 * TAB_WIDTH + 2))); - - std::size_t size = ser.size(); - if (size > 0) - { - do - { - ser(*this, "", ""); - } while (ser.next()); - } - - bool joined = joinLinesIfPossible(); - bool isDictionary = stack_.back().isDictionary; - if (isDictionary) - { - buffer_->buffer()[stack_.back().startPosition] = '{'; - } - stack_.pop_back(); - if (!joined) - { - placeIndent(false); - } - else - { - *buffer_ << " "; - } - - if (isDictionary) - { - closeBracket(); - } - else - { - closeContainerBracket(); - } - return true; - } - - static char* joinLines(char* start, char* end) - { - YASLI_ASSERT(start <= end); - char* next = start; - while (next != end) - { - if (*next != '\t' && *next != '\r') - { - if (*next != '\n') - { - *start = *next; - } - else - { - *start = ' '; - } - ++start; - } - ++next; - } - return start; - } - - bool JSONOArchive::joinLinesIfPossible() - { - YASLI_ASSERT(!stack_.empty()); - std::size_t startPosition = stack_.back().startPosition; - YASLI_ASSERT(startPosition < buffer_->size()); - int indentCount = stack_.back().indentCount; - //YASLI_ASSERT(startPosition >= indentCount); - if (buffer_->position() - startPosition - indentCount < std::size_t(textWidth_)) - { - char* buffer = buffer_->buffer(); - char* start = buffer + startPosition; - char* end = buffer + buffer_->position(); - end = joinLines(start, end); - std::size_t newPosition = end - buffer; - YASLI_ASSERT(newPosition <= buffer_->position()); - buffer_->setPosition(newPosition); - return true; - } - return false; - } -} -// vim:ts=4 sw=4: diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONOArchive.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONOArchive.h deleted file mode 100644 index 085e1abf16..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONOArchive.h +++ /dev/null @@ -1,108 +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_EDITORCOMMON_SERIALIZATION_JSONOARCHIVE_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_JSONOARCHIVE_H -#pragma once - -#include "Serialization/IArchive.h" -#include "Serialization/MemoryWriter.h" -#include "EditorCommonAPI.h" -#include - -namespace Serialization { - class MemoryWriter; - - class JSONOArchive - : public IArchive - { - public: - // header = 0 - default header, use "" to omit - JSONOArchive(int textWidth = 80, const char* header = 0); - ~JSONOArchive(); - - bool save(const char* fileName); - - const char* c_str() const; - const char* buffer() const { return c_str(); } - size_t length() const; - - // from Archive: - bool operator()(bool& value, const char* name = "", const char* label = 0); - bool operator()(IString& value, const char* name = "", const char* label = 0); - bool operator()(IWString& value, const char* name = "", const char* label = 0); - bool operator()(float& value, const char* name = "", const char* label = 0); - bool operator()(double& value, const char* name = "", const char* label = 0); - bool operator()(int16& value, const char* name = "", const char* label = 0); - bool operator()(uint16& value, const char* name = "", const char* label = 0); - bool operator()(int32& value, const char* name = "", const char* label = 0); - bool operator()(uint32& value, const char* name = "", const char* label = 0); - bool operator()(int64& value, const char* name = "", const char* label = 0); - bool operator()(uint64& value, const char* name = "", const char* label = 0); - - bool operator()(char& value, const char* name = "", const char* label = 0); - bool operator()(int8& value, const char* name = "", const char* label = 0); - bool operator()(uint8& value, const char* name = "", const char* label = 0); - - bool operator()(const SStruct& ser, const char* name = "", const char* label = 0); - bool operator()(const SBlackBox& box, const char* name = "", const char* label = 0); - bool operator()(IContainer& ser, const char* name = "", const char* label = 0); - bool operator()(IKeyValue& keyValue, const char* name = "", const char* label = 0); - bool operator()(IPointer& ser, const char* name = "", const char* label = 0); - // ^^^ - - using IArchive::operator(); - - private: - void openBracket(); - void closeBracket(); - void openContainerBracket(); - void closeContainerBracket(); - void placeName(const char* name); - void placeIndent(bool putComma = true); - void placeIndentCompact(bool putComma = true); - - bool joinLinesIfPossible(); - - struct Level - { - Level(bool _isContainer, std::size_t position, int column) - : isContainer(_isContainer) - , isKeyValue(false) - , isDictionary(false) - , startPosition(position) - , indentCount(-column) - , elementIndex(0) - , nameIndex(0) - {} - bool isKeyValue; - bool isContainer; - bool isDictionary; - std::size_t startPosition; - int nameIndex; - int elementIndex; - int indentCount; - }; - - typedef std::vector Stack; - Stack stack_; - std::unique_ptr buffer_; - const char* header_; - int textWidth_; - string fileName_; - int compactOffset_; - bool isKeyValue_; - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_JSONOARCHIVE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryReader.cpp b/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryReader.cpp deleted file mode 100644 index 995064a57a..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryReader.cpp +++ /dev/null @@ -1,92 +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 "EditorCommon_precompiled.h" -#include -#include "Serialization/Assert.h" -#include "MemoryReader.h" -#include -#include - -namespace Serialization { - MemoryReader::MemoryReader() - : size_(0) - , position_(0) - , memory_(0) - , ownedMemory_(false) - { - } - - - MemoryReader::MemoryReader(const void* memory, std::size_t size, bool ownAndFree) - : size_(size) - , position_((const char*)(memory)) - , memory_((const char*)(memory)) - , ownedMemory_(ownAndFree) - { - } - - MemoryReader::~MemoryReader() - { - if (ownedMemory_) - { - free(const_cast(memory_)); - memory_ = 0; - size_ = 0; - } - } - - void MemoryReader::setPosition(const char* position) - { - position_ = position; - } - - void MemoryReader::read(void* data, std::size_t size) - { - YASLI_ASSERT(memory_ && position_); - YASLI_ASSERT(position_ - memory_ + size <= size_); - memcpy(data, position_, size); - position_ += size; - } - - bool MemoryReader::checkedRead(void* data, std::size_t size) - { - if (!memory_ || !position_) - { - return false; - } - if (position_ - memory_ + size > size_) - { - return false; - } - - memcpy(data, position_, size); - position_ += size; - return true; - } - - bool MemoryReader::checkedSkip(std::size_t size) - { - if (!memory_ || !position_) - { - return false; - } - if (position_ - memory_ + size > size_) - { - return false; - } - - position_ += size; - return true; - } -} diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryReader.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryReader.h deleted file mode 100644 index 1785574285..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryReader.h +++ /dev/null @@ -1,62 +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_EDITORCOMMON_SERIALIZATION_MEMORYREADER_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_MEMORYREADER_H -#pragma once - - -#include - -namespace Serialization { - class MemoryReader - { - public: - MemoryReader(); - MemoryReader(const void* memory, size_t size, bool ownAndFree = false); - ~MemoryReader(); - - void setPosition(const char* position); - const char* position() { return position_; } - - template - void read(T& value) - { - read(reinterpret_cast(&value), sizoef(value)); - } - void read(void* data, size_t size); - bool checkedSkip(size_t size); - bool checkedRead(void* data, size_t size); - template - bool checkedRead(T& t) - { - return checkedRead((void*)&t, sizeof(t)); - } - - const char* buffer() const { return memory_; } - size_t size() const { return size_; } - - const char* begin() const { return memory_; } - const char* end() const { return memory_ + size_; } - - - private: - size_t size_; - const char* position_; - const char* memory_; - bool ownedMemory_; - }; -} -// vim:ts=4 sw=4: - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_MEMORYREADER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryWriter.cpp b/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryWriter.cpp deleted file mode 100644 index 7cb515bb10..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryWriter.cpp +++ /dev/null @@ -1,275 +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 "EditorCommon_precompiled.h" -#include -#include "Serialization/Assert.h" -#include -#include -#include -#include -#ifdef _MSC_VER -# include -# define isnan _isnan -#endif - -#include "MemoryWriter.h" - -#undef YASLI_ASSERT -#define YASLI_ASSERT(x) - -namespace Serialization { - MemoryWriter::MemoryWriter(std::size_t size, bool reallocate) - : size_(size) - , reallocate_(reallocate) - , digits_(5) - { - allocate(size); - } - - MemoryWriter::~MemoryWriter() - { - position_ = 0; - free(memory_); - } - - void MemoryWriter::allocate(std::size_t initialSize) - { - memory_ = (char*)malloc(initialSize + 1); - position_ = memory_; - } - - void MemoryWriter::reallocate(std::size_t newSize) - { - YASLI_ASSERT(newSize > size_); - std::size_t pos = position(); - memory_ = (char*)realloc(memory_, newSize + 1); - YASLI_ASSERT(memory_ != 0); - position_ = memory_ + pos; - size_ = newSize; - } - - MemoryWriter& MemoryWriter::operator<<(int value) - { - // TODO: optimize - char buffer[12]; - sprintf_s(buffer, "%i", value); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(long value) - { - // TODO: optimize - char buffer[12]; -#ifdef _MSC_VER - sprintf_s(buffer, "%i", value); -#else - sprintf_s(buffer, "%li", value); -#endif - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(unsigned long value) - { - // TODO: optimize - char buffer[12]; -#ifdef _MSC_VER - sprintf_s(buffer, "%u", value); -#else - sprintf_s(buffer, "%lu", value); -#endif - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(long long value) - { - // TODO: optimize - char buffer[24]; -#ifdef _MSC_VER - sprintf_s(buffer, "%I64i", value); -#else - sprintf_s(buffer, "%lli", value); -#endif - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(unsigned long long value) - { - // TODO: optimize - char buffer[24]; -#ifdef _MSC_VER - sprintf_s(buffer, "%I64u", value); -#else - sprintf_s(buffer, "%llu", value); -#endif - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(unsigned int value) - { - // TODO: optimize - char buffer[12]; - sprintf_s(buffer, "%u", value); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(char value) - { - char buffer[12]; - sprintf_s(buffer, "%i", int(value)); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(unsigned char value) - { - char buffer[12]; - sprintf_s(buffer, "%i", int(value)); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(signed char value) - { - char buffer[12]; - sprintf_s(buffer, "%i", int(value)); - return operator<<((const char*)buffer); - } - - inline void cutRightZeros(const char* str) - { - for (char* p = (char*)str + strlen(str) - 1; p >= str; --p) - { - if (*p == '0') - { - *p = 0; - } - else - { - return; - } - } - } - - MemoryWriter& MemoryWriter::operator<<(double value) - { - // YASLI_ASSERT(!isnan(value)); disabled, because physics data is not always initialized - - int point = 0; - int sign = 0; - -#ifdef _MSC_VER - char buf[_CVTBUFSIZE]; - _fcvt_s(buf, value, digits_, &point, &sign); -#else - const char* buf = fcvt(value, digits_, &point, &sign); -#endif - - if (sign != 0) - { - write("-"); - } - if (point <= 0) - { - cutRightZeros(buf); - if (strlen(buf)) - { - write("0."); - while (point < 0) - { - write("0"); - ++point; - } - write(buf); - } - else - { - write("0"); - } - *position_ = '\0'; - } - else - { - write(buf, point); - write("."); - cutRightZeros(buf + point); - operator<<(buf + point); - } - return *this; - } - - MemoryWriter& MemoryWriter::operator<<(const char* value) - { - write((void*)value, strlen(value)); - YASLI_ASSERT(position() < size()); - *position_ = '\0'; - return *this; - } - - MemoryWriter& MemoryWriter::operator<<(const wchar_t* value) - { - write((void*)value, wcslen(value) * sizeof(wchar_t)); - YASLI_ASSERT(position() < size()); - *position_ = '\0'; - return *this; - } - - void MemoryWriter::setPosition(std::size_t pos) - { - YASLI_ASSERT(pos < size_); - YASLI_ASSERT(memory_ + pos <= position_); - position_ = memory_ + pos; - } - - void MemoryWriter::write(const char* value) - { - write((void*)value, strlen(value)); - } - - bool MemoryWriter::write(const void* data, std::size_t size) - { - YASLI_ASSERT(memory_ <= position_); - YASLI_ASSERT(position() < this->size()); - if (size_ - position() > size) - { - memcpy(position_, data, size); - position_ += size; - } - else - { - if (!reallocate_) - { - return false; - } - - reallocate(size_ * 2); - write(data, size); - } - YASLI_ASSERT(position() < this->size()); - return true; - } - - void MemoryWriter::write(char c) - { - if (size_ - position() > 1) - { - *(char*)(position_) = c; - ++position_; - } - else - { - YASLI_ESCAPE(reallocate_, return ); - reallocate(size_ * 2); - write(c); - } - YASLI_ASSERT(position() < this->size()); - } -} diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryWriter.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryWriter.h deleted file mode 100644 index acd852cb62..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryWriter.h +++ /dev/null @@ -1,80 +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_EDITORCOMMON_SERIALIZATION_MEMORYWRITER_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_MEMORYWRITER_H -#pragma once - - -#include -#include "Pointers.h" -#include "EditorCommonAPI.h" - -namespace Serialization { - class MemoryWriter - : public RefCounter - { - public: - MemoryWriter(std::size_t size = 128, bool reallocate = true); - ~MemoryWriter(); - - const char* c_str() { return memory_; }; - const wchar_t* w_str() { return (wchar_t*)memory_; }; - char* buffer() { return memory_; } - const char* buffer() const { return memory_; } - std::size_t size() const{ return size_; } - void clear() { position_ = memory_; } - - // String interface (after this calls '\0' is always written) - MemoryWriter& operator<<(int value); - MemoryWriter& operator<<(long value); - MemoryWriter& operator<<(unsigned long value); - MemoryWriter& operator<<(unsigned int value); - MemoryWriter& operator<<(long long value); - MemoryWriter& operator<<(unsigned long long value); - MemoryWriter& operator<<(float value) { return (*this) << double(value); } - MemoryWriter& operator<<(double value); - MemoryWriter& operator<<(signed char value); - MemoryWriter& operator<<(unsigned char value); - MemoryWriter& operator<<(char value); - MemoryWriter& operator<<(const char* value); - MemoryWriter& operator<<(const wchar_t* value); - - // Binary interface (does not writes trailing '\0') - template - void write(const T& value) - { - write(reinterpret_cast(&value), sizeof(value)); - } - void write(char c); - void write(const char* str); - bool write(const void* data, std::size_t size); - - std::size_t position() const { return position_ - memory_; } - void setPosition(std::size_t pos); - - MemoryWriter& setDigits(int digits) { digits_ = (unsigned char)digits; return *this; } - - private: - void allocate(std::size_t initialSize); - void reallocate(std::size_t newSize); - - std::size_t size_; - char* position_; - char* memory_; - bool reallocate_; - unsigned char digits_; - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_MEMORYWRITER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Pointers.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Pointers.h deleted file mode 100644 index db674701d4..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Pointers.h +++ /dev/null @@ -1,265 +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_EDITORCOMMON_SERIALIZATION_POINTERS_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_POINTERS_H -#pragma once - -#include "Serialization/Assert.h" - -namespace Serialization { - class RefCounter - { - public: - RefCounter() - : refCounter_(0) - {} - ~RefCounter() {}; - - int refCount() const { return refCounter_; } - - void acquire() { ++refCounter_; } - int release() { return --refCounter_; } - private: - int refCounter_; - }; - - class PolyRefCounter - : public RefCounter - { - public: - virtual ~PolyRefCounter() {} - }; - - class PolyPtrBase - { - public: - PolyPtrBase() - : ptr_(0) - { - } - void release() - { - if (ptr_) - { - if (!ptr_->release()) - { - delete ptr_; - } - ptr_ = 0; - } - } - void set(PolyRefCounter* const ptr) - { - if (ptr_ != ptr) - { - release(); - ptr_ = ptr; - if (ptr_) - { - ptr_->acquire(); - } - } - } - protected: - PolyRefCounter* ptr_; - }; - - template - class PolyPtr - : public PolyPtrBase - { - public: - PolyPtr() - : PolyPtrBase() - { - } - - PolyPtr(PolyRefCounter* ptr) - { - set(ptr); - } - - template - PolyPtr(U* ptr) - { - // TODO: replace with static_assert - YASLI_ASSERT("PolyRefCounter must be a first base when used with multiple inheritance." && - static_cast(ptr) == reinterpret_cast(ptr)); - set(static_cast(ptr)); - } - - PolyPtr(const PolyPtr& ptr) - : PolyPtrBase() - { - set(ptr.ptr_); - } - ~PolyPtr() - { - release(); - } - operator T*() const { - return get(); - } - template - operator PolyPtr() const { - return PolyPtr(get()); - } - operator bool() const { - return ptr_ != 0; - } - - PolyPtr& operator=(const PolyPtr& ptr) - { - set(ptr.ptr_); - return *this; - } - T* get() const { return reinterpret_cast(ptr_); } - T& operator*() const - { - return *get(); - } - T* operator->() const { return get(); } - }; - - class IArchive; - template - class SharedPtr - { - public: - SharedPtr() - : ptr_(0) {} - SharedPtr(T* const ptr) - : ptr_(0) - { - set(ptr); - } - SharedPtr(const SharedPtr& ptr) - : ptr_(0) - { - set(ptr.ptr_); - } - ~SharedPtr() - { - release(); - } - operator T*() const { - return get(); - } - template - operator SharedPtr() const { - return SharedPtr(get()); - } - SharedPtr& operator=(const SharedPtr& ptr) - { - set(ptr.ptr_); - return *this; - } - T* get() { return ptr_; } - T* get() const { return ptr_; } - T& operator*() - { - return *get(); - } - T* operator->() const { return get(); } - void release() - { - if (ptr_) - { - if (!ptr_->release()) - { - delete ptr_; - } - ptr_ = 0; - } - } - template - void set(_T* const ptr) { reset(ptr); } - template - void reset(_T* const ptr) - { - if (ptr_ != ptr) - { - release(); - ptr_ = ptr; - if (ptr_) - { - ptr_->acquire(); - } - } - } - protected: - T* ptr_; - }; - - - template - class AutoPtr - { - public: - AutoPtr() - : ptr_(0) - { - } - AutoPtr(T* ptr) - : ptr_(0) - { - set(ptr); - } - ~AutoPtr() - { - release(); - } - AutoPtr& operator=(T* ptr) - { - set(ptr); - return *this; - } - void set(T* ptr) - { - if (ptr_ && ptr_ != ptr) - { - release(); - } - ptr_ = ptr; - } - T* get() const { return ptr_; } - operator T*() const { - return get(); - } - void detach() - { - ptr_ = 0; - } - void release() - { - delete ptr_; - ptr_ = 0; - } - T& operator*() const { return *get(); } - T* operator->() const { return get(); } - private: - T* ptr_; - }; - - class IArchive; -} - -template -bool Serialize(Serialization::IArchive& ar, Serialization::SharedPtr& ptr, const char* name, const char* label); - -template -bool Serialize(Serialization::IArchive& ar, Serialization::PolyPtr& ptr, const char* name, const char* label); - -#include -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_POINTERS_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/PointersImpl.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/PointersImpl.h deleted file mode 100644 index 3d5d5d0c72..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/PointersImpl.h +++ /dev/null @@ -1,140 +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_EDITORCOMMON_SERIALIZATION_POINTERSIMPL_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_POINTERSIMPL_H -#pragma once - - -#include "Pointers.h" -#include "Serialization/IClassFactory.h" -#include "Serialization/ClassFactory.h" - -namespace Serialization { - template - class SharedPtrSerializer - : public IPointer - { - public: - SharedPtrSerializer(SharedPtr& ptr) - : ptr_(ptr) - {} - - const char* registeredTypeName() const - { - if (ptr_) - { - return ClassFactory::the().getRegisteredTypeName(ptr_.get()); - } - else - { - return ""; - } - } - void create(const char* typeName) const - { - YASLI_ASSERT(!ptr_ || ptr_->refCount() == 1); - if (typeName && typeName[0] != '\0') - { - ptr_.set(factory()->create(typeName)); - } - else - { - ptr_.set((T*)0); - } - } - TypeID baseType() const { return TypeID::get(); } - virtual SStruct serializer() const - { - return SStruct(*ptr_); - } - void* get() const - { - return reinterpret_cast(ptr_.get()); - } - const void* handle() const - { - return &ptr_; - } - TypeID pointerType() const - { - return TypeID::get >(); - } - virtual ClassFactory* factory() const{ return &ClassFactory::the(); } - - protected: - SharedPtr& ptr_; - }; - - template - class PolyPtrSerializer - : public IPointer - { - public: - PolyPtrSerializer(PolyPtr& ptr) - : ptr_(ptr) - {} - - TypeID type() const - { - if (ptr_) - { - return TypeID::get(ptr_.get()); - } - else - { - return TypeID(); - } - } - void create(TypeID type) const - { - // YASLI_ASSERT(!ptr_ || ptr_->refCount() == 1); not necessary to be true - if (type) - { - ptr_.set(ClassFactory::the().create(type)); - } - else - { - ptr_.set((T*)0); - } - } - TypeID baseType() const { return TypeID::get(); } - virtual SStruct serializer() const - { - return SStruct(*ptr_); - } - void* get() const - { - return reinterpret_cast(ptr_.get()); - } - IClassFactory* factory() const { return &ClassFactory::the(); } - - protected: - PolyPtr& ptr_; - }; -} - -template -bool Serialize(Serialization::IArchive& ar, Serialization::SharedPtr& ptr, const char* name, const char* label) -{ - return ar(static_cast(Serialization::SharedPtrSerializer(ptr)), name, label); -} - -template -bool Serialize(Serialization::IArchive& ar, Serialization::PolyPtr& ptr, const char* name, const char* label) -{ - return ar(static_cast(Serialization::PolyPtrSerializer(ptr)), name, label); -} -// vim:sw=4 ts=4: - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_POINTERSIMPL_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Qt.cpp b/Code/Sandbox/Plugins/EditorCommon/Serialization/Qt.cpp deleted file mode 100644 index f3001b95da..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Qt.cpp +++ /dev/null @@ -1,393 +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 "EditorCommon_precompiled.h" -#include "EditorCommonAPI.h" -#include "Serialization/Serializer.h" -#include "Serialization/Qt.h" -#include "Serialization/STL.h" -#include "Serialization/IArchive.h" -#include -#include -#include -#include -#include - -class StringQt - : public Serialization::IWString -{ -public: - StringQt(QString& str) - : str_(str) {} - - void set(const wchar_t* value) { str_.setUnicode((const QChar*)value, (int)wcslen(value)); } - const wchar_t* get() const { return (wchar_t*)str_.data(); } - const void* handle() const { return &str_; } - Serialization::TypeID type() const{ return Serialization::TypeID::get(); } -private: - QString& str_; -}; - -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QString& value, const char* name, const char* label) -{ - StringQt str(value); - return ar(static_cast(str), name, label); -} - -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QByteArray& byteArray, const char* name, const char* label) -{ - std::vector temp(byteArray.begin(), byteArray.end()); - if (!ar(temp, name, label)) - { - return false; - } - if (ar.IsInput()) - { - byteArray = QByteArray(temp.empty() ? (char*)0 : (char*)&temp[0], (int)temp.size()); - } - return true; -} - -QString GetIndexPath(QAbstractItemModel* model, const QModelIndex& index) -{ - QString path; - - QModelIndex cur = index; - while (cur.isValid() && cur != QModelIndex()) - { - if (!path.isEmpty()) - { - path = QString("|") + path; - } - path = model->data(cur).toString() + path; - cur = model->parent(cur); - } - return path; -} - -QModelIndex FindIndexChildByText(QAbstractItemModel* model, const QModelIndex& parent, const QString& text) -{ - int rowCount = model->rowCount(parent); - for (int i = 0; i < rowCount; ++i) - { - QModelIndex child = model->index(i, 0, parent); - QString childText = model->data(child).toString(); - if (childText == text) - { - return child; - } - } - return QModelIndex(); -} - -QModelIndex GetIndexByPath(QAbstractItemModel* model, const QString& path) -{ - QStringList items = path.split('|'); - QModelIndex cur = QModelIndex(); - for (int i = 0; i < items.size(); ++i) - { - cur = FindIndexChildByText(model, cur, items[i]); - if (!cur.isValid()) - { - return QModelIndex(); - } - } - return cur; -} - -std::vector GetIndexPaths(QAbstractItemModel* model, const QModelIndexList& indices) -{ - std::vector result; - for (int i = 0; i < indices.size(); ++i) - { - QString path = GetIndexPath(model, indices[i]); - if (!path.isEmpty()) - { - result.push_back(path); - } - } - return result; -} - -QModelIndexList GetIndicesByPath(QAbstractItemModel* model, const std::vector& paths) -{ - QModelIndexList result; - for (int i = 0; i < paths.size(); ++i) - { - QModelIndex index = GetIndexByPath(model, paths[i]); - if (index.isValid()) - { - result.push_back(index); - } - } - return result; -} - -struct QTreeViewStateSerializer -{ - QTreeView* treeView; - QTreeViewStateSerializer(QTreeView* treeView) - : treeView(treeView) {} - - void Serialize(Serialization::IArchive& ar) - { - QAbstractItemModel* model = treeView->model(); - - std::vector expandedItems; - if (ar.IsOutput()) - { - std::vector stack; - stack.push_back(QModelIndex()); - while (!stack.empty()) - { - QModelIndex index = stack.back(); - stack.pop_back(); - - int rowCount = model->rowCount(index); - for (int i = 0; i < rowCount; ++i) - { - QModelIndex child = model->index(i, 0, index); - if (treeView->isExpanded(child)) - { - stack.push_back(child); - expandedItems.push_back(GetIndexPath(model, child)); - } - } - } - } - ar(expandedItems, "expandedItems"); - if (ar.IsInput()) - { - treeView->collapseAll(); - for (size_t i = 0; i < expandedItems.size(); ++i) - { - QModelIndex index = GetIndexByPath(model, expandedItems[i]); - if (index.isValid()) - { - treeView->expand(index); - } - } - } - - std::vector selectedItems; - if (ar.IsOutput()) - { - selectedItems = GetIndexPaths(model, treeView->selectionModel()->selectedIndexes()); - } - ar(selectedItems, "selectedItems"); - if (ar.IsInput()) - { - QModelIndexList indices = GetIndicesByPath(model, selectedItems); - if (!indices.empty()) - { - treeView->selectionModel()->select(QModelIndex(), QItemSelectionModel::ClearAndSelect); - for (int i = 0; i < indices.size(); ++i) - { - treeView->selectionModel()->select(indices[i], QItemSelectionModel::Select); - } - } - } - - QString currentItem; - if (ar.IsOutput()) - { - currentItem = GetIndexPath(model, treeView->selectionModel()->currentIndex()); - } - ar(currentItem, "currentItem"); - if (ar.IsInput()) - { - QModelIndex currentIndex = GetIndexByPath(model, currentItem); - treeView->scrollTo(currentIndex, QAbstractItemView::PositionAtCenter); - treeView->selectionModel()->setCurrentIndex(currentIndex, QItemSelectionModel::Current); - } - - std::vector sectionsHidden; - std::vector sectionsVisible; - if (ar.IsOutput()) - { - for (int i = 0; i < treeView->model()->columnCount(); ++i) - { - if (treeView->header()->isSectionHidden(i)) - { - sectionsHidden.push_back(i); - } - else - { - sectionsVisible.push_back(i); - } - } - } - ar(sectionsHidden, "sectionsHidden"); - ar(sectionsVisible, "sectionsVisible"); - if (ar.IsInput()) - { - int columnCount = treeView->model()->columnCount(); - for (int i = 0; i < sectionsHidden.size(); ++i) - { - int section = sectionsHidden[i]; - if (section >= 0 && section < columnCount) - { - treeView->header()->hideSection(section); - } - } - for (int i = 0; i < sectionsVisible.size(); ++i) - { - int section = sectionsVisible[i]; - if (section >= 0 && section < columnCount) - { - treeView->header()->showSection(section); - } - } - } - } -}; - -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QTreeView* treeView, const char* name, const char* label) -{ - return ar(QTreeViewStateSerializer(treeView), name, label); -} - - -static const char* g_paletteColorGroupNames[QPalette::NColorGroups] = { - "Active", "Disabled", "Inactive" -}; - -static const char* g_paletteColorRoleNames[QPalette::NColorRoles] = { - "WindowText", "Button", "Light", "Midlight", "Dark", "Mid", - "Text", "BrightText", "ButtonText", "Base", "Window", "Shadow", - "Highlight", "HighlightedText", - "Link", "LinkVisited", - "AlternateBase", - "NoRole", - "ToolTipBase", "ToolTipText", -#if !defined(AZ_PLATFORM_LINUX) - "PlaceholderText", -#endif // !defined(AZ_PLATFORM_LINUX) -}; - -struct QPaletteSerializable -{ - QPalette& palette; - QPaletteSerializable(QPalette& palette) - : palette(palette) - { - } - - struct SRole - { - int role; - QPalette& palette; - - SRole(QPalette& palette, int role) - : palette(palette) - , role(role) - { - } - - void Serialize(Serialization::IArchive& ar) - { - for (int group = 0; group < QPalette::NColorGroups; ++group) - { - QColor color = palette.color(QPalette::ColorGroup(group), QPalette::ColorRole(role)); - ar(color, g_paletteColorGroupNames[group], g_paletteColorGroupNames[group]); - if (ar.IsInput()) - { - palette.setColor(QPalette::ColorGroup(group), QPalette::ColorRole(role), color); - } - } - } - }; - - void Serialize(Serialization::IArchive& ar) - { - for (int roleIndex = 0; roleIndex < QPalette::NColorRoles; ++roleIndex) - { - SRole role(palette, roleIndex); - ar(role, g_paletteColorRoleNames[roleIndex], g_paletteColorRoleNames[roleIndex]); - } - } -}; - -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QPalette& palette, const char* name, const char* label) -{ - QPaletteSerializable serializer(palette); - return ar(serializer, name, label); -} - -struct QColorSerializable -{ - QColor& color; - QColorSerializable(QColor& color) - : color(color) {} - - void Serialize(Serialization::IArchive& ar) - { - // this is not comprehensive, as QColor can store color components - // in diffrent models, depending on the way they were specified - unsigned char r = color.red(); - unsigned char g = color.green(); - unsigned char b = color.blue(); - unsigned char a = color.alpha(); - ar(r, "r", "^R"); - ar(g, "g", "^G"); - ar(b, "b", "^B"); - ar(a, "a", "^A"); - if (ar.IsInput()) - { - color.setRed(r); - color.setGreen(g); - color.setBlue(b); - color.setAlpha(a); - } - } -}; - -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QColor& color, const char* name, const char* label) -{ - QColorSerializable serializer(color); - return ar(serializer, name, label); -} - -struct QSplitterSerializer -{ - QSplitter& splitter; - - QSplitterSerializer(QSplitter& splitter) - : splitter(splitter) {} - - void Serialize(Serialization::IArchive& ar) - { - QList qsizes = splitter.sizes(); - std::vector sizes(qsizes.begin(), qsizes.end()); - ar(sizes, "sizes", "Sizes"); - if (ar.IsInput()) - { - qsizes.clear(); - for (int i = 0; i < sizes.size(); ++i) - { - qsizes.push_back(sizes[i]); - } - splitter.setSizes(qsizes); - } - } -}; - -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QSplitter* splitter, const char* name, const char* label) -{ - if (!splitter) - { - return false; - } - QSplitterSerializer serializer(*splitter); - return ar(serializer, name, label); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Qt.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Qt.h deleted file mode 100644 index c315567bb0..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Qt.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. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_QT_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_QT_H -#pragma once - -#include "EditorCommonAPI.h" - -class QByteArray; -class QColor; -class QPalette; -class QSplitter; -class QString; -class QTreeView; - -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QSplitter* splitter, const char* name, const char* label); -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QByteArray& value, const char* name, const char* label); -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QString& value, const char* name, const char* label); -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QTreeView* treeViewState, const char* name, const char* label); -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QPalette& palette, const char* name, const char* label); -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QColor& color, const char* name, const char* label); -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_QT_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/QtImpl.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/QtImpl.h deleted file mode 100644 index 299e9be568..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/QtImpl.h +++ /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. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_QTIMPL_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_QTIMPL_H -#pragma once - -#include "Serialization/Serializer.h" - -namespace Serialization { -} - - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_QTIMPL_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Token.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Token.h deleted file mode 100644 index 1c9f803e55..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Token.h +++ /dev/null @@ -1,93 +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_EDITORCOMMON_SERIALIZATION_TOKEN_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_TOKEN_H -#pragma once - -#include - -#include "Serialization/Strings.h" - -namespace Serialization { - struct Token - { - Token(const char* _str = 0) - : start(_str) - , end(_str ? _str + strlen(_str) : 0) - { - } - - Token(const char* _str, size_t _len) - : start(_str) - , end(_str + _len) {} - Token(const char* _start, const char* _end) - : start(_start) - , end(_end) {} - - void set(const char* _start, const char* _end) { start = _start; end = _end; } - std::size_t length() const{ return end - start; } - - bool operator==(const Token& rhs) const - { - if (length() != rhs.length()) - { - return false; - } - return memcmp(start, rhs.start, length()) == 0; - } - bool operator==(const string& rhs) const - { - if (length() != rhs.size()) - { - return false; - } - return memcmp(start, rhs.c_str(), length()) == 0; - } - - bool operator==(const char* text) const - { - if (strncmp(text, start, length()) == 0) - { - return text[length()] == '\0'; - } - return false; - } - bool operator!=(const char* text) const - { - if (strncmp(text, start, length()) == 0) - { - return text[length()] != '\0'; - } - return true; - } - bool operator==(char c) const - { - return length() == 1 && *start == c; - } - bool operator!=(char c) const - { - return length() != 1 || *start != c; - } - - operator bool() const{ - return start != end; - } - string str() const{ return string(start, end); } - - const char* start; - const char* end; - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_TOKEN_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/yasli_NOTICES.txt b/Code/Sandbox/Plugins/EditorCommon/Serialization/yasli_NOTICES.txt deleted file mode 100644 index 5e8ea4b43e..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/yasli_NOTICES.txt +++ /dev/null @@ -1,49 +0,0 @@ -Portions based on WWidgets and Yasli Serialization Library - -wWidgets - Lightweight UI Toolkit. -Copyright (C) 2009-2011 Evgeny Andreeshchev - Alexander Kotliar - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - - -Yasli Serialization Library -Copyright (c) 2007 Eugene Andreeshchev - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/Code/Sandbox/Plugins/EditorCommon/Timeline.cpp b/Code/Sandbox/Plugins/EditorCommon/Timeline.cpp deleted file mode 100644 index 49a3a07f35..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Timeline.cpp +++ /dev/null @@ -1,2728 +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 "EditorCommon_precompiled.h" -#include "Timeline.h" -#include "QtUtil.h" -#include "DrawingPrimitives/TimeSlider.h" -#include "DrawingPrimitives/Ruler.h" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#ifdef min -#undef min -#endif - -#ifdef max -#undef max -#endif - -int STimelineViewState::ScrollOffset(float origin) const -{ - return int((origin / visibleDistance + 0.5f) * widthPixels); -} - -int STimelineViewState::TimeToLayout(float time) const -{ - return int((time / visibleDistance) * widthPixels + 0.5f); -} - -int STimelineViewState::TimeToLocal(float time) const -{ - return TimeToLayout(time) + treeWidth + scrollPixels.x(); -} - -float STimelineViewState::LayoutToTime(int x) const -{ - return (float(x) - 0.5f) / widthPixels * visibleDistance; -} - -float STimelineViewState::LocalToTime(int x) const -{ - return LayoutToTime(x - treeWidth - scrollPixels.x()); -} - -QPoint STimelineViewState::LocalToLayout(const QPoint& p) const -{ - return p - scrollPixels - QPoint(treeWidth, 0); -} - -QPoint STimelineViewState::LayoutToLocal(const QPoint& p) const -{ - return p + scrollPixels + QPoint(treeWidth, 0); -} - -enum -{ - THUMB_WIDTH = 12, - THUMB_HEIGHT = 24, - - RULER_HEIGHT = 16, - RULER_SHADOW_HEIGHT = 6, - RULER_MARK_HEIGHT = 8, - - TRACK_MARK_HEIGHT = 6, - - DEFAULT_KEY_WIDTH = 8, - VERTICAL_PADDING = 4, - TRACK_DESCRIPTION_INDENT = 8, - - SELECTION_WIDTH = 4, - SCROLL_SHADOW_WIDTH = 8, - - MAX_PUSH_OUT = VERTICAL_PADDING * 2, - PUSH_OUT_DISTANCE = 3, - - SPLITTER_WIDTH = 10, - - DEFAULT_TREE_WIDTH = 200, - TREE_LEFT_MARGIN = 6, - TREE_INDENT_MULTIPLIER = 12, - TREE_BRANCH_INDICATOR_SIZE = 8 -}; - -namespace -{ - const float DEFAULT_KEY_RADIUS = 0.1f; - const int TIMELINE_PADDING = 20; -} - -struct STimelineContentElementRef -{ - STimelineContentElementRef() - : pTrack(nullptr) - , index(0) - {} - - STimelineContentElementRef(STimelineTrack* pTrack, size_t index) - : pTrack(pTrack) - , index(index) - {} - - STimelineElement& GetElement() const - { - return pTrack->elements[index]; - } - - bool IsValid() const { return pTrack != 0 && index < pTrack->elements.size(); } - - bool operator<(const STimelineContentElementRef& rhs) const - { - if (pTrack == rhs.pTrack) - { - return index < rhs.index; - } - else - { - if (!pTrack && rhs.pTrack) - { - return true; - } - else if (pTrack && !rhs.pTrack) - { - return false; - } - else if (pTrack && rhs.pTrack) - { - return pTrack->name < rhs.pTrack->name; - } - return false; - } - } - - STimelineTrack* pTrack; - size_t index; -}; - -struct SElementLayout -{ - STimelineElement::EType type; - int caps; - float pushOutDistance; - QRect rect; - ColorB color; - string description; - - STimelineContentElementRef elementRef; - std::vector subElements; - - bool IsSelected() const - { - if ((elementRef.pTrack->caps & STimelineTrack::CAP_COMPOUND_TRACK) == 0) - { - return elementRef.GetElement().selected; - } - else - { - bool bSelected = false; - const size_t numSubElements = subElements.size(); - - for (size_t i = 0; i < numSubElements; ++i) - { - bSelected = bSelected || subElements[i].GetElement().selected; - } - - return bSelected; - } - } - - void SetSelected(const bool bSelected) const - { - if ((elementRef.pTrack->caps & STimelineTrack::CAP_COMPOUND_TRACK) == 0) - { - elementRef.GetElement().selected = bSelected; - } - else - { - const size_t numSubElements = subElements.size(); - for (size_t i = 0; i < numSubElements; ++i) - { - subElements[i].GetElement().selected = bSelected; - } - } - } - - SElementLayout() - : pushOutDistance(0.0f) - , caps(0) - , type(STimelineElement::KEY) - {} -}; - -struct STrackLayout; -typedef std::vector STrackLayouts; - -struct STrackLayout -{ - QRect rect; - int indent; - - STimelineTrack* pTimelineTrack; - - std::vector elements; - STrackLayouts tracks; - - STrackLayout() - : indent(0) - , pTimelineTrack(0) - { - } -}; - -struct STimelineLayout -{ - int thumbPositionX; - STrackLayouts tracks; - SAnimTime minStartTime; - SAnimTime maxEndTime; - QSize size; - - STimelineLayout() - : thumbPositionX(0) - , minStartTime(0.0f) - , maxEndTime(1.0f) - , size(1, 1) - { - } -}; - -namespace -{ - QColor InterpolateColor(const QColor& a, const QColor& b, float k) - { - float mk = 1.0f - k; - return QColor(aznumeric_cast(a.red() * mk + b.red() * k), - aznumeric_cast(a.green() * mk + b.green() * k), - aznumeric_cast(a.blue() * mk + b.blue() * k), - aznumeric_cast(a.alpha() * mk + b.alpha() * k)); - } - - void ClampViewOrigin(STimelineViewState* viewState, const STimelineLayout& layout) - { - float zoomOffset = viewState->visibleDistance * 0.5f; - - const float padding = viewState->LayoutToTime(TIMELINE_PADDING); - float maxViewOrigin = layout.minStartTime.ToFloat() - zoomOffset + padding; - float minViewOrigin = std::min(viewState->visibleDistance - layout.maxEndTime.ToFloat() - zoomOffset - padding, maxViewOrigin); - - viewState->viewOrigin = clamp_tpl(viewState->viewOrigin, minViewOrigin, maxViewOrigin); - } - - SElementLayout& AddElementToTrackLayout(STimelineTrack& track, STrackLayout& trackLayout, const STimelineElement& element, - const STimelineViewState& viewState, uint keyWidth, [[maybe_unused]] int treeWidth, int& currentTop, size_t elementIndex) - { - trackLayout.elements.push_back(SElementLayout()); - SElementLayout& elementl = trackLayout.elements.back(); - elementl.color = element.color; - elementl.type = element.type; - elementl.caps = element.caps; - elementl.description = element.description; - elementl.elementRef.pTrack = &track; - elementl.elementRef.index = elementIndex; - - if (element.type == STimelineElement::KEY) - { - int left = (viewState.TimeToLayout(element.start.ToFloat()) - keyWidth / 2); - int right = left + keyWidth; - elementl.rect = QRect(left, currentTop + VERTICAL_PADDING, right - left, track.height - VERTICAL_PADDING * 2); - } - else - { - int left = viewState.TimeToLayout(element.start.ToFloat()); - int right = viewState.TimeToLayout(element.end.ToFloat()); - elementl.rect = QRect(left, currentTop + VERTICAL_PADDING, right - left, track.height - VERTICAL_PADDING * 2); - } - - return elementl; - } - - void AddCompoundElementsToTrackLayout(STimelineTrack& track, STimelineLayout* layout, const STimelineViewState& viewState, int trackId, uint keyWidth, int treeWidth, int& currentTop) - { - const size_t numSubTracks = track.tracks.size(); - SAnimTime currentElementTime = SAnimTime::Min(); - size_t* pCurrentSubTrackIndices = static_cast(alloca(sizeof(size_t) * numSubTracks)); - memset(pCurrentSubTrackIndices, 0, sizeof(size_t) * numSubTracks); - - while (true) - { - bool bElementFound = false; - SAnimTime minElementTime = SAnimTime::Max(); - - // First search for minimum element time for current track positions - for (size_t i = 0; i < numSubTracks; ++i) - { - const STimelineTrack& subTrack = *track.tracks[i]; - const STimelineElements& elements = subTrack.elements; - const size_t numTrackElements = elements.size(); - const size_t index = pCurrentSubTrackIndices[i]; - - if (index < numTrackElements) - { - const SAnimTime elementTime = elements[index].start; - minElementTime = min(elementTime, minElementTime); - bElementFound = true; - } - } - - if (!bElementFound) - { - break; - } - - STimelineElement compoundElement; - compoundElement.start = minElementTime; - compoundElement.end = minElementTime; - - // If elements were found create a compound element - STrackLayout& trackLayout = layout->tracks[trackId]; - SElementLayout& compoundElementLayout = AddElementToTrackLayout(track, trackLayout, compoundElement, viewState, keyWidth, treeWidth, currentTop, 0); - currentElementTime = minElementTime; - - compoundElementLayout.description = "("; - - // Advance track positions and add elements IDs to compound element if times match - for (size_t i = 0; i < numSubTracks; ++i) - { - STimelineTrack* pSubTrack = track.tracks[i]; - const STimelineElements& elements = pSubTrack->elements; - const size_t numTrackElements = elements.size(); - size_t& index = pCurrentSubTrackIndices[i]; - - if (index < numTrackElements) - { - const SAnimTime elementTime = elements[index].start; - - if (elementTime == minElementTime) - { - STimelineContentElementRef ref; - ref.pTrack = pSubTrack; - ref.index = index; - compoundElementLayout.subElements.push_back(ref); - compoundElementLayout.description += elements[index].description; - ++index; - } - else - { - compoundElementLayout.description += "-"; - } - - if ((i + 1) < numSubTracks) - { - compoundElementLayout.description += ", "; - } - } - } - - compoundElementLayout.description += ")"; - } - } - - bool FilterTracks(const STimelineTrack& track, std::unordered_set& invisibleTracks, const char* filterString) - { - bool bAnyChildVisible = false; - const bool bNameMatchesFilter = CryStringUtils::stristr(track.name, filterString) != nullptr; - - if (!bNameMatchesFilter) - { - const size_t numChildTracks = track.tracks.size(); - for (size_t i = 0; i < numChildTracks; ++i) - { - bAnyChildVisible = FilterTracks(*track.tracks[i], invisibleTracks, filterString) || bAnyChildVisible; - } - } - - if (!bNameMatchesFilter && !bAnyChildVisible) - { - invisibleTracks.insert(&track); - } - - return bNameMatchesFilter || bAnyChildVisible; - } - - void CalculateMinMaxTime(STimelineLayout* layout, STimelineTrack& parentTrack) - { - layout->minStartTime = min(layout->minStartTime, parentTrack.startTime); - layout->maxEndTime = max(layout->maxEndTime, parentTrack.endTime); - - const size_t numTracks = parentTrack.tracks.size(); - for (size_t i = 0; i < numTracks; ++i) - { - STimelineTrack& track = *parentTrack.tracks[i]; - CalculateMinMaxTime(layout, track); - } - } - - void CalculateTrackLayout(STimelineLayout* layout, int& currentTop, int currentIndent, STimelineTrack& parentTrack, const STimelineViewState& viewState, - float thumbTime, uint keyWidth, int treeWidth, const std::unordered_set& invisibleTracks) - { - const size_t numTracks = parentTrack.tracks.size(); - for (size_t i = 0; i < numTracks; ++i) - { - STimelineTrack& track = *parentTrack.tracks[i]; - - if (stl::find(invisibleTracks, &track)) - { - continue; - } - - layout->tracks.push_back(STrackLayout()); - STrackLayout& trackLayout = layout->tracks.back(); - trackLayout.elements.reserve(track.elements.size()); - trackLayout.indent = currentIndent; - trackLayout.pTimelineTrack = &track; - - const bool bIsCompositeTrack = (track.caps & STimelineTrack::CAP_COMPOUND_TRACK) != 0; - - if (bIsCompositeTrack) - { - const int trackLayoutId = layout->tracks.size() - 1; - AddCompoundElementsToTrackLayout(track, layout, viewState, trackLayoutId, keyWidth, treeWidth, currentTop); - } - else - { - for (size_t i2 = 0; i2 < track.elements.size(); ++i2) - { - const STimelineElement& element = track.elements[i2]; - AddElementToTrackLayout(track, trackLayout, element, viewState, keyWidth, treeWidth, currentTop, i2); - } - } - - int left = viewState.TimeToLayout(track.startTime.ToFloat()); - int right = viewState.TimeToLayout(track.endTime.ToFloat()); - trackLayout.rect = QRect(left, currentTop, right - left, track.height); - currentTop += track.height; - - if (track.expanded) - { - CalculateTrackLayout(layout, currentTop, currentIndent + 1, track, viewState, thumbTime, keyWidth, treeWidth, invisibleTracks); - } - } - } - - void ApplyPushOut(STimelineLayout* layout, uint keyWidth) - { - float maxPushOut = 0.0f; - - const size_t numLayoutTracks = layout->tracks.size(); - for (size_t i = 0; i < numLayoutTracks; ++i) - { - STrackLayout& track = layout->tracks[i]; - - const size_t numElements = track.elements.size(); - for (size_t i2 = 0; i2 < numElements; ++i2) - { - if (track.elements[i2].type != STimelineElement::KEY) - { - continue; - } - - for (size_t j = 0; j < numElements; ++j) - { - if ((track.elements[j].type != STimelineElement::KEY) || (j == i2)) - { - continue; - } - - float distance = aznumeric_cast(track.elements[j].rect.left() - track.elements[i2].rect.left()); - float delta = clamp_tpl(1.0f - fabsf(distance) / keyWidth, 0.0f, 1.0f); - - if (delta == 0.0f) - { - continue; - } - - float& pushOutDistance = track.elements[i2].pushOutDistance; - pushOutDistance += (i2 < j) ? -delta : delta; - - if (fabsf(pushOutDistance) > maxPushOut) - { - maxPushOut = fabsf(pushOutDistance); - } - } - } - } - - float maxPushOutNormalized = float(MAX_PUSH_OUT) / PUSH_OUT_DISTANCE; - float pushOutScale = 1.0f; - - if (maxPushOut > maxPushOutNormalized && maxPushOut > 0.0f) - { - pushOutScale = maxPushOutNormalized / maxPushOut; - } - - for (size_t i = 0; i < numLayoutTracks; ++i) - { - STrackLayout& track = layout->tracks[i]; - - for (size_t j = 0; j < track.elements.size(); ++j) - { - track.elements[j].rect.translate(QPoint(0, int(pushOutScale * track.elements[j].pushOutDistance * PUSH_OUT_DISTANCE))); - } - } - } - - void CalculateLayout(STimelineLayout* layout, STimelineContent& content, const STimelineViewState& viewState, const QLineEdit* pFilterLineEdit, float thumbTime, uint keyWidth, bool treeVisible) - { - layout->thumbPositionX = viewState.TimeToLayout(thumbTime); - - if (!content.track.tracks.empty()) - { - layout->minStartTime = SAnimTime::Max(); - layout->maxEndTime = SAnimTime::Min(); - } - else - { - layout->minStartTime = SAnimTime(0.0f); - layout->maxEndTime = SAnimTime(1.0f); - } - - int currentTop = RULER_HEIGHT + VERTICAL_PADDING; - const int treeWidth = treeVisible ? viewState.treeWidth : 0; - - std::unordered_set invisibleTracks; - if (pFilterLineEdit && !pFilterLineEdit->text().isEmpty()) - { - FilterTracks(content.track, invisibleTracks, QtUtil::ToString(pFilterLineEdit->text())); - } - - CalculateMinMaxTime(layout, content.track); - CalculateTrackLayout(layout, currentTop, 0, content.track, viewState, thumbTime, keyWidth, treeWidth, invisibleTracks); - - layout->size = QSize(viewState.TimeToLayout(layout->maxEndTime.ToFloat()), currentTop + VERTICAL_PADDING); - } - - STrackLayout* HitTestTrack(STrackLayouts& tracks, const QPoint& point) - { - auto findIter = std::upper_bound(tracks.begin(), tracks.end(), point.y(), [&](int y, const STrackLayout& track) - { - return y < track.rect.bottom(); - }); - - if (findIter != tracks.end() && findIter->rect.contains(point)) - { - return &(*findIter); - } - - return nullptr; - } - - void ForEachTrack(STimelineTrack& track, AZStd::function fun) - { - fun(track); - - for (size_t i = 0; i < track.tracks.size(); ++i) - { - STimelineTrack& subTrack = *track.tracks[i]; - ForEachTrack(subTrack, fun); - } - } - - void ForEachElement(STimelineTrack& track, AZStd::function fun) - { - ForEachTrack(track, [&](STimelineTrack& subTrack) - { - for (size_t i = 0; i < subTrack.elements.size(); ++i) - { - fun(subTrack, subTrack.elements[i]); - } - }); - } - - void ForEachElementWithIndex(STimelineTrack& track, AZStd::function fun) - { - ForEachTrack(track, [&](STimelineTrack& subTrack) - { - for (size_t i = 0; i < subTrack.elements.size(); ++i) - { - fun(subTrack, subTrack.elements[i], i); - } - }); - } - - void ClearTrackSelection(STimelineTrack& track) - { - ForEachTrack(track, [](STimelineTrack& track) - { - track.selected = false; - }); - } - - void GetSelectedTracks(STimelineTrack& track, std::vector& tracks) - { - ForEachTrack(track, [&](STimelineTrack& track) - { - if (track.selected) - { - tracks.push_back(&track); - } - }); - } - - void ClearElementSelection(STimelineTrack& track) - { - ForEachElement(track, [](STimelineTrack& track, STimelineElement& element) - { - track.keySelectionChanged = track.keySelectionChanged || element.selected; - element.selected = false; - }); - } - - void SetSelectedElementTimes(STimelineTrack& track, const std::vector& times) - { - auto iter = times.begin(); - ForEachElement(track, [&](STimelineTrack& track, STimelineElement& element) - { - if (element.selected) - { - track.modified = true; - element.start = *(iter++); - } - }); - } - - std::vector GetSelectedElementTimes(STimelineTrack& track) - { - std::vector times; - ForEachElement(track, [&]([[maybe_unused]] STimelineTrack& track, STimelineElement& element) - { - if (element.selected) - { - times.push_back(element.start); - } - }); - return times; - } - - VectorSet GetSelectedElementsTimeSet(STimelineTrack& track) - { - VectorSet timeSet; - ForEachElement(track, [&]([[maybe_unused]] STimelineTrack& track, STimelineElement& element) - { - if (element.selected) - { - timeSet.insert(element.start); - } - }); - return timeSet; - } - - typedef std::vector > TSelectedElements; - TSelectedElements GetSelectedElements(STimelineTrack& track) - { - TSelectedElements elements; - - ForEachElement(track, [&](STimelineTrack& track, STimelineElement& element) - { - if (element.selected) - { - elements.push_back(std::make_pair(&track, &element)); - } - }); - - return elements; - } - - void MoveSelectedElements(STimelineTrack& track, SAnimTime delta) - { - ForEachElement(track, [&](STimelineTrack& track, STimelineElement& element) - { - if (element.selected) - { - track.modified = true; - element.start += delta; - } - }); - } - - void DeletedMarkedElements(STimelineTrack& track) - { - ForEachTrack(track, [&](STimelineTrack& track) - { - for (auto iter = track.elements.begin(); iter != track.elements.end(); ) - { - if (iter->deleted) - { - iter = track.elements.erase(iter); - } - else - { - ++iter; - } - } - }); - } - - void SelectElementsInRect(const STrackLayouts& tracks, const QRect& rect) - { - for (size_t j = 0; j < tracks.size(); ++j) - { - const STrackLayout& track = tracks[j]; - - for (size_t i = 0; i < track.elements.size(); ++i) - { - const SElementLayout& element = track.elements[i]; - - if ((element.caps & STimelineElement::CAP_SELECT) == 0) - { - continue; - } - - STimelineTrack* pTimelineTrack = element.elementRef.pTrack; - const bool bIsCompoundTrack = (pTimelineTrack->caps & STimelineTrack::CAP_COMPOUND_TRACK) != 0; - - if (element.rect.intersects(rect)) - { - if (!bIsCompoundTrack) - { - if (!element.elementRef.GetElement().selected) - { - element.elementRef.GetElement().selected = true; - element.elementRef.pTrack->keySelectionChanged = true; - } - } - else - { - const size_t numSubElements = element.subElements.size(); - - for (size_t k = 0; k < numSubElements; ++k) - { - if (!element.subElements[k].GetElement().selected) - { - element.subElements[k].GetElement().selected = true; - element.subElements[k].pTrack->keySelectionChanged = true; - } - } - } - } - } - - SelectElementsInRect(track.tracks, rect); - } - } - - typedef std::vector SElementLayoutPtrs; - bool HitTestElements(STrackLayouts& tracks, const QRect& rect, SElementLayoutPtrs& out) - { - bool bHit = false; - - for (size_t j = 0; j < tracks.size(); ++j) - { - STrackLayout& track = tracks[j]; - - for (size_t i = 0; i < track.elements.size(); ++i) - { - SElementLayout& element = track.elements[i]; - - if (element.rect.intersects(rect)) - { - out.push_back(&element); - bHit = true; - } - } - - bHit = bHit || HitTestElements(track.tracks, rect, out); - } - - return bHit; - } - - enum EPass - { - PASS_BACKGROUND, - PASS_SELECTION, - PASS_SHADOW, - PASS_MAIN, - NUM_PASSES - }; - - QBrush PickTrackBrush(const QPalette& palette, const STrackLayout& track) - { - const QColor trackColor = InterpolateColor(palette.color(QPalette::Mid), palette.color(QPalette::Window), 0.96f); - const QColor descriptionTrackColor = InterpolateColor(palette.color(QPalette::Mid), palette.color(QPalette::Window), 0.9f); - const QColor compositeTrackColor = InterpolateColor(palette.color(QPalette::Mid), palette.color(QPalette::Window), 0.85f); - const QColor selectionColor = InterpolateColor(palette.color(QPalette::Highlight), palette.color(QPalette::Window), 0.5f); - - const bool bIsDescriptionTrack = (track.pTimelineTrack->caps & STimelineTrack::CAP_DESCRIPTION_TRACK) != 0; - const bool bIsCompositeTrack = (track.pTimelineTrack->caps & STimelineTrack::CAP_COMPOUND_TRACK) != 0; - - const QColor color = bIsDescriptionTrack ? descriptionTrackColor : (bIsCompositeTrack ? compositeTrackColor : trackColor); - return QBrush(track.pTimelineTrack->selected ? InterpolateColor(color, selectionColor, 0.3f) : color); - } - - struct SElementLayoutIntCompareLeft - { - const bool operator()(const SElementLayout& a, int b) { return a.rect.left() < b; } - const bool operator()(int a, const SElementLayout& b) { return a < b.rect.left(); } - }; - - struct SElementLayoutIntCompareRight - { - const bool operator()(const SElementLayout& a, int b) { return a.rect.right() < b; } - const bool operator()(int a, const SElementLayout& b) { return a < b.rect.right(); } - }; - - void DrawTracks(QPainter& painter, const uint startPass, const uint endPass, const STimelineLayout& layout, const STimelineViewState& viewState, - const QPalette& palette, [[maybe_unused]] const QPoint& mousePos, bool hasFocus, int width, float keyRadius, float timeUnitScale, bool drawMarkers) - { - const STrackLayouts& tracks = layout.tracks; - - const int trackAreaLeft = viewState.LocalToLayout(QPoint(viewState.treeWidth, 0)).x(); - const int trackAreaRight = trackAreaLeft + width; - - const QColor textColor = palette.buttonText().color(); - QPen descriptionTextPen = QPen(InterpolateColor(textColor, palette.color(QPalette::Window), 0.5f)); - - DrawingPrimitives::STickOptions markOptions; - markOptions.m_rect = QRect(-viewState.scrollPixels.x(), 0, width - viewState.treeWidth, 0); - markOptions.m_visibleRange = Range(viewState.LocalToTime(viewState.treeWidth) * timeUnitScale, viewState.LocalToTime(width) * timeUnitScale); - markOptions.m_rulerRange = Range(layout.minStartTime.ToFloat() * timeUnitScale, layout.maxEndTime.ToFloat() * timeUnitScale); - markOptions.m_markHeight = TRACK_MARK_HEIGHT; - - // Precalculate ticks because they are the same for all tracks - std::vector ticks = DrawingPrimitives::CalculateTicks(markOptions.m_rect.width(), markOptions.m_visibleRange, markOptions.m_rulerRange, nullptr, nullptr); - - for (int i = startPass; i <= endPass; ++i) - { - EPass pass = (EPass)i; - - for (size_t j = 0; j < tracks.size(); ++j) - { - const STrackLayout& track = tracks[j]; - - const bool bIsDescriptionTrack = (track.pTimelineTrack->caps & STimelineTrack::CAP_DESCRIPTION_TRACK) != 0; - const bool bIsCompositeTrack = (track.pTimelineTrack->caps & STimelineTrack::CAP_COMPOUND_TRACK) != 0; - const bool bIsToggleTrack = (track.pTimelineTrack->caps & STimelineTrack::CAP_TOGGLE_TRACK) != 0; - - std::vector sortedElements = track.elements; - std::sort(sortedElements.begin(), sortedElements.end(), [](const SElementLayout& a, const SElementLayout& b) { return a.rect.left() < b.rect.left(); }); - const uint numElements = sortedElements.size(); - - if (pass == PASS_BACKGROUND) - { - painter.setPen(Qt::NoPen); - painter.setBrush(PickTrackBrush(palette, track)); - QRect backgroundRect = track.rect; - backgroundRect.setLeft(-viewState.scrollPixels.x()); - backgroundRect.setWidth(width); - painter.drawRect(backgroundRect); - - if (bIsDescriptionTrack) - { - painter.setPen(descriptionTextPen); - QRect textRect = track.rect; - textRect.moveLeft(textRect.left() - viewState.scrollPixels.x() + TRACK_DESCRIPTION_INDENT); - textRect.setWidth(width); - textRect.moveTop(textRect.top() + 1); - painter.drawText(textRect, QString(track.pTimelineTrack->name)); - } - - const int lineY = track.rect.bottom() + 1; - painter.setPen(QPen(InterpolateColor(palette.color(QPalette::Mid), palette.color(QPalette::Window), 0.75f))); - painter.drawLine(QPoint(trackAreaLeft, lineY), QPoint(trackAreaRight, lineY)); - - if (drawMarkers && !bIsDescriptionTrack) - { - markOptions.m_rect.setTop(track.rect.top()); - markOptions.m_rect.setBottom(track.rect.bottom()); - DrawingPrimitives::DrawTicks(ticks, painter, palette, markOptions); - } - - if (bIsToggleTrack) - { - const QColor toggleColor = InterpolateColor(QColor(255, 255, 255), palette.color(QPalette::Mid), 0.5f); - - const uint drawStart = track.pTimelineTrack->toggleDefaultState ? 0 : 1; - - painter.setBrush(QBrush(toggleColor)); - QRect toggleRect = track.rect; - toggleRect.setTop(toggleRect.top() + 2); - toggleRect.setBottom(toggleRect.bottom() - 2); - - for (uint i2 = drawStart; i2 <= numElements; i2 += 2) - { - const int left = (i2 == 0) ? (-viewState.scrollPixels.x()) : sortedElements[i2 - 1].rect.right(); - const int right = (i2 == numElements) ? (-viewState.scrollPixels.x() + width) : sortedElements[i2].rect.left(); - - toggleRect.setLeft(left); - toggleRect.setRight(right); - painter.drawRect(toggleRect); - } - } - - continue; - } - - auto begin = std::lower_bound(sortedElements.begin(), sortedElements.end(), -viewState.scrollPixels.x(), SElementLayoutIntCompareRight()); - auto end = std::upper_bound(sortedElements.begin(), sortedElements.end(), width - viewState.scrollPixels.x(), SElementLayoutIntCompareLeft()); - - if (begin != sortedElements.begin()) - { - --begin; - } - if (end != sortedElements.end()) - { - ++end; - } - - for (auto iter = begin; iter != end; ++iter) - { - const SElementLayout& element = *iter; - QRectF rect = QRectF(element.rect); - float ratio = 1.0f; - - if (rect.width() != 0) - { - ratio = rect.height() != 0 ? aznumeric_cast(rect.width() / float(rect.height())) : 1.0f; - } - - const bool bSelected = element.IsSelected(); - - if (element.type == STimelineElement::KEY) - { - float rx = keyRadius * 200.0f / ratio; - float ry = keyRadius * 200.0f; - - if (pass == PASS_SELECTION) - { - if (bSelected) - { - QRectF selectionRect = rect.adjusted(-SELECTION_WIDTH * 0.5f + 0.5f, -SELECTION_WIDTH * 0.5f + 0.5f, SELECTION_WIDTH * 0.5f - 0.5f, SELECTION_WIDTH * 0.5f - 0.5f); - painter.setPen(QPen(palette.color(hasFocus ? QPalette::Highlight : QPalette::Shadow), SELECTION_WIDTH)); - painter.setBrush(QBrush(Qt::NoBrush)); - painter.drawRoundedRect(selectionRect, rx, ry, Qt::RelativeSize); - } - } - else if (pass != PASS_SHADOW) - { - QRectF shadowRect = rect.adjusted(-1.0f, -0.5f, 1.0f, 1.5f); - painter.setPen(QPen(QColor(0, 0, 0, 128), 2.0f)); - painter.setBrush(QBrush(Qt::NoBrush)); - painter.drawRoundedRect(shadowRect, rx, ry, Qt::RelativeSize); - - painter.setPen(QPen(QColor(element.color.r, element.color.g, element.color.b, 255))); - painter.setBrush(QBrush(QColor(element.color.r, element.color.g, element.color.b, 255))); - painter.drawRoundedRect(rect, rx, ry, Qt::RelativeSize); - - QRect textRect = track.rect; - textRect.moveLeft(aznumeric_cast(rect.right() + TRACK_DESCRIPTION_INDENT)); - textRect.setTop(textRect.top() + 1); - - if ((iter + 1) != sortedElements.end()) - { - textRect.setRight((iter + 1)->rect.left() - 6); - } - - painter.setPen(descriptionTextPen); - const QString elidedText = painter.fontMetrics().elidedText(element.description.c_str(), Qt::ElideRight, textRect.width()); - painter.drawText(textRect, Qt::TextSingleLine, elidedText); - } - } - else - { - float radius = 0.2f; - float rx = radius * 200.0f / ratio; - float ry = radius * 200.0f; - - if (pass == PASS_SELECTION) - { - if (bSelected) - { - QRectF selectionRect = rect.adjusted(-SELECTION_WIDTH * 0.5f + 0.5f, -SELECTION_WIDTH * 0.5f + 0.5f, SELECTION_WIDTH * 0.5f - 0.5f, SELECTION_WIDTH * 0.5f - 0.5f); - painter.setPen(QPen(palette.color(hasFocus ? QPalette::Highlight : QPalette::Shadow), SELECTION_WIDTH)); - painter.setBrush(QBrush(Qt::NoBrush)); - painter.drawRoundedRect(selectionRect, rx, ry, Qt::RelativeSize); - } - } - else if (pass == PASS_SHADOW) - { - QRectF shadowRect = rect.adjusted(0.0f, 0.0f, 0.0f, 1.0f); - painter.setPen(QPen(QColor(0, 0, 0, 128), 2.0f)); - painter.setBrush(QBrush(Qt::NoBrush)); - painter.drawRoundedRect(shadowRect, radius * 200.0f / ratio, radius * 200.0f, Qt::RelativeSize); - } - else - { - painter.setPen(QPen(QColor(element.color.r, element.color.g, element.color.b, 255))); - painter.setBrush(QBrush(QColor(element.color.r, element.color.g, element.color.b, 128))); - painter.drawRoundedRect(rect, radius * 200.0f / ratio, radius * 200.0f, Qt::RelativeSize); - } - } - } - } - } - } - - void DrawSelectionLines(QPainter& painter, const QPalette& palette, const STimelineViewState& viewState, STimelineContent& content, [[maybe_unused]] int rulerPrecision, [[maybe_unused]] int width, int height, [[maybe_unused]] float time, [[maybe_unused]] float timeUnitScale, bool hasFocus) - { - const VectorSet times = GetSelectedElementsTimeSet(content.track); - - QColor indicatorColor = palette.color(hasFocus ? QPalette::Highlight : QPalette::Shadow); - indicatorColor.setAlpha(70); - - for (auto iter = times.begin(); iter != times.end(); ++iter) - { - const float indicatorX = viewState.TimeToLocal(iter->ToFloat()) + 0.5f; - painter.setPen(indicatorColor); - painter.drawLine(QPointF(indicatorX, 0), QPointF(indicatorX, height)); - } - } - - void DrawTree(QPainter& painter, const QRect& treeRect, const QPalette& palette, QWidget* timeline, [[maybe_unused]] const STimelineContent& content, const STrackLayouts& tracks, const STimelineViewState& viewState, int scroll) - { - painter.save(); - - painter.setClipRect(treeRect); - painter.setClipping(true); - - painter.translate(0, -scroll); - - QTextOption textOption; - textOption.setWrapMode(QTextOption::NoWrap); - - const QColor textColor = palette.buttonText().color(); - - QStyleOptionFrame opt; - opt.palette = palette; - opt.state = QStyle::State_Enabled; - opt.rect = QRect(treeRect.left(), treeRect.top() - 1, treeRect.width(), treeRect.height() + 2); - - // Draw frame around tree - timeline->style()->drawPrimitive(QStyle::PE_Frame, &opt, &painter, timeline); - - for (size_t i = 0; i < tracks.size(); ++i) - { - const STrackLayout& track = tracks[i]; - - const QRect backgroundRect(1, track.rect.top() + 1, viewState.treeWidth - SPLITTER_WIDTH - 1, track.rect.height() - 1); - - const bool bIsDescriptionTrack = (track.pTimelineTrack->caps & STimelineTrack::CAP_DESCRIPTION_TRACK) != 0; - const bool bIsCompositeTrack = (track.pTimelineTrack->caps & STimelineTrack::CAP_COMPOUND_TRACK) != 0; - - painter.setPen(Qt::NoPen); - painter.setBrush(PickTrackBrush(palette, track)); - painter.drawRect(backgroundRect); - - const int branchLeft = TREE_LEFT_MARGIN + track.indent * TREE_INDENT_MULTIPLIER; - - if (track.pTimelineTrack->tracks.size() > 0) - { - QStyleOptionViewItem opt2; - opt2.rect = QRect(branchLeft, track.rect.top() + 1, TREE_BRANCH_INDICATOR_SIZE, track.rect.height() - 2); - opt2.state = QStyle::State_Enabled | QStyle::State_Children; - opt2.state |= track.pTimelineTrack->expanded ? QStyle::State_Open : QStyle::State_None; - - timeline->style()->drawPrimitive(QStyle::PE_IndicatorBranch, &opt2, &painter, timeline); - } - - const int textLeft = branchLeft + TREE_BRANCH_INDICATOR_SIZE + 4; - const int textWidth = std::max(treeRect.width() - textLeft - 4, 0); - const QRect textRect(textLeft, track.rect.top() + 1, textWidth, track.rect.height() - 2); - painter.setPen(QPen(textColor)); - painter.drawText(textRect, QString(track.pTimelineTrack->name), textOption); - } - - for (size_t i = 0; i < tracks.size(); ++i) - { - const STrackLayout& track = tracks[i]; - - const int lineY = track.rect.bottom() + 1; - painter.setPen(QPen(InterpolateColor(palette.color(QPalette::Mid), palette.color(QPalette::Window), 0.75f))); - painter.drawLine(QPoint(0, lineY), QPoint(treeRect.width(), lineY)); - } - - painter.restore(); - } - - void DrawSplitter(QPainter& painter, const QRect& splitterRect, const QPalette& palette, QWidget* timeline) - { - painter.fillRect(splitterRect, palette.color(QPalette::Window)); - - // Draw frame around splitter - QStyleOptionFrame frameOpt; - frameOpt.palette = palette; - frameOpt.state = QStyle::State_Enabled; - frameOpt.rect = QRect(splitterRect.left(), splitterRect.top(), splitterRect.width(), splitterRect.height() + 2); - timeline->style()->drawPrimitive(QStyle::PE_Frame, &frameOpt, &painter, timeline); - - // Draw resize handle dots - QStyleOption option; - option.palette = palette; - option.rect = QRect(splitterRect.left(), splitterRect.top() - 1, splitterRect.width() - 2, splitterRect.height() + 2); - timeline->style()->drawPrimitive(QStyle::PE_IndicatorDockWidgetResizeHandle, &option, &painter, timeline); - } -} - -struct CTimeline::SMouseHandler -{ - virtual ~SMouseHandler() = default; - virtual void mousePressEvent([[maybe_unused]] QMouseEvent* ev) {} - virtual void mouseDoubleClickEvent([[maybe_unused]] QMouseEvent* ev) {} - virtual void mouseMoveEvent([[maybe_unused]] QMouseEvent* ev) {} - virtual void mouseReleaseEvent([[maybe_unused]] QMouseEvent* ev) {} - virtual void focusOutEvent([[maybe_unused]] QFocusEvent* ev) {} - virtual void paintOver([[maybe_unused]] QPainter& painter) {} -}; - -struct CTimeline::SSelectionHandler - : SMouseHandler -{ - CTimeline* m_timeline; - QPoint m_startPoint; - QRect m_rect; - bool m_add; - TSelectedElements m_oldSelectedElements; - - SSelectionHandler(CTimeline* timeline, bool add) - : m_timeline(timeline) - , m_add(add) - { - if (m_timeline->m_pContent) - { - m_oldSelectedElements = GetSelectedElements(m_timeline->m_pContent->track); - } - } - - void mousePressEvent(QMouseEvent* ev) override - { - const int scroll = m_timeline->m_scrollBar ? m_timeline->m_scrollBar->value() : 0; - const QPoint pos(ev->pos().x(), ev->pos().y() + scroll); - m_startPoint = m_timeline->m_viewState.LocalToLayout(pos); - m_rect = QRect(m_startPoint, m_startPoint + QPoint(1, 1)); - } - - void mouseMoveEvent(QMouseEvent* ev) override - { - const int scroll = m_timeline->m_scrollBar ? m_timeline->m_scrollBar->value() : 0; - const QPoint pos(ev->pos().x(), ev->pos().y() + scroll); - m_rect = QRect(m_startPoint, m_timeline->m_viewState.LocalToLayout(pos) + QPoint(1, 1)); - Apply(true); - } - - void Apply(bool continuous) - { - if (m_timeline->m_pContent) - { - const TSelectedElements selectedElements = GetSelectedElements(m_timeline->m_pContent->track); - - ClearElementSelection(m_timeline->m_pContent->track); - SelectElementsInRect(m_timeline->m_layout->tracks, m_rect); - - const TSelectedElements newSelectedElements = GetSelectedElements(m_timeline->m_pContent->track); - if ((continuous && selectedElements != newSelectedElements) - || (!continuous && m_oldSelectedElements != newSelectedElements)) - { - m_timeline->SignalSelectionChanged(continuous); - } - } - } - - void mouseReleaseEvent([[maybe_unused]] QMouseEvent* ev) override - { - Apply(false); - } - - void paintOver(QPainter& painter) override - { - painter.save(); - QColor highlightColor = m_timeline->palette().color(QPalette::Highlight); - QColor highlightColorA = QColor(highlightColor.red(), highlightColor.green(), highlightColor.blue(), 128); - painter.setPen(QPen(highlightColor)); - painter.setBrush(QBrush(highlightColorA)); - painter.drawRect(QRectF(m_rect)); - painter.restore(); - } -}; - -static STimelineElement* NextSelectedElement(const SElementLayoutPtrs& array, STimelineElement* nextToValue, STimelineElement* defaultValue) -{ - for (size_t i = 0; i < array.size(); ++i) - { - if (&array[i]->elementRef.GetElement() == nextToValue) - { - return &array[(i + 1) % array.size()]->elementRef.GetElement(); - } - } - return defaultValue; -} - -struct CTimeline::SMoveHandler - : SMouseHandler -{ - CTimeline* m_timeline; - QPoint m_startPoint; - bool m_cycleSelection; - SAnimTime m_startTime; - SAnimTime m_newTime; - std::vector m_elementTimes; - - SMoveHandler(CTimeline* timeline, bool cycleSelection) - : m_timeline(timeline) - , m_cycleSelection(cycleSelection) {} - - void mousePressEvent(QMouseEvent* ev) override - { - m_startTime = m_timeline->m_time; - m_newTime = m_startTime; - - const int scroll = m_timeline->m_scrollBar ? m_timeline->m_scrollBar->value() : 0; - const QPoint currentPos(ev->pos().x(), ev->pos().y() + scroll); - - m_startPoint = m_timeline->m_viewState.LocalToLayout(QPoint(currentPos)); - m_elementTimes = GetSelectedElementTimes(m_timeline->m_pContent->track); - } - - void mouseMoveEvent(QMouseEvent* ev) override - { - if (m_timeline->m_viewState.widthPixels == 0) - { - return; - } - - const int scroll = m_timeline->m_scrollBar ? m_timeline->m_scrollBar->value() : 0; - const QPoint currentPos(ev->pos().x(), ev->pos().y() + scroll); - - int delta = m_timeline->m_viewState.LocalToLayout(currentPos).x() - m_startPoint.x(); - - const TSelectedElements selectedElements = GetSelectedElements(m_timeline->m_pContent->track); - - SetSelectedElementTimes(m_timeline->m_pContent->track, m_elementTimes); - - SAnimTime minDeltaTime = SAnimTime::Min(); - SAnimTime maxDeltaTime = SAnimTime::Max(); - SAnimTime minKeyTime = SAnimTime::Min(); - - for (size_t i = 0; i < selectedElements.size(); ++i) - { - const STimelineTrack& track = *selectedElements[i].first; - const STimelineElement& element = *selectedElements[i].second; - - SAnimTime minStartDelta = track.startTime - element.start; - minDeltaTime = max(minStartDelta, minDeltaTime); - SAnimTime maxEndDelta = track.endTime - (element.type == element.CLIP ? element.end : element.start); - maxDeltaTime = min(maxEndDelta, maxDeltaTime); - - minKeyTime = min(element.start, minKeyTime); - } - - SAnimTime deltaTime = SAnimTime(float(delta) / m_timeline->m_viewState.widthPixels * m_timeline->m_viewState.visibleDistance); - if (m_timeline->m_snapKeys) - { - SAnimTime newMinKeyTime = minKeyTime + deltaTime; - newMinKeyTime = newMinKeyTime.SnapToNearest(m_timeline->m_frameRate); - deltaTime = newMinKeyTime - minKeyTime; - } - - deltaTime = clamp_tpl(deltaTime, minDeltaTime, maxDeltaTime); - - m_newTime = m_startTime + deltaTime; - - MoveSelectedElements(m_timeline->m_pContent->track, deltaTime); - - m_timeline->ContentChanged(true); - - m_timeline->setCursor(Qt::SizeHorCursor); - m_cycleSelection = false; - } - - void focusOutEvent([[maybe_unused]] QFocusEvent* ev) - { - SetSelectedElementTimes(m_timeline->m_pContent->track, m_elementTimes); - m_timeline->UpdateLayout(); - } - - void mouseReleaseEvent(QMouseEvent* ev) - { - if (m_cycleSelection) - { - SElementLayoutPtrs hitElements; - - const int scroll = m_timeline->m_scrollBar ? m_timeline->m_scrollBar->value() : 0; - const QPoint currentPos(ev->pos().x(), ev->pos().y() + scroll); - - QPoint posInLayoutSpace = m_timeline->m_viewState.LocalToLayout(currentPos); - HitTestElements(m_timeline->m_layout->tracks, QRect(posInLayoutSpace - QPoint(2, 2), posInLayoutSpace + QPoint(2, 2)), hitElements); - - if (!hitElements.empty()) - { - TSelectedElements selectedElements = GetSelectedElements(m_timeline->m_pContent->track); - if (selectedElements.size() == 1) - { - STimelineElement* lastSelection = selectedElements[0].second; - - ClearElementSelection(m_timeline->m_pContent->track); - NextSelectedElement(hitElements, lastSelection, &hitElements.back()->elementRef.GetElement())->selected = true; - m_timeline->SignalSelectionChanged(false); - } - else - { - ClearElementSelection(m_timeline->m_pContent->track); - hitElements.back()->elementRef.GetElement().selected = true; - m_timeline->SignalSelectionChanged(false); - } - } - } - - m_timeline->ContentChanged(false); - } -}; - -struct CTimeline::SPanHandler - : SMouseHandler -{ - CTimeline* m_timeline; - QPoint m_startPoint; - float m_startOrigin; - - SPanHandler(CTimeline* timeline) - : m_timeline(timeline) - { - } - - void mousePressEvent(QMouseEvent* ev) override - { - m_startPoint = QPoint(int(ev->x()), int(ev->y())); - m_startOrigin = m_timeline->m_viewState.viewOrigin; - } - - void mouseMoveEvent(QMouseEvent* ev) override - { - QPoint pos(int(ev->x()), int(ev->y())); - float delta = 0.0f; - - if (m_timeline->m_viewState.widthPixels != 0) - { - delta = (pos - m_startPoint).x() * m_timeline->m_viewState.visibleDistance / m_timeline->m_viewState.widthPixels; - } - - m_timeline->m_viewState.viewOrigin = m_startOrigin + delta; - ClampViewOrigin(&m_timeline->m_viewState, *m_timeline->m_layout); - } - - void mouseReleaseEvent([[maybe_unused]] QMouseEvent* ev) override - { - } -}; - -struct CTimeline::SScrubHandler - : SMouseHandler -{ - CTimeline* m_timeline; - SScrubHandler(CTimeline* timeline) - : m_timeline(timeline) {} - SAnimTime m_startThumbPosition; - QPoint m_startPoint; - - void SetThumbPositionX(int positionX) - { - SAnimTime time = SAnimTime(m_timeline->m_viewState.LayoutToTime(positionX)); - - m_timeline->ClampAndSetTime(time, false); - } - - void mousePressEvent(QMouseEvent* ev) override - { - QPoint point = QPoint(ev->pos().x(), ev->pos().y()); - - QPoint posInLayout = m_timeline->m_viewState.LocalToLayout(point); - - int thumbPositionX = m_timeline->m_viewState.TimeToLayout(m_timeline->m_time.ToFloat()); - QRect thumbRect(thumbPositionX - THUMB_WIDTH / 2, 0, THUMB_WIDTH, THUMB_HEIGHT); - - if (!thumbRect.contains(posInLayout)) - { - SetThumbPositionX(m_timeline->m_viewState.LocalToLayout(point).x()); - } - - m_startThumbPosition = m_timeline->m_time; - m_startPoint = point; - } - - void Apply(QMouseEvent* ev, [[maybe_unused]] bool continuous) - { - QPoint point = QPoint(ev->pos().x(), ev->pos().y()); - - bool shift = ev->modifiers().testFlag(Qt::ShiftModifier); - bool control = ev->modifiers().testFlag(Qt::ControlModifier); - - float delta = 0.0f; - - if (m_timeline->m_viewState.widthPixels != 0) - { - delta = (point.x() - m_startPoint.x()) * m_timeline->m_viewState.visibleDistance / m_timeline->m_viewState.widthPixels; - } - - if (shift) - { - delta *= 0.01f; - } - - if (control) - { - delta *= 0.1f; - } - - m_timeline->ClampAndSetTime(m_startThumbPosition + SAnimTime(delta), true); - } - - void mouseMoveEvent(QMouseEvent* ev) override - { - Apply(ev, true); - } - - void mouseReleaseEvent(QMouseEvent* ev) override - { - Apply(ev, false); - } -}; - -struct CTimeline::SSplitterHandler - : SMouseHandler -{ - CTimeline* m_timeline; - int m_offset; - bool m_movedSlider; - - SSplitterHandler(CTimeline* timeline) - : m_timeline(timeline) - , m_offset(0) - , m_movedSlider(false) {} - - void mousePressEvent(QMouseEvent* ev) override - { - m_offset = m_timeline->m_viewState.treeWidth - ev->pos().x(); - } - - void mouseReleaseEvent([[maybe_unused]] QMouseEvent* ev) override - { - if (!m_movedSlider) - { - STimelineViewState& viewState = m_timeline->m_viewState; - - if (viewState.treeWidth == SPLITTER_WIDTH) - { - viewState.treeWidth = viewState.treeLastOpenedWidth; - } - else - { - viewState.treeLastOpenedWidth = viewState.treeWidth; - viewState.treeWidth = SPLITTER_WIDTH; - } - - m_timeline->UpdateLayout(); - m_timeline->update(); - } - } - - void mouseMoveEvent(QMouseEvent* ev) override - { - m_timeline->setCursor(QCursor(Qt::SplitHCursor)); - uint treeWidth = clamp_tpl(ev->pos().x(), SPLITTER_WIDTH, m_timeline->width()) + m_offset; - m_timeline->m_viewState.treeWidth = treeWidth; - m_timeline->m_viewState.treeLastOpenedWidth = treeWidth; - m_timeline->UpdateLayout(); - m_timeline->update(); - m_movedSlider = true; - } -}; - -struct CTimeline::STreeMouseHandler - : SMouseHandler -{ - CTimeline* m_timeline; - STreeMouseHandler(CTimeline* timeline) - : m_timeline(timeline) {} - - void mousePressEvent(QMouseEvent* ev) override - { - const bool bCtrlPressed = (ev->modifiers() & Qt::CTRL) != 0; - const bool bShiftPressed = (ev->modifiers() & Qt::SHIFT) != 0; - - const int scroll = m_timeline->m_scrollBar ? m_timeline->m_scrollBar->value() : 0; - const QPoint pos(ev->pos().x(), ev->pos().y() + scroll); - - STrackLayout* pTrackLayout = m_timeline->GetTrackLayoutFromPos(pos); - - if (!pTrackLayout) - { - if (!bShiftPressed && !bCtrlPressed) - { - ClearTrackSelection(m_timeline->m_pContent->track); - } - } - else - { - const int left = TREE_LEFT_MARGIN + pTrackLayout->indent * TREE_INDENT_MULTIPLIER; - const int right = left + TREE_BRANCH_INDICATOR_SIZE; - - const int x = pos.x(); - - if (x >= left && x <= right) - { - ToggleTrackExpansion(pTrackLayout); - } - else - { - const bool bPreviousState = pTrackLayout->pTimelineTrack->selected; - - if (!bCtrlPressed) - { - ClearTrackSelection(m_timeline->m_pContent->track); - } - - if (bCtrlPressed) - { - pTrackLayout->pTimelineTrack->selected = !bPreviousState; - } - else if (bShiftPressed) - { - STrackLayouts& tracks = m_timeline->m_layout->tracks; - - auto startFindIter = std::find_if(tracks.begin(), tracks.end(), [=](const STrackLayout& track) { return (pTrackLayout == &track); }); - auto endFindIter = std::find_if(tracks.begin(), tracks.end(), [=](const STrackLayout& track) { return (m_timeline->m_pLastSelectedTrack == &track); }); - - if (startFindIter != tracks.end() && endFindIter != tracks.end()) - { - if (startFindIter > endFindIter) - { - std::swap(startFindIter, endFindIter); - } - - for (auto iter = startFindIter; iter <= endFindIter; ++iter) - { - iter->pTimelineTrack->selected = true; - } - } - } - else - { - pTrackLayout->pTimelineTrack->selected = true; - } - - if (!bShiftPressed && pTrackLayout->pTimelineTrack->selected) - { - m_timeline->m_pLastSelectedTrack = pTrackLayout; - } - - m_timeline->SignalTrackSelectionChanged(); - } - } - } - - void mouseDoubleClickEvent(QMouseEvent* ev) override - { - if (ev->modifiers() == 0) - { - STrackLayout* pTrackLayout = m_timeline->GetTrackLayoutFromPos(ev->pos()); - ToggleTrackExpansion(pTrackLayout); - } - } - -private: - void ToggleTrackExpansion(STrackLayout* pTrackLayout) - { - if (pTrackLayout && pTrackLayout->pTimelineTrack) - { - pTrackLayout->pTimelineTrack->expanded = !pTrackLayout->pTimelineTrack->expanded; - m_timeline->UpdateLayout(); - m_timeline->update(); - } - } -}; - -// --------------------------------------------------------------------------- - -CTimeline::CTimeline(QWidget* parent) - : QWidget(parent) - , m_cycled(true) - , m_sizeToContent(false) - , m_snapTime(false) - , m_snapKeys(false) - , m_treeVisible(false) - , m_selIndicators(false) - , m_verticalScrollbarVisible(false) - , m_drawMarkers(false) - , m_layout(new STimelineLayout) - , m_keyWidth(DEFAULT_KEY_WIDTH) - , m_keyRadius(DEFAULT_KEY_RADIUS) - , m_cornerWidget(nullptr) - , m_scrollBar(nullptr) - , m_cornerWidgetWidth(0) - , m_pContent(nullptr) - , m_timeUnitScale(1.0f) - , m_timeStepNum(1) - , m_timeStepIndex(0) - , m_frameRate(SAnimTime::eFrameRate_30fps) - , m_time(0.0f) - , m_pFilterLineEdit(nullptr) - , m_pLastSelectedTrack(nullptr) -{ - setMinimumWidth(THUMB_WIDTH * 3); - setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Maximum); - setFocusPolicy(Qt::WheelFocus); - setMouseTracking(true); - - m_viewState.visibleDistance = 1.0f; -} - -CTimeline::~CTimeline() -{ -} - -void CTimeline::paintEvent([[maybe_unused]] QPaintEvent* ev) -{ - const QPoint mousePos = mapFromGlobal(QCursor::pos()); - - QPainter painter(this); - painter.save(); - painter.translate(0.5f, 0.5f); - - if (m_viewState.visibleDistance != 0) - { - SAnimTime totalDuration = m_layout->maxEndTime - m_layout->minStartTime; - m_viewState.scrollPixels = QPoint(m_viewState.ScrollOffset(m_viewState.viewOrigin), 0); - m_viewState.maxScrollX = int(m_viewState.widthPixels * totalDuration.ToFloat() / m_viewState.visibleDistance) - m_viewState.widthPixels; - } - else - { - m_viewState.scrollPixels = QPoint(0, 0); - m_viewState.maxScrollX = 0; - } - - const int scroll = m_scrollBar ? m_scrollBar->value() : 0; - const QPoint localToLayoutTranslate = m_viewState.LayoutToLocal(QPoint(0, -scroll)); - - int rulerPrecision = 0; - - painter.translate(localToLayoutTranslate); - painter.setRenderHint(QPainter::Antialiasing); - - DrawTracks(painter, PASS_BACKGROUND, PASS_BACKGROUND, *m_layout, m_viewState, - palette(), mousePos, hasFocus(), width(), m_keyRadius, m_timeUnitScale, m_drawMarkers); - - DrawTracks(painter, PASS_SELECTION, PASS_MAIN, *m_layout, m_viewState, - palette(), mousePos, hasFocus(), width(), m_keyRadius, m_timeUnitScale, m_drawMarkers); - - painter.translate(-localToLayoutTranslate); - - DrawingPrimitives::SRulerOptions rulerOptions; - rulerOptions.m_rect = QRect(m_viewState.treeWidth, -1, size().width() - m_viewState.treeWidth, RULER_HEIGHT + 2); - rulerOptions.m_visibleRange = Range(m_viewState.LocalToTime(m_viewState.treeWidth) * m_timeUnitScale, m_viewState.LocalToTime(size().width()) * m_timeUnitScale); - rulerOptions.m_rulerRange = Range(m_layout->minStartTime.ToFloat() * m_timeUnitScale, m_layout->maxEndTime.ToFloat() * m_timeUnitScale); - rulerOptions.m_markHeight = RULER_MARK_HEIGHT; - rulerOptions.m_shadowSize = RULER_SHADOW_HEIGHT; - DrawingPrimitives::DrawRuler(painter, palette(), rulerOptions, &rulerPrecision); - - if (m_pContent && isEnabled()) - { - DrawingPrimitives::STimeSliderOptions timeSliderOptions; - timeSliderOptions.m_rect = rect(); - timeSliderOptions.m_precision = rulerPrecision; - timeSliderOptions.m_position = m_viewState.TimeToLocal(m_time.ToFloat()); - timeSliderOptions.m_time = m_time.ToFloat() * m_timeUnitScale; - timeSliderOptions.m_bHasFocus = hasFocus(); - DrawingPrimitives::DrawTimeSlider(painter, palette(), timeSliderOptions); - - DrawSelectionLines(painter, palette(), m_viewState, *m_pContent, rulerPrecision, width(), height(), m_time.ToFloat(), m_timeUnitScale, hasFocus()); - } - - painter.translate(localToLayoutTranslate); - - if (m_mouseHandler) - { - m_mouseHandler->paintOver(painter); - } - - painter.translate(-localToLayoutTranslate); - - if (m_viewState.scrollPixels.x() < 0) - { - QRect rect(m_viewState.treeWidth, 0, SCROLL_SHADOW_WIDTH, height()); - QLinearGradient grad(rect.left(), rect.top(), rect.right(), rect.top()); - grad.setColorAt(0.0f, QColor(0, 0, 0, 96)); - grad.setColorAt(1.0f, QColor(0, 0, 0, 0)); - painter.fillRect(rect, QBrush(grad)); - } - - SAnimTime totalDuration = m_layout->maxEndTime - m_layout->minStartTime; - - if (m_viewState.scrollPixels.x() > -m_viewState.maxScrollX) - { - QRect rect(width() - SCROLL_SHADOW_WIDTH, 0, SCROLL_SHADOW_WIDTH, height()); - QLinearGradient grad(rect.left(), rect.top(), rect.right(), rect.top()); - grad.setColorAt(0.0f, QColor(0, 0, 0, 0)); - grad.setColorAt(1.0f, QColor(0, 0, 0, 96)); - painter.fillRect(rect, QBrush(grad)); - } - - { - QColor color = palette().color(QPalette::Dark); - color.setAlpha(128); - painter.setPen(QPen(color)); - painter.drawLine(QPoint(0, 0), QPoint(0, height())); - painter.drawLine(QPoint(width() - 1, 0), QPoint(width() - 1, height())); - painter.drawLine(QPoint(1, 0), QPoint(width() - 1, 0)); - painter.drawLine(QPoint(0, height()), QPoint(width() - 1, height())); - } - - painter.restore(); - - if (m_treeVisible) - { - if (m_pContent) - { - QRect treeRect(0, 0, m_viewState.treeWidth - SPLITTER_WIDTH + 1, height()); - DrawTree(painter, treeRect, palette(), this, *m_pContent, m_layout->tracks, m_viewState, scroll); - } - - QRect splitterRect(m_viewState.treeWidth - SPLITTER_WIDTH, 0, SPLITTER_WIDTH, height()); - DrawSplitter(painter, splitterRect, palette(), this); - } - - if (!isEnabled()) - { - QColor disabledOverlayColor = palette().color(QPalette::Disabled, QPalette::Button); - disabledOverlayColor.setAlpha(128); - painter.fillRect(0, 0, width(), height(), QBrush(disabledOverlayColor)); - } -} - -void CTimeline::keyPressEvent(QKeyEvent* ev) -{ - const QPoint mousePos = mapFromGlobal(QCursor::pos()); - QMouseEvent mouseEvent(QEvent::MouseMove, mousePos, Qt::NoButton, Qt::NoButton, ev->modifiers()); - mouseMoveEvent(&mouseEvent); - int rawKey = ev->key() | ev->modifiers(); - QKeySequence key(rawKey); - - if (key == QKeySequence(Qt::Key_Z | Qt::CTRL)) - { - SignalUndo(); - } - else if (key == QKeySequence(Qt::Key_Y | Qt::CTRL) || (key == QKeySequence(Qt::Key_Z | Qt::CTRL | Qt::SHIFT))) - { - SignalRedo(); - } - else - { - HandleKeyEvent(rawKey); - } -} - -void CTimeline::keyReleaseEvent(QKeyEvent* ev) -{ - const QPoint mousePos = mapFromGlobal(QCursor::pos()); - QMouseEvent mouseEvent(QEvent::MouseMove, mousePos, Qt::NoButton, Qt::NoButton, ev->modifiers()); - mouseMoveEvent(&mouseEvent); -} - -bool CTimeline::HandleKeyEvent(int k) -{ - QKeySequence key(k); - - if (key == QKeySequence(Qt::Key_Delete)) - { - OnMenuDelete(); - return true; - } - - if (key == QKeySequence(Qt::Key_D)) - { - OnMenuDuplicate(); - return true; - } - - if (key == QKeySequence(Qt::Key_Home)) - { - m_time = SAnimTime(0); - update(); - SignalScrub(false); - return true; - } - if (key == QKeySequence(Qt::Key_End)) - { - SAnimTime endTime = SAnimTime(0); - for (size_t i = 0; i < m_pContent->track.tracks.size(); ++i) - { - endTime = std::max(endTime, m_pContent->track.tracks[i]->endTime); - } - m_time = endTime; - update(); - SignalScrub(false); - return true; - } - if (key == QKeySequence(Qt::Key_X) || key == QKeySequence(Qt::Key_PageUp)) - { - OnMenuPreviousKey(); - return true; - } - if (key == QKeySequence(Qt::Key_C) || key == QKeySequence(Qt::Key_PageDown)) - { - OnMenuNextKey(); - return true; - } - - if (k == Qt::Key_Comma || k == Qt::Key_Left) - { - OnMenuPreviousFrame(); - return true; - } - - if (k == Qt::Key_Period || k == Qt::Key_Right) - { - OnMenuNextFrame(); - return true; - } - - if (key == QKeySequence(Qt::Key_Space)) - { - OnMenuPlay(); - return true; - } - - // shortcut is Ctrl+# - int maskedKey = ((~Qt::KeyboardModifierMask) & k); - if (((k & Qt::CTRL) != 0) && (maskedKey >= Qt::Key_0 && maskedKey <= Qt::Key_9)) - { - int number = maskedKey - int(Qt::Key_0); - SignalNumberHotkey(number); - return true; - } - - return false; -} - -bool CTimeline::ProcessesKey(const QKeySequence& key) -{ - static QSet customShortcuts = { - QKeySequence(Qt::Key_Delete), - QKeySequence(Qt::Key_D), - QKeySequence(Qt::Key_Home), - QKeySequence(Qt::Key_End), - QKeySequence(Qt::Key_PageUp), - QKeySequence(Qt::Key_X), - QKeySequence(Qt::Key_PageDown), - QKeySequence(Qt::Key_C), - QKeySequence(Qt::Key_Comma), - QKeySequence(Qt::Key_Left), - QKeySequence(Qt::Key_Period), - QKeySequence(Qt::Key_Right), - QKeySequence(Qt::Key_Space), - QKeySequence(Qt::CTRL | Qt::Key_0), - QKeySequence(Qt::CTRL | Qt::Key_1), - QKeySequence(Qt::CTRL | Qt::Key_2), - QKeySequence(Qt::CTRL | Qt::Key_3), - QKeySequence(Qt::CTRL | Qt::Key_4), - QKeySequence(Qt::CTRL | Qt::Key_5), - QKeySequence(Qt::CTRL | Qt::Key_6), - QKeySequence(Qt::CTRL | Qt::Key_7), - QKeySequence(Qt::CTRL | Qt::Key_8), - QKeySequence(Qt::CTRL | Qt::Key_9) - }; - - return customShortcuts.contains(key); -} - -void CTimeline::mousePressEvent(QMouseEvent* ev) -{ - setFocus(); - - const bool bInTreeArea = m_treeVisible && (ev->x() <= m_viewState.treeWidth); - - if (ev->button() == Qt::LeftButton) - { - QPoint posInLayout = m_viewState.LocalToLayout(ev->pos()); - - if (bInTreeArea) - { - const bool bOverSplitter = ev->x() >= (m_viewState.treeWidth - SPLITTER_WIDTH); - - if (bOverSplitter) - { - m_mouseHandler.reset(new SSplitterHandler(this)); - m_mouseHandler->mousePressEvent(ev); - update(); - } - else - { - m_mouseHandler.reset(new STreeMouseHandler(this)); - m_mouseHandler->mousePressEvent(ev); - update(); - } - } - else if (ev->y() < RULER_HEIGHT) - { - m_mouseHandler.reset(new SScrubHandler(this)); - m_mouseHandler->mousePressEvent(ev); - update(); - } - else - { - QPoint posInLayoutSpace = m_viewState.LocalToLayout(ev->pos()); - - SElementLayoutPtrs hitElements; - bool bHit = HitTestElements(m_layout->tracks, QRect(posInLayoutSpace - QPoint(2, 2), posInLayoutSpace + QPoint(2, 2)), hitElements); - - if (ev->modifiers() & Qt::SHIFT || ev->modifiers() & Qt::CTRL) - { - if (bHit) - { - hitElements.back()->SetSelected(hitElements.back()->IsSelected()); - mouseMoveEvent(ev); - update(); - } - else - { - m_mouseHandler.reset(new SSelectionHandler(this, true)); - m_mouseHandler->mousePressEvent(ev); - } - } - else - { - if (bHit) - { - bool useExistingSelection = std::any_of(hitElements.begin(), hitElements.end(), [](const SElementLayout* element) { return element->IsSelected(); }); - - if (!useExistingSelection) - { - const TSelectedElements selectedElements = GetSelectedElements(m_pContent->track); - - ClearElementSelection(m_pContent->track); - hitElements.back()->SetSelected(true); - - if (selectedElements != GetSelectedElements(m_pContent->track)) - { - SignalSelectionChanged(false); - } - } - - bool cycleSelection = useExistingSelection; - m_mouseHandler.reset(new SMoveHandler(this, cycleSelection)); - m_mouseHandler->mousePressEvent(ev); - update(); - } - else - { - m_mouseHandler.reset(new SSelectionHandler(this, false)); - m_mouseHandler->mousePressEvent(ev); - update(); - } - } - } - } - else if (ev->button() == Qt::MiddleButton) - { - if (!bInTreeArea) - { - m_mouseHandler.reset(new SPanHandler(this)); - m_mouseHandler->mousePressEvent(ev); - update(); - } - } - else if (ev->button() == Qt::RightButton) - { - if (bInTreeArea) - { - std::vector selectedTracks; - GetSelectedTracks(m_pContent->track, selectedTracks); - - STrackLayout* pLayout = GetTrackLayoutFromPos(ev->pos()); - if (pLayout) - { - if (!stl::find(selectedTracks, pLayout->pTimelineTrack)) - { - ClearTrackSelection(m_pContent->track); - pLayout->pTimelineTrack->selected = true; - } - - SignalTreeContextMenu(mapToGlobal(ev->pos())); - } - } - else - { - QMenu menu; - bool hasSelection = false; - ForEachElement(m_pContent->track, [&]([[maybe_unused]] STimelineTrack& t, STimelineElement& e) - { - if (e.selected) - { - hasSelection = true; - } - }); - - menu.addAction("Selection to Cursor", this, SLOT(OnMenuSelectionToCursor()))->setEnabled(hasSelection); - QAction* duplicateAction = menu.addAction("Duplicate", this, SLOT(OnMenuDuplicate()), QKeySequence("D")); - duplicateAction->setEnabled(hasSelection); - menu.addSeparator(); - menu.addAction("Delete Event(s)", this, SLOT(OnMenuDelete()), QKeySequence("Delete"))->setEnabled(hasSelection); - menu.addSeparator(); - menu.addAction("Play / Pause", this, SLOT(OnMenuPlay()), QKeySequence("Space")); - menu.addAction("Previous Frame", this, SLOT(OnMenuPreviousFrame()), QKeySequence(",")); - menu.addAction("Next Frame", this, SLOT(OnMenuNextFrame()), QKeySequence(".")); - menu.addAction("Jump to Previous Event", this, SLOT(OnMenuPreviousKey()), QKeySequence("X")); - menu.addAction("Jump to Next Event", this, SLOT(OnMenuNextKey()), QKeySequence("C")); - menu.exec(QCursor::pos(), duplicateAction); - } - } -} - -void CTimeline::AddKeyToTrack(STimelineTrack& track, SAnimTime time) -{ - if (m_snapKeys) - { - time = time.SnapToNearest(m_frameRate); - } - - track.modified = true; - track.elements.push_back(track.defaultElement); - track.elements.back().added = true; - SAnimTime length = track.defaultElement.end - track.defaultElement.start; - track.elements.back().start = time; - track.elements.back().end = length; - track.elements.back().selected = true; -} - -void CTimeline::mouseDoubleClickEvent(QMouseEvent* ev) -{ - if (ev->button() == Qt::LeftButton) - { - QPoint posInLayout = m_viewState.LocalToLayout(ev->pos()); - - const bool bInTreeArea = m_treeVisible && (ev->x() <= m_viewState.treeWidth); - - if (bInTreeArea) - { - const bool bOverSplitter = ev->x() >= (m_viewState.treeWidth - SPLITTER_WIDTH); - - if (!bOverSplitter) - { - m_mouseHandler.reset(new STreeMouseHandler(this)); - m_mouseHandler->mouseDoubleClickEvent(ev); - update(); - } - } - - QPoint layoutPoint = m_viewState.LocalToLayout(ev->pos()); - STrackLayout* track = HitTestTrack(m_layout->tracks, layoutPoint); - - if (track) - { - SElementLayoutPtrs hitElements; - const bool bHit = HitTestElements(m_layout->tracks, QRect(layoutPoint - QPoint(2, 2), layoutPoint + QPoint(2, 2)), hitElements); - - if (!bHit) - { - float time = m_viewState.LayoutToTime(layoutPoint.x()); - STimelineTrack& timelineTrack = *track->pTimelineTrack; - - if ((timelineTrack.caps & STimelineTrack::CAP_COMPOUND_TRACK) == 0) - { - AddKeyToTrack(timelineTrack, SAnimTime(time)); - } - else - { - const size_t numSubTracks = timelineTrack.tracks.size(); - for (size_t i = 0; i < numSubTracks; ++i) - { - STimelineTrack& subTrack = *timelineTrack.tracks[i]; - AddKeyToTrack(subTrack, SAnimTime(time)); - } - } - - ContentChanged(false); - m_mouseHandler.reset(); - mouseMoveEvent(ev); - } - } - } -} - -void CTimeline::UpdateCursor(QMouseEvent* ev) -{ - const int scroll = m_scrollBar ? m_scrollBar->value() : 0; - const QPoint pos(ev->pos().x(), ev->pos().y() + scroll); - - QPoint posInLayoutSpace = m_viewState.LocalToLayout(pos); - - SElementLayoutPtrs hitElements; - HitTestElements(m_layout->tracks, QRect(posInLayoutSpace - QPoint(2, 2), posInLayoutSpace + QPoint(2, 2)), hitElements); - const bool bOverSelected = !hitElements.empty() && hitElements.back()->IsSelected(); - const bool bInTreeArea = m_treeVisible && (ev->x() <= m_viewState.treeWidth); - - bool shift = ev->modifiers().testFlag(Qt::ShiftModifier); - bool control = ev->modifiers().testFlag(Qt::ControlModifier); - - if (m_mouseHandler) - { - m_mouseHandler->mouseMoveEvent(ev); - update(); - } - else if (m_treeVisible && (ev->x() <= m_viewState.treeWidth) && (ev->x() >= (m_viewState.treeWidth - SPLITTER_WIDTH))) - { - setCursor(QCursor(Qt::SplitHCursor)); - } - else if (!bInTreeArea && bOverSelected && !(shift || control)) - { - setCursor(QCursor(Qt::SizeHorCursor)); - } - else - { - setCursor(QCursor()); - } -} - -void CTimeline::mouseMoveEvent(QMouseEvent* ev) -{ - UpdateCursor(ev); -} - -void CTimeline::mouseReleaseEvent(QMouseEvent* ev) -{ - if (ev->button() == Qt::LeftButton || ev->button() == Qt::MiddleButton) - { - if (m_mouseHandler.get()) - { - m_mouseHandler->mouseReleaseEvent(ev); - m_mouseHandler.reset(); - update(); - } - } - UpdateCursor(ev); -} - -void CTimeline::focusOutEvent(QFocusEvent* ev) -{ - if (m_mouseHandler.get()) - { - m_mouseHandler->focusOutEvent(ev); - m_mouseHandler.reset(); - } - - update(); -} - -void CTimeline::wheelEvent(QWheelEvent* ev) -{ - int pixelDelta = ev->pixelDelta().manhattanLength(); - - if (pixelDelta == 0) - { - pixelDelta = ev->angleDelta().y(); - } - - const float fractionOfView = std::min(m_viewState.widthPixels != 0 ? float(pixelDelta) / m_viewState.widthPixels : 0.0f, 0.5f); - - SetVisibleDistance(m_viewState.visibleDistance - m_viewState.visibleDistance * fractionOfView); -} - -QSize CTimeline::sizeHint() const -{ - return QSize(m_layout->size); -} - -void CTimeline::resizeEvent([[maybe_unused]] QResizeEvent* ev) -{ - UpdateLayout(); -} - -SAnimTime CTimeline::ClampAndSnapTime(SAnimTime time, bool snapToFrames) const -{ - SAnimTime minTime = m_layout->minStartTime; - SAnimTime maxTime = m_layout->maxEndTime; - SAnimTime unclampedTime = time; - SAnimTime deltaTime = maxTime - minTime; - - if (m_cycled) - { - while (unclampedTime < minTime) - { - unclampedTime += deltaTime; - } - - unclampedTime = ((unclampedTime - minTime) % deltaTime) + minTime; - } - - SAnimTime clampedTime = clamp_tpl(unclampedTime, minTime, maxTime); - - if (!snapToFrames) - { - return clampedTime; - } - else - { - int timeStepIndex = static_cast(floor(clampedTime.ToFloat() * static_cast(m_timeStepNum) + 0.05f)); - float normalizedTime = static_cast(timeStepIndex) / static_cast(m_timeStepNum); - return SAnimTime(normalizedTime); - } -} - -void CTimeline::ClampAndSetTime(SAnimTime time, bool scrubThrough) -{ - SAnimTime newTime = ClampAndSnapTime(time, m_snapTime); - - if (newTime != m_time) - { - m_time = newTime; - UpdateLayout(); - update(); - SignalScrub(scrubThrough); - } -} - -void CTimeline::SetTimeUnitScale(float scale, float step) -{ - m_timeUnitScale = scale; - m_timeStepNum = static_cast(scale / step); - update(); -} - -void CTimeline::SetTime(SAnimTime time) -{ - m_time = time; - update(); -} - -void CTimeline::SetCycled(bool cycled) -{ - m_cycled = cycled; -} - -void CTimeline::SetContent(STimelineContent* pContent) -{ - m_pContent = pContent; - - UpdateLayout(); - update(); -} - -void CTimeline::UpdateLayout() -{ - m_layout->tracks.clear(); - - m_viewState.widthPixels = width(); - - if (m_treeVisible) - { - m_viewState.widthPixels -= m_viewState.treeWidth; - m_viewState.widthPixels = std::max(m_viewState.widthPixels, 0); - } - - if (m_verticalScrollbarVisible) - { - if (!m_scrollBar) - { - m_scrollBar = new QScrollBar(Qt::Vertical, this); - connect(m_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(OnVerticalScroll(int))); - } - - const uint scrollbarWidth = style()->pixelMetric(QStyle::PM_ScrollBarExtent, 0, this); - m_scrollBar->setGeometry(width() - scrollbarWidth, 0, scrollbarWidth, height()); - - m_viewState.widthPixels -= scrollbarWidth; - m_viewState.widthPixels = std::max(m_viewState.widthPixels, 0); - } - else if (!m_verticalScrollbarVisible && m_scrollBar) - { - SAFE_DELETE(m_scrollBar); - } - - ClampViewOrigin(&m_viewState, *m_layout); - - if (m_pContent) - { - CalculateLayout(m_layout.get(), *m_pContent, m_viewState, m_pFilterLineEdit, m_time.ToFloat(), m_keyWidth, m_treeVisible); - ApplyPushOut(m_layout.get(), m_keyWidth); - } - - if (m_scrollBar) - { - const int timelineHeight = rect().height(); - const int scrollBarRange = m_layout->size.height() - timelineHeight; - - if (scrollBarRange > 0) - { - m_scrollBar->setRange(0, scrollBarRange); - m_scrollBar->show(); - } - else - { - m_scrollBar->setValue(0); - m_scrollBar->hide(); - } - } - - if (m_sizeToContent) - { - setMaximumHeight(m_layout->size.height()); - setMinimumHeight(m_layout->size.height()); - } - else - { - setMinimumHeight(RULER_HEIGHT + 1); - setMaximumHeight(QWIDGETSIZE_MAX); - } - - if (m_treeVisible) - { - if (!m_pFilterLineEdit) - { - m_pFilterLineEdit = new QLineEdit(this); - connect(m_pFilterLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(OnFilterChanged())); - } - - const uint cornerWidgetWidth = m_cornerWidget ? m_cornerWidgetWidth : 0; - m_pFilterLineEdit->resize(m_viewState.treeWidth - SPLITTER_WIDTH - cornerWidgetWidth, RULER_HEIGHT + VERTICAL_PADDING); - - if (m_cornerWidget) - { - m_cornerWidget->setGeometry(m_viewState.treeWidth - SPLITTER_WIDTH - cornerWidgetWidth, 0, cornerWidgetWidth, RULER_HEIGHT + VERTICAL_PADDING); - } - } - else if (!m_treeVisible && m_pFilterLineEdit) - { - SAFE_DELETE(m_pFilterLineEdit); - } -} - -void CTimeline::SetSizeToContent(bool sizeToContent) -{ - m_sizeToContent = sizeToContent; - - UpdateLayout(); -} - -void CTimeline::ContentChanged(bool continuous) -{ - SignalContentChanged(continuous); - - DeletedMarkedElements(m_pContent->track); - - if (!continuous) - { - ForEachElement(m_pContent->track, [](STimelineTrack& track, STimelineElement& element) - { - track.modified = false; - element.added = false; - }); - } - - UpdateLayout(); - update(); -} - -void CTimeline::OnMenuSelectionToCursor() -{ - TSelectedElements elements = GetSelectedElements(m_pContent->track); - - for (size_t i = 0; i < elements.size(); ++i) - { - STimelineTrack& track = *elements[i].first; - STimelineElement& element = *elements[i].second; - SAnimTime length = element.end - element.start; - element.start = m_time; - element.end = element.start + length; - if (element.type == element.CLIP) - { - if (length > track.endTime) - { - element.start = track.endTime - length; - } - } - if (element.start < track.startTime) - { - element.start = track.startTime; - } - } - - ContentChanged(false); -} - -void CTimeline::OnMenuDuplicate() -{ - TSelectedElements selectedElements = GetSelectedElements(m_pContent->track); - if (selectedElements.empty()) - { - return; - } - - typedef std::vector > TTrackElements; - - TTrackElements elements; - - ForEachElement(m_pContent->track, [&](STimelineTrack& track, STimelineElement& element) - { - if (element.selected) - { - elements.push_back(std::make_pair(&track, element)); - element.selected = false; - } - }); - - for (size_t i = 0; i < elements.size(); ++i) - { - STimelineTrack* track = elements[i].first; - const STimelineElement& element = elements[i].second; - track->elements.push_back(element); - STimelineElement& e = track->elements.back(); - e.userId = 0; - e.added = true; - e.sideLoadChanged = true; - e.selected = true; - } - - ContentChanged(false); - SignalSelectionChanged(false); -} - -void CTimeline::OnMenuCopy() -{ -} - -void CTimeline::OnMenuPaste() -{ -} - -void CTimeline::OnMenuDelete() -{ - ForEachElement(m_pContent->track, [](STimelineTrack& track, STimelineElement& element) - { - if (element.selected) - { - track.modified = true; - element.deleted = true; - } - }); - - ContentChanged(false); -} - -void CTimeline::OnMenuPlay() -{ - SignalPlay(); -} - -typedef std::vector > TimeToId; -static void GetAllTimes(TimeToId* times, const STimelineTrack& track) -{ - for (size_t i = 0; i < track.tracks.size(); ++i) - { - GetAllTimes(times, *track.tracks[i]); - } -} - -static void GetAllTimes(TimeToId* times, STimelineContent& content) -{ - ForEachTrack(content.track, [&](STimelineTrack& track) - { - times->push_back(std::make_pair(track.startTime, STimelineContentElementRef())); - times->push_back(std::make_pair(track.endTime, STimelineContentElementRef())); - }); - - ForEachElementWithIndex(content.track, [=](STimelineTrack& track, STimelineElement& element, size_t i) - { - STimelineContentElementRef ref(&track, i); - times->push_back(std::make_pair(element.start, ref)); - if (element.type == STimelineElement::CLIP) - { - times->push_back(std::make_pair(element.end, ref)); - } - }); - - std::sort(times->begin(), times->end()); -} - -static STimelineContentElementRef SelectedIdAtTime(const std::vector& selection, [[maybe_unused]] const STimelineContent& content, SAnimTime time) -{ - for (size_t i = 0; i < selection.size(); ++i) - { - const STimelineContentElementRef& id = selection[i]; - const STimelineElement& element = id.GetElement(); - if (element.start == time || element.end == time) - { - return id; - } - } - return STimelineContentElementRef(); -} - -void CTimeline::OnMenuPreviousKey() -{ - if (!m_pContent) - { - return; - } - TimeToId times; - GetAllTimes(×, *m_pContent); - - std::vector selection; - ForEachElementWithIndex(m_pContent->track, [&](STimelineTrack& t, STimelineElement& e, size_t i) - { - if (e.selected) - { - selection.push_back(STimelineContentElementRef(&t, i)); - } - }); - - STimelineContentElementRef selectedId = SelectedIdAtTime(selection, *m_pContent, m_time); - - TimeToId::iterator it = std::lower_bound(times.begin(), times.end(), std::make_pair(m_time, selectedId)); - if (it != times.end()) - { - if (it != times.begin()) - { - --it; - } - - ClearElementSelection(m_pContent->track); - if (it->second.IsValid()) - { - it->second.GetElement().selected = true; - } - - m_time = it->first; - - SignalSelectionChanged(false); - SignalScrub(false); - update(); - } -} - -void CTimeline::OnMenuNextKey() -{ - if (!m_pContent) - { - return; - } - TimeToId times; - GetAllTimes(×, *m_pContent); - - std::vector selection; - ForEachElementWithIndex(m_pContent->track, [&](STimelineTrack& t, STimelineElement& e, size_t i) - { - if (e.selected) - { - selection.push_back(STimelineContentElementRef(&t, i)); - } - }); - - STimelineContentElementRef selectedId = SelectedIdAtTime(selection, *m_pContent, m_time); - - TimeToId::iterator it = std::upper_bound(times.begin(), times.end(), std::make_pair(m_time, selectedId)); - if (it != times.end()) - { - ClearElementSelection(m_pContent->track); - if (it->second.IsValid()) - { - it->second.GetElement().selected = true; - } - - m_time = it->first; - - SignalSelectionChanged(false); - SignalScrub(false); - update(); - } -} - -void CTimeline::OnMenuPreviousFrame() -{ - m_timeStepIndex = static_cast(floor(m_time.ToFloat() * static_cast(m_timeStepNum) + 0.05f)) - 1; - if (m_timeStepIndex < 0) - { - m_timeStepIndex = m_timeStepNum; - } - float normalizedTime = static_cast(m_timeStepIndex) / static_cast(m_timeStepNum); - m_time = SAnimTime(normalizedTime); - SignalScrub(false); - update(); -} - -void CTimeline::OnMenuNextFrame() -{ - m_timeStepIndex = static_cast(floor(m_time.ToFloat() * static_cast(m_timeStepNum) + 0.05f)) + 1; - if (m_timeStepIndex > m_timeStepNum) - { - m_timeStepIndex = 0; - } - float normalizedTime = static_cast(m_timeStepIndex) / static_cast(m_timeStepNum); - m_time = SAnimTime(normalizedTime); - SignalScrub(false); - update(); -} - -void CTimeline::OnFilterChanged() -{ - UpdateLayout(); - update(); -} - -void CTimeline::OnVerticalScroll([[maybe_unused]] int value) -{ - update(); -} - -bool CTimeline::event(QEvent* e) -{ - switch (e->type()) - { - case QEvent::ShortcutOverride: - { - // When a shortcut is matched, Qt's event processing sends out a shortcut override event - // to allow other systems to override it. If it's not overridden, then the key events - // get processed as a shortcut, even if the widget that's the target has a keyPress event - // handler. So, we need to communicate that we've processed the shortcut override - // which will tell Qt not to process it as a shortcut and instead pass along the - // keyPressEvent. - - QKeyEvent* keyEvent = static_cast(e); - QKeySequence keySequence = keyEvent->key() | keyEvent->modifiers(); - - // special case undo/redo, because they're only handled in CTimeline::keyPressEvent() - // and not in HandleKeyEvent: - static QSet customShortcuts = { - QKeySequence(Qt::CTRL | Qt::Key_Z), - QKeySequence(Qt::CTRL | Qt::Key_Y), - QKeySequence(Qt::Key_Z | Qt::CTRL | Qt::SHIFT) - }; - - if (ProcessesKey(keySequence) || customShortcuts.contains(keySequence)) - { - e->accept(); - return true; - } - } - break; - } - - return QWidget::event(e); -} - -void CTimeline::SetTreeVisible(bool visible) -{ - m_treeVisible = visible; - m_viewState.treeWidth = visible ? DEFAULT_TREE_WIDTH : 0; - - UpdateLayout(); - update(); -} - -STrackLayout* CTimeline::GetTrackLayoutFromPos(const QPoint& pos) const -{ - if (pos.y() < RULER_HEIGHT) - { - return nullptr; - } - - STrackLayouts& tracks = m_layout->tracks; - - auto findIter = std::upper_bound(tracks.begin(), tracks.end(), pos.y(), [&](int y, const STrackLayout& track) - { - return y < track.rect.bottom(); - }); - - if (findIter != tracks.end() && pos.y() <= findIter->rect.bottom()) - { - return &(*findIter); - } - - return nullptr; -} - -void CTimeline::SetCustomTreeCornerWidget(QWidget* pWidget, uint width) -{ - SAFE_DELETE(m_cornerWidget); - - m_cornerWidget = pWidget; - m_cornerWidgetWidth = width; - - if (m_cornerWidget) - { - m_cornerWidget->setCursor(QCursor()); - } - - UpdateLayout(); - update(); -} - -void CTimeline::SetVerticalScrollbarVisible(bool bVisible) -{ - m_verticalScrollbarVisible = bVisible; - UpdateLayout(); - update(); -} - -void CTimeline::SetDrawTrackTimeMarkers(bool bDrawMarkers) -{ - m_drawMarkers = bDrawMarkers; - update(); -} - -void CTimeline::SetVisibleDistance(float distance) -{ - const float totalDuration = (m_layout->maxEndTime - m_layout->minStartTime).ToFloat(); - const float padding = (float(TIMELINE_PADDING) - 0.5f) / m_viewState.widthPixels * totalDuration; - m_viewState.visibleDistance = clamp_tpl(distance, 0.01f, totalDuration + 2.0f * padding); - - UpdateLayout(); - update(); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/Timeline.h b/Code/Sandbox/Plugins/EditorCommon/Timeline.h deleted file mode 100644 index 7449841695..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Timeline.h +++ /dev/null @@ -1,216 +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 -#ifndef CRYINCLUDE_EDITORCOMMON_TIMELINE_H -#define CRYINCLUDE_EDITORCOMMON_TIMELINE_H - -#include -#include - -#include "TimelineContent.h" - -class QPainter; -class QPaintEvent; -class QLineEdit; -class QScrollBar; - -struct STimelineLayout; - -struct STimelineViewState -{ - float viewOrigin; - float visibleDistance; - float clampedViewOrigin; - int widthPixels; - QPoint scrollPixels; - int maxScrollX; - int treeWidth; - int treeLastOpenedWidth; - - STimelineViewState() - : viewOrigin(0.0f) - , clampedViewOrigin(0.0f) - , visibleDistance(1.0f) - , scrollPixels(0, 0) - , maxScrollX(0) - , treeWidth(0) - , widthPixels(1) - { - } - - QPoint LocalToLayout(const QPoint& p) const; - QPoint LayoutToLocal(const QPoint& p) const; - - int ScrollOffset(float origin) const; - int TimeToLayout(float time) const; - float LocalToTime(int x) const; - int TimeToLocal(float time) const; - float LayoutToTime(int x) const; -}; - -struct STrackLayout; - -class EDITOR_COMMON_API CTimeline - : public QWidget -{ - Q_OBJECT -public: - CTimeline(QWidget* parent); - ~CTimeline(); - - void SetContent(STimelineContent* pContent); - STimelineContent* Content() const { return m_pContent; } - - void ContentUpdated() { UpdateLayout(); update(); } - - bool IsDragged() const { return m_mouseHandler.get() != 0; } - - // make it possible to have actual time in normalized units, but different display units - void SetTimeUnitScale(float timeUnitScale, float step); - void SetTime(SAnimTime time); - void SetCycled(bool cycled); - void SetSizeToContent(bool sizeToContent); - void SetFrameRate(SAnimTime::EFrameRate frameRate) { m_frameRate = frameRate; } - void SetTimeSnapping(bool snapTime) { m_snapTime = snapTime; } - void SetKeySnapping(bool snapKeys) { m_snapKeys = snapKeys; } - void SetKeyWidth(uint width) { m_keyWidth = width; UpdateLayout(); update(); } - void SetKeyRadius(float radius) { m_keyRadius = radius; UpdateLayout(); update(); } - void SetTreeVisible(bool visible); - void SetDrawSelectionIndicators(bool visible) { m_selIndicators = visible; update(); } - void SetCustomTreeCornerWidget(QWidget* pWidget, uint width); - void SetVerticalScrollbarVisible(bool bVisible); - void SetDrawTrackTimeMarkers(bool bDrawMarkers); - void SetVisibleDistance(float distance); - - SAnimTime Time() const { return m_time; } - - bool HandleKeyEvent(int key); - bool ProcessesKey(const QKeySequence& key); - - void paintEvent(QPaintEvent* ev) override; - void mousePressEvent(QMouseEvent* ev) override; - void mouseMoveEvent(QMouseEvent* ev) override; - void mouseReleaseEvent(QMouseEvent* ev) override; - void focusOutEvent(QFocusEvent* ev) override; - void mouseDoubleClickEvent(QMouseEvent* ev) override; - - void AddKeyToTrack(STimelineTrack& subTrack, SAnimTime time); - - void keyPressEvent(QKeyEvent* ev) override; - void keyReleaseEvent(QKeyEvent* ev) override; - void resizeEvent(QResizeEvent* ev) override; - void wheelEvent(QWheelEvent* ev) override; - QSize sizeHint() const override; - -signals: - void SignalScrub(bool scrubThrough); - void SignalContentChanged(bool continuous); - void SignalSelectionChanged(bool continuous); - void SignalTrackSelectionChanged(); - void SignalPlay(); - void SignalNumberHotkey(int number); - void SignalTreeContextMenu(const QPoint& point); - - void SignalUndo(); - void SignalRedo(); - -protected slots: - void OnMenuSelectionToCursor(); - void OnMenuDuplicate(); - void OnMenuCopy(); - void OnMenuPaste(); - void OnMenuDelete(); - void OnMenuPlay(); - void OnMenuNextKey(); - void OnMenuPreviousKey(); - void OnMenuNextFrame(); - void OnMenuPreviousFrame(); - void OnFilterChanged(); - void OnVerticalScroll(int value); - -protected: - - bool event(QEvent* e) override; - -private: - struct SMouseHandler; - struct SSelectionHandler; - struct SMoveHandler; - struct SPanHandler; - struct SScrubHandler; - struct SSplitterHandler; - struct STreeMouseHandler; - - void ContentChanged(bool continuous); - void UpdateLayout(); - void UpdateCursor(QMouseEvent* ev); - void DrawMarkers(QPainter& painter, int offsetY); - SAnimTime ClampAndSnapTime(SAnimTime time, bool snapToFrames) const; - void ClampAndSetTime(SAnimTime time, bool scrubThrough); - STrackLayout* GetTrackLayoutFromPos(const QPoint& pos) const; - - // Exposed parameters - float m_timeUnitScale; - int m_timeStepNum; - int m_timeStepIndex; - SAnimTime::EFrameRate m_frameRate; - bool m_cycled : 1; - bool m_sizeToContent : 1; - bool m_snapTime : 1; - bool m_snapKeys : 1; - bool m_treeVisible : 1; - bool m_selIndicators : 1; - bool m_verticalScrollbarVisible : 1; - bool m_drawMarkers : 1; - uint m_keyWidth; - float m_keyRadius; - uint m_cornerWidgetWidth; - - // Widgets - QScrollBar* m_scrollBar; - QWidget* m_cornerWidget; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - STimelineViewState m_viewState; - STimelineContent* m_pContent; - SAnimTime m_time; - std::unique_ptr m_layout; - std::unique_ptr m_mouseHandler; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - // Filtering - QLineEdit* m_pFilterLineEdit; - - // Track selection - STrackLayout* m_pLastSelectedTrack; - - friend class CTimelineTracks; -}; - -class CTimelineTracks - : public QWidget -{ - Q_OBJECT -public: - CTimelineTracks(QWidget* widget) - : QWidget(widget) {} - void ConnectToTimeline(CTimeline* timeline) { m_timeline = timeline; } - -private: - CTimeline* m_timeline; -}; - - - -#endif // CRYINCLUDE_EDITORCOMMON_TIMELINE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/TimelineContent.cpp b/Code/Sandbox/Plugins/EditorCommon/TimelineContent.cpp deleted file mode 100644 index 8ee8c3acf6..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/TimelineContent.cpp +++ /dev/null @@ -1,20 +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 "TimelineContent.h" -#include "Serialization.h" - -SERIALIZATION_ENUM_BEGIN_NESTED(STimelineElement, ECaps, "Capabilities") -SERIALIZATION_ENUM_VALUE_NESTED(STimelineElement, CAP_SELECT, "Select") -SERIALIZATION_ENUM_VALUE_NESTED(STimelineElement, CAP_MOVE, "Move") -SERIALIZATION_ENUM_VALUE_NESTED(STimelineElement, CAP_DELETE, "Delete") -SERIALIZATION_ENUM_VALUE_NESTED(STimelineElement, CAP_CHANGE_DURATION, "Change Duration") -SERIALIZATION_ENUM_END() diff --git a/Code/Sandbox/Plugins/EditorCommon/TimelineContent.h b/Code/Sandbox/Plugins/EditorCommon/TimelineContent.h deleted file mode 100644 index a2d89f9c7d..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/TimelineContent.h +++ /dev/null @@ -1,154 +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_EDITORCOMMON_TIMELINECONTENT_H -#define CRYINCLUDE_EDITORCOMMON_TIMELINECONTENT_H -#pragma once - -#include "QPropertyTree/Color.h" -#include "Serialization/Strings.h" -#include "Serialization/SmartPtr.h" -#include "Serialization.h" - -#include -#include - -using Serialization::string; - -struct STimelineElement -{ - enum EType - { - KEY, - CLIP - }; - - enum ECaps - { - CAP_SELECT = BIT(0), - CAP_DELETE = BIT(1), - - // not implemented: - CAP_MOVE = BIT(2), - CAP_CHANGE_DURATION = BIT(3) - }; - - EType type; - int caps; - SAnimTime start; - SAnimTime end; - ColorB color; - float baseWeight; - uint64 userId; - string description; - DynArray userSideLoad; - // state flags - bool selected : 1; - bool added : 1; - bool deleted : 1; - bool sideLoadChanged : 1; - - STimelineElement() - : type(KEY) - , start(0.0f) - , end(0.1f) - , color(212, 212, 212, 255) - , caps(CAP_SELECT | CAP_MOVE | CAP_CHANGE_DURATION) - , selected(false) - , added(false) - , deleted(false) - , sideLoadChanged(false) - , userId(0) - { - } - - void Serialize(IArchive& ar) - { - ar(type, "type", "^>80>"); - ar(start, "start", "^"); - if (type == CLIP) - { - ar(end, "end", "^"); - } - ar(BitFlags(caps), "caps", "Capabilities"); - ar(color, "color", "Color"); - } -}; -typedef std::vector STimelineElements; - -struct STimelineTrack; -typedef std::vector<_smart_ptr > STimelineTracks; - -struct STimelineTrack - : public _i_reference_target_t -{ - enum ECaps - { - CAP_ADD_ELEMENTS = BIT(0), - CAP_DESCRIPTION_TRACK = BIT(1), // No keys - CAP_COMPOUND_TRACK = BIT(2), // No own keys, but will show combined keys for child tracks - CAP_TOGGLE_TRACK = BIT(3), // For boolean tracks that are either on or off between keys. Used to key visibility etc. - }; - bool expanded : 1; - bool modified : 1; - bool selected : 1; - bool deleted : 1; - bool keySelectionChanged : 1; - bool toggleDefaultState : 1; // Default state for toggle tracks (on or off) - int height; - int caps; - SAnimTime startTime; - SAnimTime endTime; - string type; - string name; - DynArray userSideLoad; - STimelineElements elements; - STimelineElement defaultElement; - STimelineTracks tracks; - - STimelineTrack() - : expanded(true) - , modified(false) - , selected(false) - , deleted(false) - , keySelectionChanged(false) - , height(64) - , startTime(0.0f) - , endTime(1.0f) - , caps(CAP_ADD_ELEMENTS) - {} - - void Serialize(IArchive& ar) - { - ar(name, "name", "^"); - ar(type, "type", "^"); - ar(height, "height", "Height"); - ar(startTime, "startTime", "Start Time"); - ar(endTime, "endTime", "End Time"); - ar(elements, "elements", "Elements"); - ar(tracks, "tracks", "+Tracks"); - } -}; - -struct STimelineContent -{ - STimelineTrack track; - DynArray userSideLoad; - - void Serialize(IArchive& ar) - { - ar(track, "track", "Track"); - } -}; - -#endif // CRYINCLUDE_EDITORCOMMON_TIMELINECONTENT_H diff --git a/Code/Sandbox/Plugins/EditorCommon/UnsavedChangesDialog.cpp b/Code/Sandbox/Plugins/EditorCommon/UnsavedChangesDialog.cpp deleted file mode 100644 index 71acb24c3c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/UnsavedChangesDialog.cpp +++ /dev/null @@ -1,117 +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 "EditorCommon_precompiled.h" -#include "UnsavedChangesDialog.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -CUnsavedChangedDialog::CUnsavedChangedDialog(QWidget* parent) - : QDialog(parent) -{ - setWindowTitle("Unsaved Changes"); - setModal(true); - - auto layout = new QBoxLayout(QBoxLayout::TopToBottom); - auto label = new QLabel("The following files were modified.\n\nWould you like to save them before closing?"); - layout->addWidget(label, 0); - - m_list = new QListWidget(); - layout->addWidget(m_list, 1); - - auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Yes | QDialogButtonBox::No | QDialogButtonBox::Cancel, Qt::Horizontal); - layout->addWidget(buttonBox, 0); - - connect(buttonBox, &QDialogButtonBox::clicked, this, [this, buttonBox](QAbstractButton* button) - { - done(buttonBox->buttonRole(button)); - }); - - setLayout(layout); - resize(500, 350); - - if (parent) - { - QPoint center = parent->mapToGlobal(parent->geometry().center()); - const QRect screenDimensions = QApplication::screenAt(center)->geometry(); - if (screenDimensions.contains(center)) - { - QPoint dialogPosition = center - QPoint(width() / 2, height() / 2); - if (screenDimensions.contains(dialogPosition)) - { - move(dialogPosition); - } - else - { - move(center); - } - } - else - { - move((screenDimensions.width() - width()) / 2, (screenDimensions.height() - height()) / 2); - } - } -} - -bool CUnsavedChangedDialog::Exec(DynArray* selectedFiles, const DynArray& files) -{ - m_list->clear(); - - std::vector items(files.size(), nullptr); - - for (size_t i = 0; i < files.size(); ++i) - { - auto item = new QListWidgetItem(files[i].c_str(), m_list); - item->setFlags(item->flags() | Qt::ItemIsUserCheckable); - item->setCheckState(Qt::Checked); - items[i] = item; - } - - selectedFiles->clear(); - - int result = exec(); - if (result == QDialogButtonBox::YesRole) - { - for (size_t i = 0; i < items.size(); ++i) - { - if (items[i]->checkState() == Qt::Checked) - { - selectedFiles->push_back(files[i].c_str()); - } - } - return true; - } - else if (result == QDialogButtonBox::NoRole) - { - return true; - } - else - { - return false; - } -} - -bool EDITOR_COMMON_API UnsavedChangesDialog(QWidget* parent, DynArray* selectedFiles, const DynArray& files) -{ - CUnsavedChangedDialog dialog(parent); - return dialog.Exec(selectedFiles, files); -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/UnsavedChangesDialog.h b/Code/Sandbox/Plugins/EditorCommon/UnsavedChangesDialog.h deleted file mode 100644 index 999b226845..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/UnsavedChangesDialog.h +++ /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. - -#pragma once - -#if !defined(Q_MOC_RUN) -#include "EditorCommonAPI.h" -#include "Serialization/Strings.h" -#include "Serialization/DynArray.h" - -#include -#endif -class QListWidget; - -// Supposed to be used through -// ConfirmSaveDialog function. -class CUnsavedChangedDialog - : public QDialog -{ - Q_OBJECT -public: - CUnsavedChangedDialog(QWidget* parent); - - bool Exec(DynArray* selectedFiles, const DynArray& files); -private: - QListWidget* m_list; - int m_result; -}; - -// Returns true if window should be closed (Yes/No). False for Cancel. -// selectedFiles contains list of files that should be saved (empty in No case). -bool EDITOR_COMMON_API UnsavedChangesDialog(QWidget* parent, DynArray* selectedFiles, const DynArray& files); diff --git a/Code/Sandbox/Plugins/EditorCommon/editorcommon_files.cmake b/Code/Sandbox/Plugins/EditorCommon/editorcommon_files.cmake index 5551c07be1..a7b3860905 100644 --- a/Code/Sandbox/Plugins/EditorCommon/editorcommon_files.cmake +++ b/Code/Sandbox/Plugins/EditorCommon/editorcommon_files.cmake @@ -13,16 +13,8 @@ set(FILES EditorCommon.h EditorCommon.cpp EditorCommon.rc - EditorCommon.qrc EditorCommonAPI.h - moc.cpp - QViewportConsumer.h - TimelineContent.h EditorCommon_precompiled.h - CurveEditorControl.cpp - CurveEditorControl.h - DisplayViewportAdapter.cpp - DisplayViewportAdapter.h ActionOutput.h ActionOutput.cpp UiEditorDLLBus.h @@ -30,140 +22,16 @@ set(FILES DockTitleBarWidget.h SaveUtilities/AsyncSaveRunner.h SaveUtilities/AsyncSaveRunner.cpp - Events/EventManager.cpp - Events/EventManager.h AxisHelper.cpp DisplayContext.cpp - QPropertyTree/PropertyRowSlider.cpp - BatchFileDialog.cpp - BatchFileDialog.h DeepFilterProxyModel.cpp DeepFilterProxyModel.h - QAbstractQVariantTreeDataModel.h - QAbstractQVariantTreeDataModel.cpp - UnsavedChangesDialog.h - UnsavedChangesDialog.cpp Resource.h DrawingPrimitives/Ruler.cpp DrawingPrimitives/Ruler.h DrawingPrimitives/TimeSlider.cpp DrawingPrimitives/TimeSlider.h - Timeline.cpp - Timeline.h - CurveEditor.cpp - CurveEditor.h - CurveEditorContent.h WinWidget/WinWidget.h WinWidget/WinWidgetManager.h WinWidget/WinWidgetManager.cpp - QPropertyTree/Color.cpp - QPropertyTree/Color.h - QPropertyTree/ConstStringList.cpp - QPropertyTree/ConstStringList.h - QPropertyTree/Factory.h - QPropertyTree/MathUtils.h - QPropertyTree/PropertyDrawContext.cpp - QPropertyTree/PropertyDrawContext.h - QPropertyTree/PropertyIArchive.cpp - QPropertyTree/PropertyIArchive.h - QPropertyTree/PropertyOArchive.cpp - QPropertyTree/PropertyOArchive.h - QPropertyTree/PropertyRow.cpp - QPropertyTree/PropertyRow.h - QPropertyTree/PropertyRowActionButton.cpp - QPropertyTree/PropertyRowBool.cpp - QPropertyTree/PropertyRowBool.h - QPropertyTree/PropertyRowColor.cpp - QPropertyTree/PropertyRowColor.h - QPropertyTree/PropertyRowColorPicker.cpp - QPropertyTree/PropertyRowColorPicker.h - QPropertyTree/PropertyRowContainer.cpp - QPropertyTree/PropertyRowContainer.h - QPropertyTree/PropertyRowField.cpp - QPropertyTree/PropertyRowField.h - QPropertyTree/PropertyRowIconXPM.cpp - QPropertyTree/PropertyRowImpl.h - QPropertyTree/PropertyRowLocalFrame.cpp - QPropertyTree/PropertyRowLocalFrame.h - QPropertyTree/PropertyRowNumber.cpp - QPropertyTree/PropertyRowNumber.h - QPropertyTree/PropertyRowNumberField.cpp - QPropertyTree/PropertyRowNumberField.h - QPropertyTree/PropertyRowObject.cpp - QPropertyTree/PropertyRowObject.h - QPropertyTree/PropertyRowPointer.cpp - QPropertyTree/PropertyRowPointer.h - QPropertyTree/PropertyRowSprite.cpp - QPropertyTree/PropertyRowSprite.h - QPropertyTree/PropertyRowString.h - QPropertyTree/PropertyRowString.cpp - QPropertyTree/PropertyRowStringListValue.cpp - QPropertyTree/PropertyRowStringListValue.h - QPropertyTree/PropertyRowTagList.cpp - QPropertyTree/PropertyRowTagList.h - QPropertyTree/PropertyRowToggleButton.cpp - QPropertyTree/PropertyTreeMenuHandler.h - QPropertyTree/PropertyTreeModel.cpp - QPropertyTree/PropertyTreeModel.h - QPropertyTree/PropertyTreeOperator.cpp - QPropertyTree/PropertyTreeOperator.h - QPropertyTree/QPropertyTree.cpp - QPropertyTree/QPropertyTree.h - QPropertyTree/QPropertyTreeStyle.h - QPropertyTree/Serialization.h - QPropertyTree/Strings.h - QPropertyTree/Unicode.h - QPropertyTree/ContextList.h - QPropertyTree/file_open.xpm - QPropertyTree/file_save.xpm - QPropertyTree/SlicerEdit.cpp - QPropertyTree/SlicerEdit.h - QPropertyTree/SlicerManipulator.cpp - QPropertyTree/SlicerManipulator.h - QPropertyTree/SlicerView.cpp - QPropertyTree/SlicerView.h - QPropertyTree/SpriteBorderEditor.cpp - QPropertyTree/SpriteBorderEditor.h - QPropertyTree/SpriteBorderEditorCommon.cpp - QPropertyTree/SpriteBorderEditorCommon.h - QPropertyTree/ValidatorBlock.h - ListSelectionDialog.cpp - ListSelectionDialog.h - QViewport.cpp - QViewport.h - QViewportEvents.h - QViewportSettings.h - QPropertyTree/PropertyRowResourceFilePath.cpp - QPropertyTree/PropertyRowResourceFilePath.h - QPropertyTree/PropertyRowResourceFolderPath.cpp - QPropertyTree/PropertyRowResourceFolderPath.h - QPropertyTree/PropertyRowResourceSelector.cpp - QPropertyTree/PropertyRowResourceSelector.h - QPropertyTree/PropertyRowOutputFilePath.cpp - QPropertyTree/PropertyRowOutputFilePath.h - QPropertyTree/QPropertyDialog.cpp - QPropertyTree/QPropertyDialog.h - Serialization.cpp - Serialization.h - Serialization/BinArchive.cpp - Serialization/BinArchive.h - Serialization/JSONIArchive.cpp - Serialization/JSONIArchive.h - Serialization/JSONOArchive.cpp - Serialization/JSONOArchive.h - Serialization/MemoryReader.cpp - Serialization/MemoryReader.h - Serialization/MemoryWriter.cpp - Serialization/MemoryWriter.h - Serialization/Pointers.h - Serialization/PointersImpl.h - Serialization/Qt.cpp - Serialization/Qt.h - Serialization/QtImpl.h - Serialization/Token.h - Serialization/Decorators/ToggleButton.h - Serialization/Decorators/ToggleButtonImpl.h - Serialization/Decorators/IGizmoSink.h - Serialization/Decorators/IconXPM.h - Serialization/Decorators/INavigationProvider.h ) diff --git a/Code/Sandbox/Plugins/EditorCommon/moc.cpp b/Code/Sandbox/Plugins/EditorCommon/moc.cpp deleted file mode 100644 index ce9570b673..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/moc.cpp +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include -#include -#include - -#include -#include -#include diff --git a/Gems/AudioEngineWwise/Code/Platform/Android/AudioEngineWwise_Traits_Android.h b/Gems/AudioEngineWwise/Code/Platform/Android/AudioEngineWwise_Traits_Android.h index 336d6e78c0..b753d321da 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Android/AudioEngineWwise_Traits_Android.h +++ b/Gems/AudioEngineWwise/Code/Platform/Android/AudioEngineWwise_Traits_Android.h @@ -22,7 +22,6 @@ #endif #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE 32 << 10 /* 32 MiB */ #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE_DEFAULT_TEXT "32768 (32 MiB)" -#define AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE_DEFAULT_TEXT "0 (0 MiB)" #define AZ_TRAIT_AUDIOENGINEWWISE_STREAMER_DEVICE_MEMORY_POOL_SIZE 2 << 10 /* 2 MiB */ diff --git a/Gems/AudioEngineWwise/Code/Platform/Linux/AudioEngineWwise_Traits_Linux.h b/Gems/AudioEngineWwise/Code/Platform/Linux/AudioEngineWwise_Traits_Linux.h index 6df576637b..a7900484e3 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Linux/AudioEngineWwise_Traits_Linux.h +++ b/Gems/AudioEngineWwise/Code/Platform/Linux/AudioEngineWwise_Traits_Linux.h @@ -26,7 +26,6 @@ #endif #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE 128 << 10 /* 128 MiB */ #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE_DEFAULT_TEXT "131072 (128 MiB)" -#define AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE_DEFAULT_TEXT "0 (0 MiB)" #define AZ_TRAIT_AUDIOENGINEWWISE_STREAMER_DEVICE_MEMORY_POOL_SIZE 2 << 10 /* 2 MiB */ diff --git a/Gems/AudioEngineWwise/Code/Platform/Mac/AudioEngineWwise_Traits_Mac.h b/Gems/AudioEngineWwise/Code/Platform/Mac/AudioEngineWwise_Traits_Mac.h index 6df576637b..a7900484e3 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Mac/AudioEngineWwise_Traits_Mac.h +++ b/Gems/AudioEngineWwise/Code/Platform/Mac/AudioEngineWwise_Traits_Mac.h @@ -26,7 +26,6 @@ #endif #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE 128 << 10 /* 128 MiB */ #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE_DEFAULT_TEXT "131072 (128 MiB)" -#define AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE_DEFAULT_TEXT "0 (0 MiB)" #define AZ_TRAIT_AUDIOENGINEWWISE_STREAMER_DEVICE_MEMORY_POOL_SIZE 2 << 10 /* 2 MiB */ diff --git a/Gems/AudioEngineWwise/Code/Platform/Windows/AudioEngineWwise_Traits_Windows.h b/Gems/AudioEngineWwise/Code/Platform/Windows/AudioEngineWwise_Traits_Windows.h index c1c51482fb..b71f0b7d0d 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Windows/AudioEngineWwise_Traits_Windows.h +++ b/Gems/AudioEngineWwise/Code/Platform/Windows/AudioEngineWwise_Traits_Windows.h @@ -26,7 +26,6 @@ #endif #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE 128 << 10 /* 128 MiB */ #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE_DEFAULT_TEXT "131072 (128 MiB)" -#define AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE_DEFAULT_TEXT "0 (0 MiB)" #define AZ_TRAIT_AUDIOENGINEWWISE_STREAMER_DEVICE_MEMORY_POOL_SIZE 2 << 10 /* 2 MiB */ diff --git a/Gems/AudioEngineWwise/Code/Platform/iOS/AudioEngineWwise_Traits_iOS.h b/Gems/AudioEngineWwise/Code/Platform/iOS/AudioEngineWwise_Traits_iOS.h index 336d6e78c0..b753d321da 100644 --- a/Gems/AudioEngineWwise/Code/Platform/iOS/AudioEngineWwise_Traits_iOS.h +++ b/Gems/AudioEngineWwise/Code/Platform/iOS/AudioEngineWwise_Traits_iOS.h @@ -22,7 +22,6 @@ #endif #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE 32 << 10 /* 32 MiB */ #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE_DEFAULT_TEXT "32768 (32 MiB)" -#define AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE_DEFAULT_TEXT "0 (0 MiB)" #define AZ_TRAIT_AUDIOENGINEWWISE_STREAMER_DEVICE_MEMORY_POOL_SIZE 2 << 10 /* 2 MiB */ diff --git a/Gems/AudioEngineWwise/Code/Source/AudioEngineWwiseGemSystemComponent.cpp b/Gems/AudioEngineWwise/Code/Source/AudioEngineWwiseGemSystemComponent.cpp index faaf4d5c75..c5dae7de75 100644 --- a/Gems/AudioEngineWwise/Code/Source/AudioEngineWwiseGemSystemComponent.cpp +++ b/Gems/AudioEngineWwise/Code/Source/AudioEngineWwiseGemSystemComponent.cpp @@ -36,10 +36,6 @@ namespace Audio { CAudioLogger g_audioImplLogger_wwise; -#if AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL - TMemoryPoolReferenced g_audioImplMemoryPoolSecondary_wwise; -#endif // AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL - namespace Platform { void* InitializeSecondaryMemoryPool(size_t& secondarySize); @@ -154,13 +150,6 @@ namespace AudioEngineWwiseGem m_engineWwise = AZStd::make_unique(assetPlatform.c_str()); if (m_engineWwise) { - #if AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL - size_t secondarySize = 0; - void* secondaryMemoryPtr = Audio::Platform::InitializeSecondaryMemoryPool(secondarySize); - - Audio::g_audioImplMemoryPoolSecondary_wwise.InitMem(secondarySize, static_cast(secondaryMemoryPtr)); - #endif // AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL - Audio::g_audioImplLogger_wwise.Log(Audio::eALT_ALWAYS, "AudioEngineWwise created!"); Audio::SAudioRequest oAudioRequestData; diff --git a/Gems/AudioEngineWwise/Code/Source/Editor/AudioSystemEditor_wwise.h b/Gems/AudioEngineWwise/Code/Source/Editor/AudioSystemEditor_wwise.h index e35b225fc6..ee7b54217d 100644 --- a/Gems/AudioEngineWwise/Code/Source/Editor/AudioSystemEditor_wwise.h +++ b/Gems/AudioEngineWwise/Code/Source/Editor/AudioSystemEditor_wwise.h @@ -35,12 +35,6 @@ namespace AudioControls bool HasProperties() override { return true; } - void Serialize(Serialization::IArchive& ar) override - { - ar(m_mult, "mult", "Multiply"); - ar(m_shift, "shift", "Shift"); - } - float m_mult; float m_shift; }; @@ -61,11 +55,6 @@ namespace AudioControls bool HasProperties() override { return true; } - void Serialize(Serialization::IArchive& ar) override - { - ar(m_value, "value", "Value"); - } - float m_value; }; diff --git a/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp b/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp index 89afb0bf33..2e11c7a810 100644 --- a/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp +++ b/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp @@ -1757,16 +1757,9 @@ namespace Audio memoryInfo.nPrimaryPoolSize = AZ::AllocatorInstance::Get().Capacity(); memoryInfo.nPrimaryPoolUsedSize = memoryInfo.nPrimaryPoolSize - AZ::AllocatorInstance::Get().GetUnAllocatedMemory(); memoryInfo.nPrimaryPoolAllocations = 0; - - #if AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL - memoryInfo.nSecondaryPoolSize = g_audioImplMemoryPoolSecondary_wwise.MemSize(); - memoryInfo.nSecondaryPoolUsedSize = memoryInfo.nSecondaryPoolSize - g_audioImplMemoryPoolSecondary_wwise.MemFree(); - memoryInfo.nSecondaryPoolAllocations = g_audioImplMemoryPoolSecondary_wwise.FragmentCount(); - #else memoryInfo.nSecondaryPoolSize = 0; memoryInfo.nSecondaryPoolUsedSize = 0; memoryInfo.nSecondaryPoolAllocations = 0; - #endif // AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL } /////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Gems/AudioEngineWwise/Code/Source/Engine/Common_wwise.h b/Gems/AudioEngineWwise/Code/Source/Engine/Common_wwise.h index 7f67196dc6..2e806a80e9 100644 --- a/Gems/AudioEngineWwise/Code/Source/Engine/Common_wwise.h +++ b/Gems/AudioEngineWwise/Code/Source/Engine/Common_wwise.h @@ -19,20 +19,6 @@ #include #include - -#if AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL - #include - #include - - using TMemoryPoolReferenced = NCryPoolAlloc::CThreadSafe, NCryPoolAlloc::CListItemReference>>; - - namespace Audio - { - extern TMemoryPoolReferenced g_audioImplMemoryPoolSecondary_wwise; - } -#endif // AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL - - #define WWISE_IMPL_VERSION_STRING "Wwise " AK_WWISESDK_VERSIONNAME #define ASSERT_WWISE_OK(x) (AKASSERT((x) == AK_Success)) diff --git a/Gems/AudioSystem/Code/Include/Editor/IAudioConnection.h b/Gems/AudioSystem/Code/Include/Editor/IAudioConnection.h index 5191f211b8..084b14bd18 100644 --- a/Gems/AudioSystem/Code/Include/Editor/IAudioConnection.h +++ b/Gems/AudioSystem/Code/Include/Editor/IAudioConnection.h @@ -14,8 +14,6 @@ #pragma once #include -#include -#include namespace AudioControls { @@ -40,10 +38,6 @@ namespace AudioControls return false; } - virtual void Serialize([[maybe_unused]] Serialization::IArchive& ar) - { - } - private: CID m_id; }; diff --git a/Gems/AudioSystem/Code/Source/Editor/AudioControl.h b/Gems/AudioSystem/Code/Source/Editor/AudioControl.h index 878cf269c6..a974c5f556 100644 --- a/Gems/AudioSystem/Code/Source/Editor/AudioControl.h +++ b/Gems/AudioSystem/Code/Source/Editor/AudioControl.h @@ -19,6 +19,7 @@ #include #include +#include #include namespace AudioControls diff --git a/Gems/AudioSystem/Code/Source/Editor/AudioResourceSelectors.cpp b/Gems/AudioSystem/Code/Source/Editor/AudioResourceSelectors.cpp index 6edf80e3fe..101454db58 100644 --- a/Gems/AudioSystem/Code/Source/Editor/AudioResourceSelectors.cpp +++ b/Gems/AudioSystem/Code/Source/Editor/AudioResourceSelectors.cpp @@ -13,7 +13,6 @@ #include #include -#include #include #include #include diff --git a/Gems/AudioSystem/Code/Source/Editor/ConnectionsWidget.ui b/Gems/AudioSystem/Code/Source/Editor/ConnectionsWidget.ui index e2043df679..120df694bc 100644 --- a/Gems/AudioSystem/Code/Source/Editor/ConnectionsWidget.ui +++ b/Gems/AudioSystem/Code/Source/Editor/ConnectionsWidget.ui @@ -120,28 +120,6 @@ 6 - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - @@ -153,12 +131,6 @@ QListWidget
QConnectionListWidget.h
- - QPropertyTree - QWidget -
QPropertyTree/QPropertyTree.h
- 1 -
diff --git a/Gems/AudioSystem/Code/Source/Editor/QConnectionsWidget.cpp b/Gems/AudioSystem/Code/Source/Editor/QConnectionsWidget.cpp index 27e810202d..ab025d5b2d 100644 --- a/Gems/AudioSystem/Code/Source/Editor/QConnectionsWidget.cpp +++ b/Gems/AudioSystem/Code/Source/Editor/QConnectionsWidget.cpp @@ -26,8 +26,6 @@ #include #include #include -#include -#include namespace AudioControls { @@ -40,10 +38,6 @@ namespace AudioControls { setupUi(this); - m_connectionProperties->setSizeToContent(true); - m_connectionPropertiesFrame->setHidden(true); - connect(m_connectionProperties, SIGNAL(signalChanged()), this, SLOT(CurrentConnectionModified())); - m_connectionList->viewport()->installEventFilter(this); m_connectionList->installEventFilter(this); @@ -131,17 +125,6 @@ namespace AudioControls } } } - - if (connection && connection->HasProperties()) - { - m_connectionProperties->attach(Serialization::SStruct(*connection.get())); - m_connectionPropertiesFrame->setHidden(false); - } - else - { - m_connectionProperties->detach(); - m_connectionPropertiesFrame->setHidden(true); - } } //-------------------------------------------------------------------------------------------// diff --git a/Gems/GameEffectSystem/preview.png b/Gems/GameEffectSystem/preview.png deleted file mode 100644 index b3a5a5880e..0000000000 --- a/Gems/GameEffectSystem/preview.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:fed875535032ff47526dd94870fc171028f3126a5c1d98f773f7da8083d495e4 -size 40620 diff --git a/Gems/LyShine/Code/Editor/ViewportWidget.cpp b/Gems/LyShine/Code/Editor/ViewportWidget.cpp index 753e207288..89c5a0bb50 100644 --- a/Gems/LyShine/Code/Editor/ViewportWidget.cpp +++ b/Gems/LyShine/Code/Editor/ViewportWidget.cpp @@ -18,7 +18,6 @@ #include #include #include -#include #include #include diff --git a/Gems/Maestro/Code/Source/Cinematics/CryMovie.cpp b/Gems/Maestro/Code/Source/Cinematics/CryMovie.cpp deleted file mode 100644 index cec0fd5f01..0000000000 --- a/Gems/Maestro/Code/Source/Cinematics/CryMovie.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "Maestro_precompiled.h" -#include "CryMovie.h" -#include "Movie.h" -#include - -#include -#include -#include - -#undef GetClassName - -////////////////////////////////////////////////////////////////////////// -struct CSystemEventListner_Movie - : public ISystemEventListener -{ -public: - virtual void OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam) - { - switch (event) - { - case ESYSTEM_EVENT_LEVEL_POST_UNLOAD: - { - STLALLOCATOR_CLEANUP; - CLightAnimWrapper::ReconstructCache(); - break; - } - } - } -}; - -static CSystemEventListner_Movie g_system_event_listener_movie; - -////////////////////////////////////////////////////////////////////////// -class CEngineModule_CryMovie - : public IEngineModule -{ - CRYINTERFACE_SIMPLE(IEngineModule) - CRYGENERATE_SINGLETONCLASS(CEngineModule_CryMovie, "EngineModule_CryMovie", 0xdce26beebdc6400f, 0xa0e9b42839f2dd5b) - - ////////////////////////////////////////////////////////////////////////// - virtual const char* GetName() const { - return "CryMovie"; - }; - virtual const char* GetCategory() const { return "CryEngine"; }; - - ////////////////////////////////////////////////////////////////////////// - virtual bool Initialize(SSystemGlobalEnvironment& env, const SSystemInitParams& initParams) - { - ISystem* pSystem = env.pSystem; - - pSystem->GetISystemEventDispatcher()->RegisterListener(&g_system_event_listener_movie); - - env.pMovieSystem = aznew CMovieSystem(pSystem); - return true; - } -}; - -CRYREGISTER_SINGLETON_CLASS(CEngineModule_CryMovie) - -CEngineModule_CryMovie::CEngineModule_CryMovie() -{ -}; - -CEngineModule_CryMovie::~CEngineModule_CryMovie() -{ -}; diff --git a/Gems/Maestro/Code/Source/Cinematics/CryMovie.def b/Gems/Maestro/Code/Source/Cinematics/CryMovie.def deleted file mode 100644 index fc5c3c91cd..0000000000 --- a/Gems/Maestro/Code/Source/Cinematics/CryMovie.def +++ /dev/null @@ -1,3 +0,0 @@ -EXPORTS - ModuleInitISystem @2 - CryModuleGetMemoryInfo @8 diff --git a/Gems/Maestro/Code/Source/Cinematics/CryMovie.h b/Gems/Maestro/Code/Source/Cinematics/CryMovie.h deleted file mode 100644 index 6936f4e1fb..0000000000 --- a/Gems/Maestro/Code/Source/Cinematics/CryMovie.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. - - -// The following ifdef block is the standard way of creating macros which make exporting -// from a DLL simpler. All files within this DLL are compiled with the CRYMOVIE_EXPORTS -// symbol defined on the command line. this symbol should not be defined on any project -// that uses this DLL. This way any other project whose source files include this file see -// CRYMOVIE_API functions as being imported from a DLL, wheras this DLL sees symbols -// defined with this macro as being exported. - -#ifndef CRYINCLUDE_CRYMOVIE_CRYMOVIE_H -#define CRYINCLUDE_CRYMOVIE_CRYMOVIE_H -#pragma once - -#ifdef CRYMOVIE_EXPORTS - #define CRYMOVIE_API DLL_EXPORT -#else - #define CRYMOVIE_API DLL_IMPORT -#endif - -struct ISystem; -struct IMovieSystem; - -extern "C" -{ -CRYMOVIE_API IMovieSystem* CreateMovieSystem(ISystem* pSystem); -CRYMOVIE_API void DeleteMovieSystem(IMovieSystem* pMM); -} -#endif // CRYINCLUDE_CRYMOVIE_CRYMOVIE_H diff --git a/Gems/Maestro/Code/Source/Cinematics/CryMovie.rc b/Gems/Maestro/Code/Source/Cinematics/CryMovie.rc deleted file mode 100644 index 5730d0a537..0000000000 --- a/Gems/Maestro/Code/Source/Cinematics/CryMovie.rc +++ /dev/null @@ -1,111 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "winres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// Russian resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_RUS) -#ifdef _WIN32 -LANGUAGE LANG_RUSSIAN, SUBLANG_DEFAULT -#pragma code_page(1251) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""winres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#endif // Russian resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// German (Germany) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_DEU) -#ifdef _WIN32 -LANGUAGE LANG_GERMAN, SUBLANG_GERMAN -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "000904b0" - BEGIN - VALUE "CompanyName", "Amazon.com, Inc." - VALUE "FileVersion", "1, 0, 0, 1" - VALUE "LegalCopyright", "Portions of this file Copyright (c) Amazon.com, Inc. or its affiliates. All Rights Reserved. Original file Copyright (c) Crytek GMBH. Used under license by Amazon.com, Inc. and its affiliates." - VALUE "ProductName", "Lumberyard" - VALUE "ProductVersion", "1, 0, 0, 1" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x9, 1200 - END -END - -#endif // German (Germany) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/Gems/SVOGI/preview.png b/Gems/SVOGI/preview.png deleted file mode 100644 index 2f1ed47754..0000000000 --- a/Gems/SVOGI/preview.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6d6204c6730e5675791765ca194e9b1cbec282208e280507de830afc2805e5fa -size 41127 diff --git a/cmake/TestImpactFramework/ConsoleFrontendConfig.in b/cmake/TestImpactFramework/ConsoleFrontendConfig.in index 5f3908671e..2371d7fb7f 100644 --- a/cmake/TestImpactFramework/ConsoleFrontendConfig.in +++ b/cmake/TestImpactFramework/ConsoleFrontendConfig.in @@ -50,7 +50,6 @@ include_filter = [ { target = "LmbrCentral.Editor.Tests", policy = "test_interleaved" }, { target = "EditorLib.Tests", policy = "test_interleaved" }, { target = "PhysX.Tests", policy = "test_interleaved" }, -{ target = "ImageProcessing.Tests", policy = "test_interleaved" }, { target = "Atom_RPI.Tests", policy = "test_interleaved" }, { target = "Atom_RHI.Tests", policy = "test_interleaved" }, { target = "AzManipulatorFramework.Tests", policy = "test_interleaved" }, diff --git a/scripts/build/package/Platform/Windows/package_filelists/atom.json b/scripts/build/package/Platform/Windows/package_filelists/atom.json index 885eff8504..f084173cb2 100644 --- a/scripts/build/package/Platform/Windows/package_filelists/atom.json +++ b/scripts/build/package/Platform/Windows/package_filelists/atom.json @@ -93,7 +93,6 @@ "GraphCanvas": "#include", "GraphModel": "#include", "HttpRequestor": "#include", - "ImageProcessing": "#include", "ImGui": "#include", "InAppPurchases": "#include", "LandscapeCanvas": "#include", diff --git a/scripts/commit_validation/commit_validation/pal_allowedlist.txt b/scripts/commit_validation/commit_validation/pal_allowedlist.txt index 278262d59c..e3bf4be52e 100644 --- a/scripts/commit_validation/commit_validation/pal_allowedlist.txt +++ b/scripts/commit_validation/commit_validation/pal_allowedlist.txt @@ -59,7 +59,6 @@ */Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/StandardPluginsConfig.h */Gems/EMotionFX/Code/MCore/Source/Config.h */Gems/GameStateSamples/Code/Include/GameStateSamples/GameStateLocalUserLobby.inl -*/Gems/ImageProcessing/Code/Tests/AtlasBuilderTest.cpp */Gems/PhysX/Code/Source/System/PhysXSystem.cpp */Gems/SaveData/Code/Tests/SaveDataTest.cpp */Gems/WhiteBox/Code/Source/Rendering/Legacy/WhiteBoxLegacyRenderMesh.cpp From dff8de94a5f4c235fc14587c58cfe146640947cb Mon Sep 17 00:00:00 2001 From: greerdv Date: Tue, 11 May 2021 16:57:23 +0100 Subject: [PATCH 045/100] making both colliders and shape colliders check m_simulating in IsPhysicsEnabled --- Gems/PhysX/Code/Source/EditorColliderComponent.cpp | 9 ++++++++- Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp | 9 ++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp index 2785ab19e1..2cf5835a1f 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp @@ -1057,7 +1057,14 @@ namespace PhysX bool EditorColliderComponent::IsPhysicsEnabled() const { - return m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle; + if (m_sceneInterface && m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) + { + if (auto* body = m_sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorBodyHandle)) + { + return body->m_simulating; + } + } + return false; } AZ::Aabb EditorColliderComponent::GetAabb() const diff --git a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp index 2c86a18301..b71bd47288 100644 --- a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp @@ -752,7 +752,14 @@ namespace PhysX bool EditorShapeColliderComponent::IsPhysicsEnabled() const { - return m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle; + if (m_sceneInterface && m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) + { + if (auto* body = m_sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorBodyHandle)) + { + return body->m_simulating; + } + } + return false; } AZ::Aabb EditorShapeColliderComponent::GetAabb() const From 26d886792d0b060c20b6c979db8718bcfa25684f Mon Sep 17 00:00:00 2001 From: Alex Peterson <26804013+AMZN-alexpete@users.noreply.github.com> Date: Tue, 11 May 2021 09:48:11 -0700 Subject: [PATCH 046/100] Initial Python bindings pass for ProjectManager Adds dependency on pybind and interface to call o3de.py functions from c++ --- Code/Tools/ProjectManager/CMakeLists.txt | 15 ++ .../Common/Clang/projectmanager_clang.cmake | 15 ++ .../Common/MSVC/projectmanager_msvc.cmake | 15 ++ .../Platform/Linux/PAL_linux.cmake | 1 + .../Platform/Linux/PAL_linux_files.cmake | 14 ++ .../Platform/Linux/Python_linux.cpp | 42 +++++ .../Platform/Mac/PAL_mac_files.cmake | 14 ++ .../Platform/Mac/Python_mac.cpp | 43 +++++ .../Platform/Windows/PAL_windows.cmake | 5 + .../Platform/Windows/PAL_windows_files.cmake | 14 ++ .../Platform/Windows/Python_windows.cpp | 43 +++++ .../Source/GemCatalog/GemInfo.h | 1 + .../ProjectManager/Source/ProjectInfo.cpp | 24 +++ .../Tools/ProjectManager/Source/ProjectInfo.h | 36 ++++ .../Source/ProjectManagerWindow.cpp | 3 + .../Source/ProjectManagerWindow.h | 3 +- .../ProjectManager/Source/ProjectsHome.cpp | 5 + .../ProjectManager/Source/PythonBindings.cpp | 155 ++++++++++++++++++ .../ProjectManager/Source/PythonBindings.h | 41 +++++ .../Source/PythonBindingsInterface.h | 39 +++++ Code/Tools/ProjectManager/Source/main.cpp | 32 ++-- .../project_manager_files.cmake | 5 + 22 files changed, 552 insertions(+), 13 deletions(-) create mode 100644 Code/Tools/ProjectManager/Platform/Common/Clang/projectmanager_clang.cmake create mode 100644 Code/Tools/ProjectManager/Platform/Common/MSVC/projectmanager_msvc.cmake create mode 100644 Code/Tools/ProjectManager/Platform/Linux/PAL_linux_files.cmake create mode 100644 Code/Tools/ProjectManager/Platform/Linux/Python_linux.cpp create mode 100644 Code/Tools/ProjectManager/Platform/Mac/PAL_mac_files.cmake create mode 100644 Code/Tools/ProjectManager/Platform/Mac/Python_mac.cpp create mode 100644 Code/Tools/ProjectManager/Platform/Windows/PAL_windows_files.cmake create mode 100644 Code/Tools/ProjectManager/Platform/Windows/Python_windows.cpp create mode 100644 Code/Tools/ProjectManager/Source/ProjectInfo.cpp create mode 100644 Code/Tools/ProjectManager/Source/ProjectInfo.h create mode 100644 Code/Tools/ProjectManager/Source/PythonBindings.cpp create mode 100644 Code/Tools/ProjectManager/Source/PythonBindings.h create mode 100644 Code/Tools/ProjectManager/Source/PythonBindingsInterface.h diff --git a/Code/Tools/ProjectManager/CMakeLists.txt b/Code/Tools/ProjectManager/CMakeLists.txt index e4354bac32..e2b5aaf696 100644 --- a/Code/Tools/ProjectManager/CMakeLists.txt +++ b/Code/Tools/ProjectManager/CMakeLists.txt @@ -13,6 +13,13 @@ if(NOT PAL_TRAIT_BUILD_HOST_TOOLS) return() endif() +# This will set python_package_name to whatever the package 'Python' is associated with +ly_get_package_association(Python python_package_name) +if (NOT python_package_name) + set(python_package_name "python-no-package-assocation-found") + message(WARNING "Python was not found in the package assocation list. Did someone call ly_associate_package(xxxxxxx Python) ?") +endif() + ly_add_target( NAME ProjectManager APPLICATION OUTPUT_NAME o3de @@ -22,7 +29,13 @@ ly_add_target( AUTORCC FILES_CMAKE project_manager_files.cmake + Platform/${PAL_PLATFORM_NAME}/PAL_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake + PLATFORM_INCLUDE_FILES Platform/${PAL_PLATFORM_NAME}/PAL_${PAL_PLATFORM_NAME_LOWERCASE}.cmake + Platform/Common/${PAL_TRAIT_COMPILER_ID}/projectmanager_${PAL_TRAIT_COMPILER_ID_LOWERCASE}.cmake + COMPILE_DEFINITIONS + PRIVATE + PY_PACKAGE="${python_package_name}" INCLUDE_DIRECTORIES PUBLIC . @@ -34,6 +47,8 @@ ly_add_target( 3rdParty::Qt::Core 3rdParty::Qt::Concurrent 3rdParty::Qt::Widgets + 3rdParty::Python + 3rdParty::pybind11 AZ::AzCore AZ::AzFramework AZ::AzToolsFramework diff --git a/Code/Tools/ProjectManager/Platform/Common/Clang/projectmanager_clang.cmake b/Code/Tools/ProjectManager/Platform/Common/Clang/projectmanager_clang.cmake new file mode 100644 index 0000000000..fb85a6cf2a --- /dev/null +++ b/Code/Tools/ProjectManager/Platform/Common/Clang/projectmanager_clang.cmake @@ -0,0 +1,15 @@ +# +# 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(LY_COMPILE_OPTIONS + PRIVATE + -fexceptions # The macro PYBIND11_EMBEDDED_MODULE uses a try catch block +) diff --git a/Code/Tools/ProjectManager/Platform/Common/MSVC/projectmanager_msvc.cmake b/Code/Tools/ProjectManager/Platform/Common/MSVC/projectmanager_msvc.cmake new file mode 100644 index 0000000000..669f14eae4 --- /dev/null +++ b/Code/Tools/ProjectManager/Platform/Common/MSVC/projectmanager_msvc.cmake @@ -0,0 +1,15 @@ +# +# 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(LY_COMPILE_OPTIONS + PRIVATE + /EHsc # The macro PYBIND11_EMBEDDED_MODULE uses a try catch block +) diff --git a/Code/Tools/ProjectManager/Platform/Linux/PAL_linux.cmake b/Code/Tools/ProjectManager/Platform/Linux/PAL_linux.cmake index 4d5680a30d..f5b9ea77a2 100644 --- a/Code/Tools/ProjectManager/Platform/Linux/PAL_linux.cmake +++ b/Code/Tools/ProjectManager/Platform/Linux/PAL_linux.cmake @@ -8,3 +8,4 @@ # 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. # + diff --git a/Code/Tools/ProjectManager/Platform/Linux/PAL_linux_files.cmake b/Code/Tools/ProjectManager/Platform/Linux/PAL_linux_files.cmake new file mode 100644 index 0000000000..a07534ee39 --- /dev/null +++ b/Code/Tools/ProjectManager/Platform/Linux/PAL_linux_files.cmake @@ -0,0 +1,14 @@ +# +# 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 + Python_linux.cpp +) diff --git a/Code/Tools/ProjectManager/Platform/Linux/Python_linux.cpp b/Code/Tools/ProjectManager/Platform/Linux/Python_linux.cpp new file mode 100644 index 0000000000..64ab9c9ca7 --- /dev/null +++ b/Code/Tools/ProjectManager/Platform/Linux/Python_linux.cpp @@ -0,0 +1,42 @@ +/* + * 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 + +namespace Platform +{ + extern bool InsertPythonLibraryPath(AZStd::unordered_set& paths, const char* pythonPackage, const char* engineRoot, const char* subPath); + + bool InsertPythonBinaryLibraryPaths(AZStd::unordered_set& paths, const char* pythonPackage, const char* engineRoot) + { + bool succeeded = true; + + succeeded = succeeded && InsertPythonLibraryPath(paths, pythonPackage, engineRoot, "python/runtime/%s/python/lib"); + succeeded = succeeded && InsertPythonLibraryPath(paths, pythonPackage, engineRoot, "python/runtime/%s/python/lib/python3.7/lib-dynload"); + succeeded = succeeded && InsertPythonLibraryPath(paths, pythonPackage, engineRoot, "python/runtime/%s/python/lib/python3.7"); + succeeded = succeeded && InsertPythonLibraryPath(paths, pythonPackage, engineRoot, "python/runtime/%s/python/lib/python3.7/site-packages"); + return succeeded; + } + + AZStd::string GetPythonHomePath(const char* pythonPackage, const char* engineRoot) + { + // append lib path to Python paths + AZ::IO::FixedMaxPath libPath = engineRoot; + libPath /= AZ::IO::FixedMaxPathString::format("python/runtime/%s/python", pythonPackage); + libPath = libPath.LexicallyNormal(); + return libPath.String(); + } +} diff --git a/Code/Tools/ProjectManager/Platform/Mac/PAL_mac_files.cmake b/Code/Tools/ProjectManager/Platform/Mac/PAL_mac_files.cmake new file mode 100644 index 0000000000..83124b6315 --- /dev/null +++ b/Code/Tools/ProjectManager/Platform/Mac/PAL_mac_files.cmake @@ -0,0 +1,14 @@ +# +# 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 + Python_mac.cpp +) diff --git a/Code/Tools/ProjectManager/Platform/Mac/Python_mac.cpp b/Code/Tools/ProjectManager/Platform/Mac/Python_mac.cpp new file mode 100644 index 0000000000..d3d55d6d5d --- /dev/null +++ b/Code/Tools/ProjectManager/Platform/Mac/Python_mac.cpp @@ -0,0 +1,43 @@ +/* + * 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 + +namespace Platform +{ + extern bool InsertPythonLibraryPath(AZStd::unordered_set& paths, const char* pythonPackage, const char* engineRoot, const char* subPath); + + bool InsertPythonBinaryLibraryPaths(AZStd::unordered_set& paths, const char* pythonPackage, const char* engineRoot) + { + bool succeeded = true; + + succeeded = succeeded && InsertPythonLibraryPath(paths, pythonPackage, engineRoot, "python/runtime/%s/Python.framework/Versions/3.7/lib"); + succeeded = succeeded && InsertPythonLibraryPath(paths, pythonPackage, engineRoot, "python/runtime/%s/Python.framework/Versions/3.7/lib/python3.7/lib-dynload"); + succeeded = succeeded && InsertPythonLibraryPath(paths, pythonPackage, engineRoot, "python/runtime/%s/Python.framework/Versions/3.7/lib/python3.7"); + succeeded = succeeded && InsertPythonLibraryPath(paths, pythonPackage, engineRoot, "python/runtime/%s/Python.framework/Versions/3.7/lib/python3.7/site-packages"); + + return succeeded; + } + + AZStd::string GetPythonHomePath(const char* pythonPackage, const char* engineRoot) + { + // append lib path to Python paths + AZ::IO::FixedMaxPath libPath = engineRoot; + libPath /= AZ::IO::FixedMaxPathString::format("python/runtime/%s/Python.framework/Versions/3.7", pythonPackage); + libPath = libPath.LexicallyNormal(); + return libPath.String(); + } +} diff --git a/Code/Tools/ProjectManager/Platform/Windows/PAL_windows.cmake b/Code/Tools/ProjectManager/Platform/Windows/PAL_windows.cmake index 4d5680a30d..dfcc107f4d 100644 --- a/Code/Tools/ProjectManager/Platform/Windows/PAL_windows.cmake +++ b/Code/Tools/ProjectManager/Platform/Windows/PAL_windows.cmake @@ -8,3 +8,8 @@ # 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(LY_COMPILE_DEFINITIONS + PRIVATE + HAVE_ROUND # defined for Windows since http://p-nand-q.com/python/building-python-33-with-vs2013.html +) diff --git a/Code/Tools/ProjectManager/Platform/Windows/PAL_windows_files.cmake b/Code/Tools/ProjectManager/Platform/Windows/PAL_windows_files.cmake new file mode 100644 index 0000000000..de083bc91a --- /dev/null +++ b/Code/Tools/ProjectManager/Platform/Windows/PAL_windows_files.cmake @@ -0,0 +1,14 @@ +# +# 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 + Python_windows.cpp +) diff --git a/Code/Tools/ProjectManager/Platform/Windows/Python_windows.cpp b/Code/Tools/ProjectManager/Platform/Windows/Python_windows.cpp new file mode 100644 index 0000000000..2ea143c63d --- /dev/null +++ b/Code/Tools/ProjectManager/Platform/Windows/Python_windows.cpp @@ -0,0 +1,43 @@ +/* + * 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 + +namespace Platform +{ + extern bool InsertPythonLibraryPath(AZStd::unordered_set& paths, const char* pythonPackage, const char* engineRoot, const char* subPath); + + bool InsertPythonBinaryLibraryPaths(AZStd::unordered_set& paths, const char* pythonPackage, const char* engineRoot) + { + bool succeeded = true; + + succeeded = succeeded && InsertPythonLibraryPath(paths, pythonPackage, engineRoot, "python/runtime/%s/python"); + succeeded = succeeded && InsertPythonLibraryPath(paths, pythonPackage, engineRoot, "python/runtime/%s/python/lib"); + succeeded = succeeded && InsertPythonLibraryPath(paths, pythonPackage, engineRoot, "python/runtime/%s/python/lib/site-packages"); + succeeded = succeeded && InsertPythonLibraryPath(paths, pythonPackage, engineRoot, "python/runtime/%s/python/DLLs"); + + return succeeded; + } + + AZStd::string GetPythonHomePath(const char* pythonPackage, const char* engineRoot) + { + // append lib path to Python paths + AZ::IO::FixedMaxPath libPath = engineRoot; + libPath /= AZ::IO::FixedMaxPathString::format("python/runtime/%s/python", pythonPackage); + libPath = libPath.LexicallyNormal(); + return libPath.String(); + } +} diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.h index 8c5040eb84..4766187d2a 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemInfo.h @@ -37,6 +37,7 @@ namespace O3DE::ProjectManager GemInfo(const QString& name, const QString& creator, const QString& summary, Platforms platforms, bool isAdded); + QString m_path; QString m_name; QString m_displayName; AZ::Uuid m_uuid; diff --git a/Code/Tools/ProjectManager/Source/ProjectInfo.cpp b/Code/Tools/ProjectManager/Source/ProjectInfo.cpp new file mode 100644 index 0000000000..b3bdb87224 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/ProjectInfo.cpp @@ -0,0 +1,24 @@ +/* +* 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 "ProjectInfo.h" + +namespace O3DE::ProjectManager +{ + ProjectInfo::ProjectInfo(const QString& path, const QString& projectName, const QString& productName, const AZ::Uuid projectId) + : m_path(path) + , m_projectName(projectName) + , m_productName(productName) + , m_projectId(projectId) + { + } +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectInfo.h b/Code/Tools/ProjectManager/Source/ProjectInfo.h new file mode 100644 index 0000000000..e5dca97d5e --- /dev/null +++ b/Code/Tools/ProjectManager/Source/ProjectInfo.h @@ -0,0 +1,36 @@ +/* +* 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 +#endif + +namespace O3DE::ProjectManager +{ + class ProjectInfo + { + public: + ProjectInfo() = default; + ProjectInfo(const QString& path, const QString& projectName, const QString& productName, const AZ::Uuid projectId); + + // from o3de_manifest.json and o3de_projects.json + QString m_path; + + // from project.json + QString m_projectName; + QString m_productName; + AZ::Uuid m_projectId; + }; +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp index 12980fc836..c86ebeee86 100644 --- a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.cpp @@ -28,6 +28,8 @@ namespace O3DE::ProjectManager { m_ui->setupUi(this); + m_pythonBindings = AZStd::make_unique(engineRootPath); + ConnectSlotsAndSignals(); QDir rootDir = QString::fromUtf8(engineRootPath.Native().data(), aznumeric_cast(engineRootPath.Native().size())); @@ -44,6 +46,7 @@ namespace O3DE::ProjectManager ProjectManagerWindow::~ProjectManagerWindow() { + m_pythonBindings.reset(); } void ProjectManagerWindow::BuildScreens() diff --git a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.h b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.h index 9e5761fbd2..6a17c4464c 100644 --- a/Code/Tools/ProjectManager/Source/ProjectManagerWindow.h +++ b/Code/Tools/ProjectManager/Source/ProjectManagerWindow.h @@ -17,7 +17,7 @@ #include #include -#include +#include #endif namespace Ui @@ -52,6 +52,7 @@ namespace O3DE::ProjectManager private: QScopedPointer m_ui; + AZStd::unique_ptr m_pythonBindings; }; } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/ProjectsHome.cpp b/Code/Tools/ProjectManager/Source/ProjectsHome.cpp index 1a451f3d10..a45b923946 100644 --- a/Code/Tools/ProjectManager/Source/ProjectsHome.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectsHome.cpp @@ -14,6 +14,8 @@ #include +#include + namespace O3DE::ProjectManager { ProjectsHome::ProjectsHome(ProjectManagerWindow* window) @@ -23,6 +25,9 @@ namespace O3DE::ProjectManager m_ui->setupUi(this); ConnectSlotsAndSignals(); + + // example of how to get the current project name + ProjectInfo currentProject = PythonBindingsInterface::Get()->GetCurrentProject(); } ProjectsHome::~ProjectsHome() diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.cpp b/Code/Tools/ProjectManager/Source/PythonBindings.cpp new file mode 100644 index 0000000000..cc14e9e4de --- /dev/null +++ b/Code/Tools/ProjectManager/Source/PythonBindings.cpp @@ -0,0 +1,155 @@ +/* + * 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 + +// Qt defines slots, which interferes with the use here. +#pragma push_macro("slots") +#undef slots +#include +#include +#include +#include +#include +#pragma pop_macro("slots") + +#include +#include +#include +#include + +namespace Platform +{ + bool InsertPythonLibraryPath( + AZStd::unordered_set& paths, const char* pythonPackage, const char* engineRoot, const char* subPath) + { + // append lib path to Python paths + AZ::IO::FixedMaxPath libPath = engineRoot; + libPath /= AZ::IO::FixedMaxPathString::format(subPath, pythonPackage); + libPath = libPath.LexicallyNormal(); + if (AZ::IO::SystemFile::Exists(libPath.c_str())) + { + paths.insert(libPath.c_str()); + return true; + } + + AZ_Warning("python", false, "Python library path should exist. path:%s", libPath.c_str()); + return false; + } + + // Implemented in each different platform's PAL implentation files, as it differs per platform. + AZStd::string GetPythonHomePath(const char* pythonPackage, const char* engineRoot); + +} // namespace Platform + +namespace O3DE::ProjectManager +{ + PythonBindings::PythonBindings(const AZ::IO::PathView& enginePath) + : m_enginePath(enginePath) + { + StartPython(); + } + + PythonBindings::~PythonBindings() + { + StopPython(); + } + + bool PythonBindings::StartPython() + { + if (Py_IsInitialized()) + { + AZ_Warning("python", false, "Python is already active"); + return false; + } + + // set PYTHON_HOME + AZStd::string pyBasePath = Platform::GetPythonHomePath(PY_PACKAGE, m_enginePath.c_str()); + if (!AZ::IO::SystemFile::Exists(pyBasePath.c_str())) + { + AZ_Warning("python", false, "Python home path must exist. path:%s", pyBasePath.c_str()); + return false; + } + + AZStd::wstring pyHomePath; + AZStd::to_wstring(pyHomePath, pyBasePath); + Py_SetPythonHome(pyHomePath.c_str()); + + // display basic Python information + AZ_TracePrintf("python", "Py_GetVersion=%s \n", Py_GetVersion()); + AZ_TracePrintf("python", "Py_GetPath=%ls \n", Py_GetPath()); + AZ_TracePrintf("python", "Py_GetExecPrefix=%ls \n", Py_GetExecPrefix()); + AZ_TracePrintf("python", "Py_GetProgramFullPath=%ls \n", Py_GetProgramFullPath()); + + try + { + // ignore system location for sites site-packages + Py_IsolatedFlag = 1; // -I - Also sets Py_NoUserSiteDirectory. If removed PyNoUserSiteDirectory should be set. + Py_IgnoreEnvironmentFlag = 1; // -E + + const bool initializeSignalHandlers = true; + pybind11::initialize_interpreter(initializeSignalHandlers); + + // Acquire GIL before calling Python code + AZStd::lock_guard lock(m_lock); + pybind11::gil_scoped_acquire acquire; + + // Setup sys.path + int result = PyRun_SimpleString("import sys"); + AZ_Warning("ProjectManagerWindow", result != -1, "Import sys failed"); + result = PyRun_SimpleString(AZStd::string::format("sys.path.append('%s')", m_enginePath.c_str()).c_str()); + AZ_Warning("ProjectManagerWindow", result != -1, "Append to sys path failed"); + + return result == 0 && !PyErr_Occurred(); + } catch ([[maybe_unused]] const std::exception& e) + { + AZ_Warning("python", false, "Py_Initialize() failed with %s", e.what()); + return false; + } + } + + bool PythonBindings::StopPython() + { + if (Py_IsInitialized()) + { + pybind11::finalize_interpreter(); + } + else + { + AZ_Warning("python", false, "Did not finalize since Py_IsInitialized() was false"); + } + return !PyErr_Occurred(); + } + + void PythonBindings::ExecuteWithLock(AZStd::function executionCallback) + { + AZStd::lock_guard lock(m_lock); + pybind11::gil_scoped_release release; + pybind11::gil_scoped_acquire acquire; + executionCallback(); + } + + ProjectInfo PythonBindings::GetCurrentProject() + { + ProjectInfo project; + + ExecuteWithLock([&] { + auto currentProjectTool = pybind11::module::import("cmake.Tools.current_project"); + auto getCurrentProject = currentProjectTool.attr("get_current_project"); + auto currentProject = getCurrentProject(m_enginePath.c_str()); + + project.m_path = currentProject.cast().c_str(); + }); + + return project; + } +} diff --git a/Code/Tools/ProjectManager/Source/PythonBindings.h b/Code/Tools/ProjectManager/Source/PythonBindings.h new file mode 100644 index 0000000000..ac55fffe80 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/PythonBindings.h @@ -0,0 +1,41 @@ +/* + * 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 + +namespace O3DE::ProjectManager +{ + class PythonBindings + : public PythonBindingsInterface::Registrar + { + public: + PythonBindings() = default; + PythonBindings(const AZ::IO::PathView& enginePath); + ~PythonBindings() override; + + // PythonBindings overrides + ProjectInfo GetCurrentProject() override; + + private: + AZ_DISABLE_COPY_MOVE(PythonBindings); + + void ExecuteWithLock(AZStd::function executionCallback); + bool StartPython(); + bool StopPython(); + + AZ::IO::FixedMaxPath m_enginePath; + AZStd::recursive_mutex m_lock; + }; +} diff --git a/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h b/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h new file mode 100644 index 0000000000..78c3625415 --- /dev/null +++ b/Code/Tools/ProjectManager/Source/PythonBindingsInterface.h @@ -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. + * + */ +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace O3DE::ProjectManager +{ + //! Interface used to interact with the o3de cli python functions + class IPythonBindings + { + public: + AZ_RTTI(O3DE::ProjectManager::IPythonBindings, "{C2B72CA4-56A9-4601-A584-3B40E83AA17C}"); + AZ_DISABLE_COPY_MOVE(IPythonBindings); + + IPythonBindings() = default; + virtual ~IPythonBindings() = default; + + //! Get the current project + virtual ProjectInfo GetCurrentProject() = 0; + }; + + using PythonBindingsInterface = AZ::Interface; +} // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/main.cpp b/Code/Tools/ProjectManager/Source/main.cpp index 149da79491..3d8bb71a0c 100644 --- a/Code/Tools/ProjectManager/Source/main.cpp +++ b/Code/Tools/ProjectManager/Source/main.cpp @@ -35,21 +35,29 @@ int main(int argc, char* argv[]) QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); AzQtComponents::Utilities::HandleDpiAwareness(AzQtComponents::Utilities::SystemDpiAware); - QApplication app(argc, argv); - // Need to use settings registry to get EngineRootFolder - AZ::IO::FixedMaxPath engineRootPath; + AZ::AllocatorInstance::Create(); + int runSuccess = 0; { - AZ::ComponentApplication componentApplication; - auto settingsRegistry = AZ::SettingsRegistry::Get(); - settingsRegistry->Get(engineRootPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder); - } + QApplication app(argc, argv); + + // Need to use settings registry to get EngineRootFolder + AZ::IO::FixedMaxPath engineRootPath; + { + AZ::ComponentApplication componentApplication; + auto settingsRegistry = AZ::SettingsRegistry::Get(); + settingsRegistry->Get(engineRootPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder); + } - AzQtComponents::StyleManager styleManager(&app); - styleManager.initialize(&app, engineRootPath); + AzQtComponents::StyleManager styleManager(&app); + styleManager.initialize(&app, engineRootPath); - O3DE::ProjectManager::ProjectManagerWindow window(nullptr, engineRootPath); - window.show(); + O3DE::ProjectManager::ProjectManagerWindow window(nullptr, engineRootPath); + window.show(); + + runSuccess = app.exec(); + } + AZ::AllocatorInstance::Destroy(); - return app.exec(); + return runSuccess; } diff --git a/Code/Tools/ProjectManager/project_manager_files.cmake b/Code/Tools/ProjectManager/project_manager_files.cmake index 073e220810..da0b7cdec7 100644 --- a/Code/Tools/ProjectManager/project_manager_files.cmake +++ b/Code/Tools/ProjectManager/project_manager_files.cmake @@ -19,9 +19,14 @@ set(FILES Source/FirstTimeUse.h Source/FirstTimeUse.cpp Source/FirstTimeUse.ui + Source/ProjectInfo.h + Source/ProjectInfo.cpp Source/ProjectManagerWindow.h Source/ProjectManagerWindow.cpp Source/ProjectManagerWindow.ui + Source/PythonBindings.h + Source/PythonBindings.cpp + Source/PythonBindingsInterface.h Source/NewProjectSettings.h Source/NewProjectSettings.cpp Source/NewProjectSettings.ui From 1cbcfa75e89de3f27e61eb19209f2be654e08ac0 Mon Sep 17 00:00:00 2001 From: Nicholas Lawson <70027408+lawsonamzn@users.noreply.github.com> Date: Tue, 11 May 2021 10:40:31 -0700 Subject: [PATCH 047/100] Fixes a crash on mac in the SourceFileRelocatorTest (#688) Note that this test should crash on windows too but its a read-beyond-the-edge-of-array memory issue which could be intermittent. --- .../native/AssetManager/SourceFileRelocator.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/Code/Tools/AssetProcessor/native/AssetManager/SourceFileRelocator.cpp b/Code/Tools/AssetProcessor/native/AssetManager/SourceFileRelocator.cpp index a242c6377c..49c7ef7f20 100644 --- a/Code/Tools/AssetProcessor/native/AssetManager/SourceFileRelocator.cpp +++ b/Code/Tools/AssetProcessor/native/AssetManager/SourceFileRelocator.cpp @@ -190,9 +190,8 @@ Please note that only those seed files will get updated that are active for your void SourceFileRelocator::HandleMetaDataFiles(QStringList pathMatches, QHash& sourceIndexMap, const ScanFolderInfo* scanFolderInfo, SourceFileRelocationContainer& metadataFiles, bool excludeMetaDataFiles) const { QSet metaDataFileEntries; - for (QStringList::Iterator fileIter = pathMatches.begin(); fileIter != pathMatches.end();) + for (QString file : pathMatches) { - QString file = *fileIter; for (int idx = 0; idx < m_platformConfig->MetaDataFileTypesCount(); idx++) { QPair metaInfo = m_platformConfig->GetMetaDataFileTypeAt(idx); @@ -203,8 +202,7 @@ Please note that only those seed files will get updated that are active for your { AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Metadata file %s will be ignored because --excludeMetadataFiles was specified in the command line.\n", file.toUtf8().constData()); - fileIter = pathMatches.erase(fileIter); - continue; + break; // don't check it against other metafile entries, we've already ascertained its a metafile. } else { @@ -263,8 +261,6 @@ Please note that only those seed files will get updated that are active for your } } } - - fileIter++; } } From 703f9deee0f01c0d00ff636ee8ce18d2c9a3646c Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Tue, 11 May 2021 12:43:30 -0500 Subject: [PATCH 048/100] Testing jenkins break --- Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt index 33873e0dfa..06b4e2a7fe 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt +++ b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt @@ -104,5 +104,14 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::ImguiAtom Gem::AtomFont Gem::AtomToolsFramework.Editor + + # Testing jenkins issue + Gem::Atom_RHI_Vulkan.Private + Gem::Atom_RHI_Vulkan.Builders + Gem::Atom_RHI_DX12.Private + Gem::Atom_RHI_DX12.Builders + Gem::Atom_RHI_Null.Private + Gem::Atom_RHI_Null.Builders + Gem::Atom_RHI_Metal.Builders ) endif() From 9d244b6e2be08732922cd519b370894e44438c07 Mon Sep 17 00:00:00 2001 From: jckand-amzn Date: Tue, 11 May 2021 12:50:38 -0500 Subject: [PATCH 049/100] Removing test dependency from EditorTests --- AutomatedTesting/Gem/PythonTests/CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 11ee414b36..3124f1048a 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -366,7 +366,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_ Legacy::Editor AZ::AssetProcessor AutomatedTesting.Assets - 3rdParty::Qt::Test COMPONENT Editor ) From 4a5d7730347d09e8c21833a4089f7ae6391ab12f Mon Sep 17 00:00:00 2001 From: Terry Michaels <81711813+tjmichaels@users.noreply.github.com> Date: Tue, 11 May 2021 12:55:00 -0500 Subject: [PATCH 050/100] Removed environment and debug mode buttons --- Code/Sandbox/Editor/MainWindow.cpp | 133 ------------------------- Code/Sandbox/Editor/MainWindow.h | 5 - Code/Sandbox/Editor/ToolbarManager.cpp | 4 - 3 files changed, 142 deletions(-) diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index b1d85c2999..e9b27ee9b8 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -695,8 +695,6 @@ void MainWindow::InitActions() am->AddAction(ID_TOOLBAR_WIDGET_REDO, QString()); am->AddAction(ID_TOOLBAR_WIDGET_SNAP_ANGLE, QString()); am->AddAction(ID_TOOLBAR_WIDGET_SNAP_GRID, QString()); - am->AddAction(ID_TOOLBAR_WIDGET_ENVIRONMENT_MODE, QString()); - am->AddAction(ID_TOOLBAR_WIDGET_DEBUG_MODE, QString()); am->AddAction(ID_TOOLBAR_WIDGET_SPACER_RIGHT, QString()); // File actions @@ -1253,44 +1251,6 @@ QToolButton* MainWindow::CreateUndoRedoButton(int command) return button; } -QToolButton* MainWindow::CreateEnvironmentModeButton() -{ - QToolButton* environmentModeButton = new QToolButton(this); - environmentModeButton->setAutoRaise(true); - environmentModeButton->setPopupMode(QToolButton::InstantPopup); - environmentModeButton->setIcon(Style::icon("Environment")); - environmentModeButton->setStatusTip(tr("Select from a variety of environment mode options")); - environmentModeButton->setToolTip(tr("Environment modes")); - - CVarMenu* environmentModeMenu = new CVarMenu(this); - connect(environmentModeMenu, &QMenu::aboutToShow, [this, environmentModeMenu]() - { - InitEnvironmentModeMenu(environmentModeMenu); - }); - environmentModeButton->setMenu(environmentModeMenu); - - return environmentModeButton; -} - -QToolButton* MainWindow::CreateDebugModeButton() -{ - QToolButton* debugModeButton = new QToolButton(this); - debugModeButton->setAutoRaise(true); - debugModeButton->setPopupMode(QToolButton::InstantPopup); - debugModeButton->setIcon(Style::icon("Debugging")); - debugModeButton->setStatusTip(tr("Select from a variety of debug/view mode options")); - debugModeButton->setToolTip(tr("Debug modes")); - - CVarMenu* debugModeMenu = new CVarMenu(this); - connect(debugModeMenu, &QMenu::aboutToShow, [this, debugModeMenu]() - { - InitDebugModeMenu(debugModeMenu); - }); - debugModeButton->setMenu(debugModeMenu); - - return debugModeButton; -} - QWidget* MainWindow::CreateSpacerRightWidget() { QWidget* spacer = new QWidget(this); @@ -1299,93 +1259,6 @@ QWidget* MainWindow::CreateSpacerRightWidget() return spacer; } -void MainWindow::InitEnvironmentModeMenu(CVarMenu* environmentModeMenu) -{ - environmentModeMenu->clear(); - environmentModeMenu->AddCVarToggleItem({ "e_Fog", tr("Hide Global Fog"), 0, 1 }); - environmentModeMenu->AddCVarToggleItem({ "r_FogVolumes", tr("Hide Fog Volumes"), 0, 1 }); - environmentModeMenu->AddCVarToggleItem({ "e_Clouds", tr("Hide Clouds"), 0, 1 }); - environmentModeMenu->AddCVarToggleItem({ "e_Wind", tr("Hide Wind"), 0, 1 }); - environmentModeMenu->AddSeparator(); - environmentModeMenu->AddCVarToggleItem({ "e_Sun", tr("Hide Sun"), 0, 1 }); - environmentModeMenu->AddCVarToggleItem({ "e_Skybox", tr("Hide Skybox"), 0, 1 }); - environmentModeMenu->AddCVarToggleItem({ "r_SSReflections", tr("Hide Screen Space Reflection"), 0, 1 }); - environmentModeMenu->AddCVarToggleItem({ "e_Shadows", tr("Hide Shadows"), 0, 1 }); - environmentModeMenu->AddCVarToggleItem({ "r_TransparentPasses", tr("Hide Transparent Objects"), 0, 1 }); - 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->AddCVarToggleItem({ "e_Entities", tr("Hide Entities"), 0, 1 }); - environmentModeMenu->AddSeparator(); - environmentModeMenu->AddCVarToggleItem({ "e_Vegetation", tr("Hide Vegetation"), 0, 1 }); - environmentModeMenu->AddCVarToggleItem({ "e_Terrain", tr("Hide Terrain"), 0, 1 }); - environmentModeMenu->AddSeparator(); - environmentModeMenu->AddCVarToggleItem({ "e_Particles", tr("Hide Particles"), 0, 1 }); - environmentModeMenu->AddCVarToggleItem({ "e_Flares", tr("Hide Flares"), 0, 1 }); - environmentModeMenu->AddCVarToggleItem({ "e_Decals", tr("Hide Decals"), 0, 1 }); - environmentModeMenu->AddSeparator(); - environmentModeMenu->AddCVarToggleItem({ "e_WaterOcean", tr("Hide Ocean Water (for legacy)"), 0, 1 }); - environmentModeMenu->AddCVarToggleItem({ "e_WaterVolumes", tr("Hide Water Volumes"), 0, 1 }); - environmentModeMenu->AddSeparator(); - environmentModeMenu->AddCVarToggleItem({ "e_BBoxes", tr("Hide BBoxes"), 0, 1 }); - environmentModeMenu->AddSeparator(); - environmentModeMenu->AddResetCVarsItem(); -} - -void MainWindow::InitDebugModeMenu(CVarMenu* debugModeMenu) -{ - debugModeMenu->clear(); - debugModeMenu->AddCVarValuesItem("r_DebugGBuffer", tr("GBuffers"), - { - {tr("Full Shading Mode (Default)"), 0}, - {tr("Normal Visualization"), 1}, - {tr("Smoothness"), 2}, - {tr("Reflectance"), 3}, - {tr("Albedo"), 4}, - {tr("Lighting Model"), 5}, - {tr("Translucency"), 6}, - {tr("Sun Self Shadowing"), 7}, - {tr("Subsurface Scattering"), 8}, - {tr("Specular Validation Overlay"), 9} - }, 0); - debugModeMenu->AddSeparator(); - debugModeMenu->AddCVarValuesItem("r_Stats", tr("Profiling"), - { - {tr("Frame Timing"), 1}, - {tr("Object Timing"), 3}, - {tr("Instance Draw Calls"), 6}, - }, 0); - debugModeMenu->AddSeparator(); - debugModeMenu->AddUniqueCVarsItem(tr("Wireframe"), - { - {"r_wireframe", tr("Wireframe Rendering Mode"), 1, 0}, - {"r_showlines", tr("Wireframe Overlay"), 1, 0} - }), - debugModeMenu->AddCVarValuesItem("e_debugdraw", tr("Art Info"), - { - {tr("Texture Memory Usage"), 4}, - {tr("Renderable Material Count"), 5}, - {tr("LOD Vertex Count"), 22} - }, 0); - - debugModeMenu->AddSeparator(); - debugModeMenu->AddCVarValuesItem("e_defaultmaterial", tr("Default Material on all Objects"), - { - {tr("Gray Material with Normal Maps"), 1}, - }, 0); - - debugModeMenu->AddCVarValuesItem("r_DeferredShadingTiledDebugAlbedo", tr("Debug Visualization of Deferred Lighting"), - { - {tr("White Albedo"), 1}, - }, 0); - - debugModeMenu->AddCVarToggleItem({ "r_ShowTangents", tr("Show Tangents"), 1, 0 }); - debugModeMenu->AddCVarToggleItem({ "p_draw_helpers", tr("Show Collision Shapes (Proxy)"), 1, 0 }); - - debugModeMenu->AddSeparator(); - debugModeMenu->AddResetCVarsItem(); -} - UndoRedoToolButton::UndoRedoToolButton(QWidget* parent) : QToolButton(parent) { @@ -2150,12 +2023,6 @@ QWidget* MainWindow::CreateToolbarWidget(int actionId) case ID_TOOLBAR_WIDGET_SNAP_ANGLE: w = CreateSnapToAngleWidget(); break; - case ID_TOOLBAR_WIDGET_ENVIRONMENT_MODE: - w = CreateEnvironmentModeButton(); - break; - case ID_TOOLBAR_WIDGET_DEBUG_MODE: - w = CreateDebugModeButton(); - break; case ID_TOOLBAR_WIDGET_SPACER_RIGHT: w = CreateSpacerRightWidget(); break; diff --git a/Code/Sandbox/Editor/MainWindow.h b/Code/Sandbox/Editor/MainWindow.h index ca8cc11677..ab60b0e0d4 100644 --- a/Code/Sandbox/Editor/MainWindow.h +++ b/Code/Sandbox/Editor/MainWindow.h @@ -208,11 +208,6 @@ private: QToolButton* CreateUndoRedoButton(int command); - QToolButton* CreateEnvironmentModeButton(); - QToolButton* CreateDebugModeButton(); - void InitEnvironmentModeMenu(CVarMenu* environmentModeMenu); - void InitDebugModeMenu(CVarMenu* debugModeMenu); - private Q_SLOTS: void ShowKeyboardCustomization(); void ExportKeyboardShortcuts(); diff --git a/Code/Sandbox/Editor/ToolbarManager.cpp b/Code/Sandbox/Editor/ToolbarManager.cpp index bbb3ef6790..5aa039189d 100644 --- a/Code/Sandbox/Editor/ToolbarManager.cpp +++ b/Code/Sandbox/Editor/ToolbarManager.cpp @@ -595,10 +595,6 @@ AmazonToolbar ToolbarManager::GetEditModeToolbar() const t.AddAction(ID_TOOLBAR_WIDGET_SNAP_GRID, ORIGINAL_TOOLBAR_VERSION); t.AddAction(ID_TOOLBAR_WIDGET_SNAP_ANGLE, ORIGINAL_TOOLBAR_VERSION); - t.AddAction(ID_TOOLBAR_SEPARATOR, ORIGINAL_TOOLBAR_VERSION); - t.AddAction(ID_TOOLBAR_WIDGET_ENVIRONMENT_MODE, ORIGINAL_TOOLBAR_VERSION); - t.AddAction(ID_TOOLBAR_WIDGET_DEBUG_MODE, ORIGINAL_TOOLBAR_VERSION); - return t; } From b11234097d8cc4741ef3e786a6823966633eb8ae Mon Sep 17 00:00:00 2001 From: srikappa Date: Tue, 11 May 2021 11:30:16 -0700 Subject: [PATCH 051/100] Fixed a capitalization issue --- .../Prefab/Instance/InstanceToTemplatePropagator.cpp | 2 +- .../AzToolsFramework/Prefab/PrefabPublicHandler.cpp | 4 ++-- .../AzToolsFramework/Prefab/PrefabPublicHandler.h | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp index 6f812df89b..a21c5301aa 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp @@ -282,7 +282,7 @@ namespace AzToolsFramework /* If the original allocator the patches were created with gets destroyed, then the patches would become garbage in the linkDom. Since we cannot guarantee the lifecycle of the patch allocators, we are doing a copy of the patches here to - associate them with the linkDom's allocator. This is a limitation with rapidjson. + associate them with the linkDom's allocator. */ PrefabDom patchesCopy; patchesCopy.CopyFrom(patches, linkDom.GetAllocator()); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index fee455b710..02fa2d14fc 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -295,7 +295,7 @@ namespace AzToolsFramework void PrefabPublicHandler::CreateLink( const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId, - UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool IsUndoRedoSupportNeeded) + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool isUndoRedoSupportNeeded) { AZ::EntityId containerEntityId = sourceInstance.GetContainerEntityId(); AZ::Entity* containerEntity = GetEntityById(containerEntityId); @@ -322,7 +322,7 @@ namespace AzToolsFramework m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(patch, containerEntityId); LinkId linkId; - if (IsUndoRedoSupportNeeded) + if (isUndoRedoSupportNeeded) { linkId = PrefabUndoHelpers::CreateLink( sourceInstance.GetTemplateId(), targetTemplateId, AZStd::move(patch), sourceInstance.GetInstanceAlias(), undoBatch); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 31937cf028..138bc84aa0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -77,11 +77,11 @@ namespace AzToolsFramework * \param targetInstance The id of the target template. * \param undoBatch The undo batch to set as parent for this create link action. * \param commonRootEntityId The id of the entity that the source instance should be parented under. - * \param IsUndoRedoSupportNeeded The flag indicating whether the link should be created with undo/redo support or not. + * \param isUndoRedoSupportNeeded The flag indicating whether the link should be created with undo/redo support or not. */ void CreateLink( const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId, - UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool IsUndoRedoSupportNeeded = true); + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool isUndoRedoSupportNeeded = true); /** * Removes the link between template of the sourceInstance and the template corresponding to targetTemplateId. From 6b72646b614b0daafd0f926b38e336cf177f52b9 Mon Sep 17 00:00:00 2001 From: sconel Date: Tue, 11 May 2021 11:42:35 -0700 Subject: [PATCH 052/100] Updated PrefabBuilder to not error when prefabs are present at end --- .../PrefabBuilder/PrefabBuilderComponent.cpp | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp b/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp index 2b97b8a63d..a95ec60d61 100644 --- a/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp +++ b/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp @@ -261,21 +261,15 @@ namespace AZ::Prefab if (context.HasCompletedSuccessfully()) { AZ_TracePrintf("Prefab Builder", "Finalizing products.\n"); - if (!context.HasPrefabs()) + + if (StoreProducts(tempDirPath, context.GetProcessedObjects(), + context.GetRegisteredProductAssetDependencies(), jobProducts)) { - if (StoreProducts(tempDirPath, context.GetProcessedObjects(), - context.GetRegisteredProductAssetDependencies(), jobProducts)) - { - return true; - } - else - { - AZ_Error("Prefab Builder", false, "One or more objects couldn't be committed to disk."); - } + return true; } else { - AZ_Error("Prefab Builder", false, "After processing there were still Prefabs left."); + AZ_Error("Prefab Builder", false, "One or more objects couldn't be committed to disk."); } } else From 4d8ed6c0cb09b2abe43b01eea5003ab989377c6a Mon Sep 17 00:00:00 2001 From: zsolleci Date: Tue, 11 May 2021 14:19:45 -0500 Subject: [PATCH 053/100] T92563569 completed and suite updated --- .../scripting/Node_HappyPath_DuplicateNode.py | 116 ++++++++++++++++++ .../PythonTests/scripting/TestSuite_Active.py | 10 +- 2 files changed, 123 insertions(+), 3 deletions(-) create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py b/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py new file mode 100644 index 0000000000..9d8cccd027 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.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. +""" + + +# fmt: off +class Tests(): + open_sc_window = ("Script Canvas window is opened", "Failed to open Script Canvas window") + node_added = ("Successfully added node to graph", "Failed to add node to graph") + node_duplicated = ("Successfully duplicated node", "Failed to duplicate the node") +# fmt: on + + +def Node_HappyPath_DuplicateNode(): + """ + Summary: + Duplicating node in graph + + Expected Behavior: + Upon selecting a node and pressing Ctrl+D, the node will be duplicated + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Open a new graph + 3) Add node to graph + 4) Select node in graph to verify existence + 5) Mock Ctrl+D to duplicate node + 6) Verify the node was duplicated + + 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, QtTest + from PySide2.QtCore import Qt + + 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 + + import azlmbr.legacy.general as general + + WAIT_FRAMES = 200 + + NODE_NAME = "Print" + NODE_CATEGORY = "Debug" + EXPECTED_STRING = f"{NODE_NAME} - {NODE_CATEGORY} (2 Selected)" + + def command_line_input(command_str): + cmd_action = pyside_utils.find_child_by_pattern( + sc_main, {"objectName": "action_ViewCommandLine", "type": QtWidgets.QAction} + ) + cmd_action.trigger() + textbox = sc.findChild(QtWidgets.QLineEdit, "commandText") + QtTest.QTest.keyClicks(textbox, command_str) + QtTest.QTest.keyClick(textbox, Qt.Key_Enter, Qt.NoModifier) + + def grab_title_text(): + scroll_area = node_inspector.findChild(QtWidgets.QScrollArea, "") + QtTest.QTest.keyClick(graph, "a", Qt.ControlModifier, WAIT_FRAMES) + general.idle_wait(1.0) + background = scroll_area.findChild(QtWidgets.QFrame, "Background") + title = background.findChild(QtWidgets.QLabel, "Title") + text = title.findChild(QtWidgets.QLabel, "Title") + print(text.text()) + return text.text() + + # 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) Open a new graph + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + sc_main = sc.findChild(QtWidgets.QMainWindow) + create_new_graph = pyside_utils.find_child_by_pattern( + sc_main, {"objectName": "action_New_Script", "type": QtWidgets.QAction} + ) + node_inspector = sc.findChild(QtWidgets.QDockWidget, "NodeInspector") + create_new_graph.trigger() + + # 3) Add node + command_line_input("add_node Print") + + # 4) Select node in graph to verify existence + graph_view = sc.findChild(QtWidgets.QFrame, "graphicsViewFrame") + graph = graph_view.findChild(QtWidgets.QWidget, "") + + # 5) Duplicate node + sc_main.activateWindow() + QtTest.QTest.keyClick(graph, "a", Qt.ControlModifier, WAIT_FRAMES) + QtTest.QTest.keyClick(graph, "d", Qt.ControlModifier, WAIT_FRAMES) + + # 6) Verify the node was duplicated + after_dup = grab_title_text() + Report.result(Tests.node_duplicated, after_dup == EXPECTED_STRING) + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from editor_python_test_tools.utils import Report + + Report.start_test(Node_HappyPath_DuplicateNode) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py index dda75f0a0c..2cd41d1980 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py @@ -84,7 +84,7 @@ class TestAutomation(TestAutomationBase): 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 @@ -122,7 +122,7 @@ class TestAutomation(TestAutomationBase): 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 @@ -195,7 +195,7 @@ class TestAutomation(TestAutomationBase): def test_NodeCategory_ExpandOnClick(self, request, workspace, editor, launcher_platform): from . import NodeCategory_ExpandOnClick as test_module self._run_test(request, workspace, editor, test_module) - + def test_NodePalette_SearchText_Deletion(self, request, workspace, editor, launcher_platform): from . import NodePalette_SearchText_Deletion as test_module self._run_test(request, workspace, editor, test_module) @@ -204,6 +204,10 @@ class TestAutomation(TestAutomationBase): from . import VariableManager_UnpinVariableType_Works as test_module self._run_test(request, workspace, editor, test_module) + def test_Node_HappyPath_DuplicateNode(self, request, workspace, editor, launcher_platform): + from . import Node_HappyPath_DuplicateNode 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 From 899d4c438d602f5379d504ac01d8da4a7cbe7e1e Mon Sep 17 00:00:00 2001 From: mbalfour Date: Tue, 11 May 2021 14:25:25 -0500 Subject: [PATCH 054/100] Move ThumbnailerNullComponent into AzToolsFramework so that it can be used by other tools that need it. SerializeContextTools will soon rely on this. --- .../AzToolsFramework/AzToolsFrameworkModule.cpp | 2 ++ .../Thumbnails}/ThumbnailerNullComponent.cpp | 6 +++--- .../Thumbnails}/ThumbnailerNullComponent.h | 8 ++++++-- .../AzToolsFramework/aztoolsframework_files.cmake | 2 ++ Code/Tools/Standalone/Source/LuaIDEApplication.cpp | 6 +++--- Code/Tools/Standalone/lua_ide_files.cmake | 2 -- 6 files changed, 16 insertions(+), 10 deletions(-) rename Code/{Tools/Standalone/Source => Framework/AzToolsFramework/AzToolsFramework/Thumbnails}/ThumbnailerNullComponent.cpp (95%) rename Code/{Tools/Standalone/Source => Framework/AzToolsFramework/AzToolsFramework/Thumbnails}/ThumbnailerNullComponent.h (89%) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFrameworkModule.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFrameworkModule.cpp index 373787e7dd..3a84c4249c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFrameworkModule.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFrameworkModule.cpp @@ -52,6 +52,7 @@ #include #include #include +#include #include #include @@ -91,6 +92,7 @@ namespace AzToolsFramework AzToolsFramework::AssetBundleComponent::CreateDescriptor(), AzToolsFramework::SliceDependencyBrowserComponent::CreateDescriptor(), AzToolsFramework::Thumbnailer::ThumbnailerComponent::CreateDescriptor(), + AzToolsFramework::Thumbnailer::ThumbnailerNullComponent::CreateDescriptor(), AzToolsFramework::AssetBrowser::AssetBrowserComponent::CreateDescriptor(), AzToolsFramework::EditorInteractionSystemComponent::CreateDescriptor(), AzToolsFramework::Components::EditorComponentAPIComponent::CreateDescriptor(), diff --git a/Code/Tools/Standalone/Source/ThumbnailerNullComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailerNullComponent.cpp similarity index 95% rename from Code/Tools/Standalone/Source/ThumbnailerNullComponent.cpp rename to Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailerNullComponent.cpp index e33cb8aa51..d156ae7c04 100644 --- a/Code/Tools/Standalone/Source/ThumbnailerNullComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailerNullComponent.cpp @@ -12,16 +12,16 @@ #include #include -#include "ThumbnailerNullComponent.h" +#include #include #include -namespace LUAEditor +namespace AzToolsFramework { namespace Thumbnailer { ThumbnailerNullComponent::ThumbnailerNullComponent() : - m_nullThumbnail(new AzToolsFramework::Thumbnailer::MissingThumbnail()) + m_nullThumbnail() { } diff --git a/Code/Tools/Standalone/Source/ThumbnailerNullComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailerNullComponent.h similarity index 89% rename from Code/Tools/Standalone/Source/ThumbnailerNullComponent.h rename to Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailerNullComponent.h index 9d0c638305..d8386235e5 100644 --- a/Code/Tools/Standalone/Source/ThumbnailerNullComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailerNullComponent.h @@ -15,7 +15,11 @@ #include #include -namespace LUAEditor +// ThumbnailerNullComponent is an alternative to ThumbnailerComponent that can be used by tools that don't use Qt. +// It doesn't do anything (hence "null"), but it allows the system and editor components that rely on the ThumbnailService +// to start up and function. + +namespace AzToolsFramework { namespace Thumbnailer { @@ -53,4 +57,4 @@ namespace LUAEditor AzToolsFramework::Thumbnailer::SharedThumbnail m_nullThumbnail; }; } // Thumbnailer -} // namespace LUAEditor +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake index a7fcf2e711..06f78ecdd3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake @@ -72,6 +72,8 @@ set(FILES AssetCatalog/PlatformAddressedAssetCatalogManager.cpp Thumbnails/ThumbnailerComponent.cpp Thumbnails/ThumbnailerComponent.h + Thumbnails/ThumbnailerNullComponent.cpp + Thumbnails/ThumbnailerNullComponent.h Thumbnails/LoadingThumbnail.cpp Thumbnails/LoadingThumbnail.h Thumbnails/MissingThumbnail.cpp diff --git a/Code/Tools/Standalone/Source/LuaIDEApplication.cpp b/Code/Tools/Standalone/Source/LuaIDEApplication.cpp index cd72fda4e3..8e52bb4d95 100644 --- a/Code/Tools/Standalone/Source/LuaIDEApplication.cpp +++ b/Code/Tools/Standalone/Source/LuaIDEApplication.cpp @@ -22,9 +22,9 @@ #include #include #include +#include #include -#include #include #include #include @@ -55,7 +55,7 @@ namespace LUAEditor RegisterComponentDescriptor(AzToolsFramework::Components::PropertyManagerComponent::CreateDescriptor()); RegisterComponentDescriptor(AzFramework::AssetSystem::AssetSystemComponent::CreateDescriptor()); RegisterComponentDescriptor(AzToolsFramework::AssetSystem::AssetSystemComponent::CreateDescriptor()); - RegisterComponentDescriptor(LUAEditor::Thumbnailer::ThumbnailerNullComponent::CreateDescriptor()); + RegisterComponentDescriptor(AzToolsFramework::Thumbnailer::ThumbnailerNullComponent::CreateDescriptor()); RegisterComponentDescriptor(AzToolsFramework::AssetBrowser::AssetBrowserComponent::CreateDescriptor()); RegisterComponentDescriptor(AzToolsFramework::Components::EditorSelectionAccentSystemComponent::CreateDescriptor()); @@ -75,7 +75,7 @@ namespace LUAEditor EnsureComponentCreated(AzToolsFramework::Components::PropertyManagerComponent::RTTI_Type()); EnsureComponentCreated(AzFramework::AssetSystem::AssetSystemComponent::RTTI_Type()); EnsureComponentCreated(AzToolsFramework::AssetSystem::AssetSystemComponent::RTTI_Type()); - EnsureComponentCreated(LUAEditor::Thumbnailer::ThumbnailerNullComponent::RTTI_Type()); + EnsureComponentCreated(AzToolsFramework::Thumbnailer::ThumbnailerNullComponent::RTTI_Type()); EnsureComponentCreated(AzToolsFramework::AssetBrowser::AssetBrowserComponent::RTTI_Type()); EnsureComponentCreated(AzToolsFramework::Components::EditorSelectionAccentSystemComponent::RTTI_Type()); } diff --git a/Code/Tools/Standalone/lua_ide_files.cmake b/Code/Tools/Standalone/lua_ide_files.cmake index c6e2c538f2..ff2196db62 100644 --- a/Code/Tools/Standalone/lua_ide_files.cmake +++ b/Code/Tools/Standalone/lua_ide_files.cmake @@ -14,8 +14,6 @@ set(FILES Source/LuaIDEApplication.cpp Source/AssetDatabaseLocationListener.h Source/AssetDatabaseLocationListener.cpp - Source/ThumbnailerNullComponent.h - Source/ThumbnailerNullComponent.cpp Source/Editor/LuaEditor.h Source/Editor/LuaEditor.cpp Source/LUA/BasicScriptChecker.h From c41ee23ea481c4b3977e708a6ed521ce58006fd9 Mon Sep 17 00:00:00 2001 From: mnaumov Date: Tue, 11 May 2021 12:40:37 -0700 Subject: [PATCH 055/100] PR feedback --- .../Types/EnhancedPBR_ForwardPass.azsl | 3 +-- .../Types/MaterialInputs/ParallaxInput.azsli | 17 +++++++++++++---- .../StandardMultilayerPBR_ForwardPass.azsl | 7 +++---- .../StandardMultilayerPBR_Shadowmap_WithPS.azsl | 6 +++--- .../Types/StandardPBR_ForwardPass.azsl | 7 +++---- .../Atom/Features/ParallaxMapping.azsli | 6 ++++-- 6 files changed, 27 insertions(+), 19 deletions(-) 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 34c57db974..f7926df818 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl @@ -150,7 +150,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float 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, displacementIsClipped); + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth, displacementIsClipped, IN.m_position.w); // 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]; @@ -163,7 +163,6 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float { DirectionalLightShadow::GetShadowCoords(shadowIndex, IN.m_worldPosition, IN.m_shadowCoords); } - IN.m_position.w = mul(ViewSrg::m_viewProjectionMatrix, IN.m_worldPosition).z; } } 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 ab601429e8..ffd7c18045 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli @@ -32,7 +32,7 @@ option bool prefix##o_useDepthMap; 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, out bool isClipped) + inout float2 uv, inout float3 worldPosition, inout float depthNDC, inout float depthCS, out bool isClipped) { if(o_parallax_feature_enabled) { @@ -72,7 +72,8 @@ void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float dep objectWorldMatrix, ViewSrg::m_viewProjectionMatrix); - depth = pdo.m_depth; + depthCS = pdo.m_depthCS; + depthNDC = pdo.m_depthNDC; worldPosition = pdo.m_worldPosition; } @@ -82,9 +83,17 @@ void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float dep 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 depthNDC, inout float depthCS) { bool isClipped; - GetParallaxInput(normal, tangent, bitangent, depthFactor, depthOffset, objectWorldMatrix, uvMatrix, uvMatrixInverse, uv, worldPosition, depth, isClipped); + GetParallaxInput(normal, tangent, bitangent, depthFactor, depthOffset, objectWorldMatrix, uvMatrix, uvMatrixInverse, uv, worldPosition, depthNDC, depthCS, isClipped); +} + +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 depthNDC) +{ + float depthCS; + GetParallaxInput(normal, tangent, bitangent, depthFactor, depthOffset, objectWorldMatrix, uvMatrix, uvMatrixInverse, uv, worldPosition, depthNDC, depthCS); } 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 9cc0047b72..bc32aa1370 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl @@ -130,9 +130,9 @@ VSOutput ForwardPassVS(VSInput IN) // ---------- Pixel Shader ---------- -PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float depth) +PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float depthNDC) { - depth = IN.m_position.z; + depthNDC = IN.m_position.z; // ------- Tangents & Bitangets ------- @@ -185,7 +185,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float 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, displacementIsClipped); + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depthNDC, IN.m_position.w, displacementIsClipped); // Adjust directional light shadow coorinates for parallax correction if(o_parallax_enablePixelDepthOffset) @@ -195,7 +195,6 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float { DirectionalLightShadow::GetShadowCoords(shadowIndex, IN.m_worldPosition, IN.m_shadowCoords); } - IN.m_position.w = mul(ViewSrg::m_viewProjectionMatrix, IN.m_worldPosition).z; } } 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 325937b228..c76dd15975 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 @@ -109,7 +109,7 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) GetDepth_Setup(IN.m_blendMask); - float depth; + float depthNDC; float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); @@ -118,9 +118,9 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) 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, depthNDC); - OUT.m_depth = depth; + OUT.m_depth = depthNDC; } 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 8621865f54..f362349a7b 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl @@ -105,7 +105,7 @@ VSOutput StandardPbr_ForwardPassVS(VSInput IN) // ---------- Pixel Shader ---------- -PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float depth) +PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float depthNDC) { // ------- Tangents & Bitangets ------- @@ -125,7 +125,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float // ------- Depth & Parallax ------- - depth = IN.m_position.z; + depthNDC = IN.m_position.z; bool displacementIsClipped = false; @@ -137,7 +137,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float 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, MaterialSrg::m_depthOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth, displacementIsClipped); + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depthNDC, IN.m_position.w, displacementIsClipped); // Adjust directional light shadow coorinates for parallax correction if(o_parallax_enablePixelDepthOffset) @@ -147,7 +147,6 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float { DirectionalLightShadow::GetShadowCoords(shadowIndex, IN.m_worldPosition, IN.m_shadowCoords); } - IN.m_position.w = mul(ViewSrg::m_viewProjectionMatrix, IN.m_worldPosition).z; } } 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 1d2beb0f10..8b1efc8eea 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli @@ -398,7 +398,8 @@ ParallaxOffset GetParallaxOffset( float depthFactor, struct PixelDepthOffset { - float m_depth; + float m_depthNDC; //!< The new depth value, in normalized device coordinates (used for final depth output) + float m_depthCS; //!< The new depth value, in clip space (can be used for other operations like light culling) float3 m_worldPosition; }; @@ -432,7 +433,8 @@ PixelDepthOffset CalcPixelDepthOffset( float depthFactor, float4 clipOffsetPosition = mul(viewProjectionMatrix, float4(worldOffsetPosition, 1.0)); PixelDepthOffset pdo; - pdo.m_depth = clipOffsetPosition.z / clipOffsetPosition.w; + pdo.m_depthCS = clipOffsetPosition.z; + pdo.m_depthNDC = clipOffsetPosition.z / clipOffsetPosition.w; pdo.m_worldPosition = worldOffsetPosition; return pdo; } From b4f7038d6aded8d6feb917518b536e100e41d41c Mon Sep 17 00:00:00 2001 From: mnaumov Date: Tue, 11 May 2021 12:42:37 -0700 Subject: [PATCH 056/100] param ordering --- .../Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 f7926df818..a91e88afad 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl @@ -150,7 +150,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float 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, displacementIsClipped, IN.m_position.w); + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth, IN.m_position.w, 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]; From 3e13dd52d18b33b1f5ba2f0c0c70323e26ad11a1 Mon Sep 17 00:00:00 2001 From: karlberg Date: Tue, 11 May 2021 12:47:15 -0700 Subject: [PATCH 057/100] First pass, removing gridmate touchpoints from AzFramework and non inclusive terminology purge --- .../AzFramework/Application/Application.cpp | 30 - .../AzFramework/Application/Application.h | 7 - .../AzFramework/AzFrameworkModule.cpp | 4 - .../Components/TransformComponent.cpp | 4 +- .../Components/TransformComponent.h | 10 +- .../DynamicSerializableFieldMarshaler.h | 146 -- .../AzFramework/Network/EntityIdMarshaler.h | 76 - .../Network/InterestManagerComponent.cpp | 187 --- .../Network/InterestManagerComponent.h | 120 -- .../AzFramework/Network/NetBindable.cpp | 111 -- .../AzFramework/Network/NetBindable.h | 799 --------- .../Network/NetBindingComponent.cpp | 287 ---- .../AzFramework/Network/NetBindingComponent.h | 85 - .../Network/NetBindingComponentChunk.cpp | 254 --- .../Network/NetBindingComponentChunk.h | 112 -- .../AzFramework/Network/NetBindingEventsBus.h | 51 - .../Network/NetBindingHandlerBus.h | 112 -- .../AzFramework/Network/NetBindingSystemBus.h | 119 -- .../Network/NetBindingSystemComponent.cpp | 66 - .../Network/NetBindingSystemComponent.h | 53 - .../Network/NetBindingSystemImpl.cpp | 957 ----------- .../Network/NetBindingSystemImpl.h | 311 ---- .../AzFramework/Network/NetSystemBus.h | 38 - .../AzFramework/Network/NetworkContext.cpp | 378 ----- .../AzFramework/Network/NetworkContext.h | 969 ----------- .../AzFramework/Script/ScriptComponent.cpp | 269 +--- .../AzFramework/Script/ScriptComponent.h | 19 +- .../AzFramework/Script/ScriptMarshal.cpp | 573 ------- .../AzFramework/Script/ScriptMarshal.h | 94 -- .../AzFramework/Script/ScriptNetBindings.cpp | 1427 ----------------- .../AzFramework/Script/ScriptNetBindings.h | 320 ---- .../TargetManagementComponent.cpp | 2 +- .../AzFramework/azframework_files.cmake | 24 - .../ToolsComponents/TransformComponent.cpp | 17 +- .../GridMate/Carrier/SecureSocketDriver.cpp | 2 +- .../Carrier/StreamSecureSocketDriver.cpp | 2 +- .../GridMate/GridMate/Replica/DataSet.cpp | 2 +- .../GridMate/GridMate/Replica/DataSet.h | 12 +- .../GridMate/Replica/DeltaCompressedDataSet.h | 4 +- .../Interest/BitmaskInterestHandler.cpp | 2 +- .../Replica/Interest/InterestManager.cpp | 2 +- .../Interest/ProximityInterestHandler.cpp | 2 +- .../GridMate/Replica/MigrationSequence.cpp | 4 +- .../GridMate/Replica/RemoteProcedureCall.h | 6 +- .../GridMate/GridMate/Replica/Replica.cpp | 4 +- .../GridMate/GridMate/Replica/Replica.h | 10 +- .../GridMate/Replica/ReplicaChunk.cpp | 18 +- .../GridMate/GridMate/Replica/ReplicaChunk.h | 10 +- .../GridMate/Replica/ReplicaDrillerEvents.h | 6 +- .../GridMate/GridMate/Replica/ReplicaMgr.cpp | 46 +- .../GridMate/GridMate/Replica/ReplicaMgr.h | 8 +- .../GridMate/GridMate/Replica/ReplicaStatus.h | 4 +- .../GridMate/Replica/SystemReplicas.cpp | 6 +- .../Replica/Tasks/ReplicaMarshalTasks.cpp | 2 +- .../Replica/Tasks/ReplicaUpdateTasks.h | 2 +- .../GridMate/GridMate/Session/Session.cpp | 14 +- Code/Framework/GridMate/Tests/Interest.cpp | 18 +- Code/Framework/GridMate/Tests/Replica.cpp | 190 +-- .../GridMate/Tests/ReplicaBehavior.cpp | 18 +- .../GridMate/Tests/ReplicaMedium.cpp | 210 +-- .../Framework/GridMate/Tests/ReplicaSmall.cpp | 12 +- Code/Framework/Tests/GridMocks.h | 58 - .../Tests/InterestManagerComponentTests.cpp | 151 -- Code/Framework/Tests/NetBinding.cpp | 600 ------- Code/Framework/Tests/NetBindingMocks.h | 335 ---- .../Tests/NetBindingSystemImplTest.cpp | 605 ------- Code/Framework/Tests/NetworkContext.cpp | 801 --------- Code/Framework/Tests/NetworkMarshal.cpp | 552 ------- .../Tests/Script/ScriptComponentTests.cpp | 62 - Code/Framework/Tests/TransformComponent.cpp | 31 - .../Tests/frameworktests_files.cmake | 6 - 71 files changed, 357 insertions(+), 11491 deletions(-) delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/DynamicSerializableFieldMarshaler.h delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/EntityIdMarshaler.h delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/InterestManagerComponent.cpp delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/InterestManagerComponent.h delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/NetBindable.cpp delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/NetBindable.h delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/NetBindingComponent.cpp delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/NetBindingComponent.h delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/NetBindingComponentChunk.cpp delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/NetBindingComponentChunk.h delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/NetBindingEventsBus.h delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/NetBindingHandlerBus.h delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemBus.h delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemComponent.cpp delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemComponent.h delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemImpl.cpp delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemImpl.h delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/NetSystemBus.h delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/NetworkContext.cpp delete mode 100644 Code/Framework/AzFramework/AzFramework/Network/NetworkContext.h delete mode 100644 Code/Framework/AzFramework/AzFramework/Script/ScriptMarshal.cpp delete mode 100644 Code/Framework/AzFramework/AzFramework/Script/ScriptMarshal.h delete mode 100644 Code/Framework/AzFramework/AzFramework/Script/ScriptNetBindings.cpp delete mode 100644 Code/Framework/AzFramework/AzFramework/Script/ScriptNetBindings.h delete mode 100644 Code/Framework/Tests/GridMocks.h delete mode 100644 Code/Framework/Tests/InterestManagerComponentTests.cpp delete mode 100644 Code/Framework/Tests/NetBinding.cpp delete mode 100644 Code/Framework/Tests/NetBindingMocks.h delete mode 100644 Code/Framework/Tests/NetBindingSystemImplTest.cpp delete mode 100644 Code/Framework/Tests/NetworkContext.cpp delete mode 100644 Code/Framework/Tests/NetworkMarshal.cpp diff --git a/Code/Framework/AzFramework/AzFramework/Application/Application.cpp b/Code/Framework/AzFramework/AzFramework/Application/Application.cpp index ba313812ce..dc6ae684cf 100644 --- a/Code/Framework/AzFramework/AzFramework/Application/Application.cpp +++ b/Code/Framework/AzFramework/AzFramework/Application/Application.cpp @@ -52,8 +52,6 @@ #include #include #include -#include -#include #include #include #include @@ -66,7 +64,6 @@ #include #include #include -#include #include #include #include @@ -197,7 +194,6 @@ namespace AzFramework ApplicationRequests::Bus::Handler::BusConnect(); AZ::UserSettingsFileLocatorBus::Handler::BusConnect(); - NetSystemRequestBus::Handler::BusConnect(); } Application::~Application() @@ -207,7 +203,6 @@ namespace AzFramework Stop(); } - NetSystemRequestBus::Handler::BusDisconnect(); AZ::UserSettingsFileLocatorBus::Handler::BusDisconnect(); ApplicationRequests::Bus::Handler::BusDisconnect(); @@ -285,13 +280,6 @@ namespace AzFramework m_pimpl.reset(); - /* The following line of code is a temporary fix. - * GridMate's ReplicaChunkDescriptor is stored in a global environment variable 'm_globalDescriptorTable' - * which does not get cleared when Application shuts down. We need to un-reflect here to clear ReplicaChunkDescriptor - * so that ReplicaChunkDescriptor::m_vdt doesn't get flooded when we repeatedly instantiate Application in unit tests. - */ - AZ::ReflectionEnvironment::GetReflectionManager()->RemoveReflectContext(); - // Free any memory owned by the command line container. m_commandLine = CommandLine(); @@ -320,8 +308,6 @@ namespace AzFramework azrtti_typeid(), azrtti_typeid(), azrtti_typeid(), - azrtti_typeid(), - azrtti_typeid(), azrtti_typeid(), azrtti_typeid(), azrtti_typeid(), @@ -457,9 +443,6 @@ namespace AzFramework void Application::CreateReflectionManager() { ComponentApplication::CreateReflectionManager(); - - // Setup NetworkContext - AZ::ReflectionEnvironment::GetReflectionManager()->AddReflectContext(); } //////////////////////////////////////////////////////////////////////////// @@ -479,19 +462,6 @@ namespace AzFramework return uuid; } - //////////////////////////////////////////////////////////////////////////// - NetworkContext* Application::GetNetworkContext() - { - NetworkContext* result = nullptr; - - if (auto reflectionManager = AZ::ReflectionEnvironment::GetReflectionManager()) - { - result = reflectionManager->GetReflectContext(); - } - - return result; - } - void Application::ResolveEnginePath(AZStd::string& engineRelativePath) const { AZ::IO::FixedMaxPath fullPath = m_engineRoot / engineRelativePath; diff --git a/Code/Framework/AzFramework/AzFramework/Application/Application.h b/Code/Framework/AzFramework/AzFramework/Application/Application.h index 4d7e45a423..6b1283be34 100644 --- a/Code/Framework/AzFramework/AzFramework/Application/Application.h +++ b/Code/Framework/AzFramework/AzFramework/Application/Application.h @@ -21,7 +21,6 @@ #include #include -#include #include #include @@ -49,7 +48,6 @@ namespace AzFramework : public AZ::ComponentApplication , public AZ::UserSettingsFileLocatorBus::Handler , public ApplicationRequests::Bus::Handler - , public NetSystemRequestBus::Handler { public: // Base class for platform specific implementations of the application. @@ -138,11 +136,6 @@ namespace AzFramework // Convenience function that should be called instead of the standard exit() function to ensure platform requirements are met. static void Exit(int errorCode) { ApplicationRequests::Bus::Broadcast(&ApplicationRequests::TerminateOnError, errorCode); } - ////////////////////////////////////////////////////////////////////////// - //! NetSystemEventBus::Handler - ////////////////////////////////////////////////////////////////////////// - NetworkContext* GetNetworkContext() override; - protected: /** diff --git a/Code/Framework/AzFramework/AzFramework/AzFrameworkModule.cpp b/Code/Framework/AzFramework/AzFramework/AzFrameworkModule.cpp index 644a7d099d..d1e4b4977a 100644 --- a/Code/Framework/AzFramework/AzFramework/AzFrameworkModule.cpp +++ b/Code/Framework/AzFramework/AzFramework/AzFrameworkModule.cpp @@ -22,8 +22,6 @@ #include #include #include -#include -#include #include #include #include @@ -42,8 +40,6 @@ namespace AzFramework AzFramework::AssetCatalogComponent::CreateDescriptor(), AzFramework::CustomAssetTypeComponent::CreateDescriptor(), AzFramework::FileTag::ExcludeFileComponent::CreateDescriptor(), - AzFramework::NetBindingComponent::CreateDescriptor(), - AzFramework::NetBindingSystemComponent::CreateDescriptor(), AzFramework::TransformComponent::CreateDescriptor(), AzFramework::NonUniformScaleComponent::CreateDescriptor(), AzFramework::GameEntityContextComponent::CreateDescriptor(), diff --git a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp index 5605fe567c..284df15eb9 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp @@ -878,15 +878,13 @@ namespace AzFramework AZ::SerializeContext* serializeContext = azrtti_cast(reflection); if (serializeContext) { - serializeContext->Class() + serializeContext->Class() ->Version(4, &TransformComponentVersionConverter) ->Field("Parent", &TransformComponent::m_parentId) ->Field("Transform", &TransformComponent::m_worldTM) ->Field("LocalTransform", &TransformComponent::m_localTM) ->Field("ParentActivationTransformMode", &TransformComponent::m_parentActivationTransformMode) ->Field("IsStatic", &TransformComponent::m_isStatic) - ->Field("InterpolatePosition", &TransformComponent::m_interpolatePosition) - ->Field("InterpolateRotation", &TransformComponent::m_interpolateRotation) ; } diff --git a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.h b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.h index abea0bd4dd..0dd53d84ed 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.h +++ b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.h @@ -17,7 +17,6 @@ #include #include #include -#include namespace AzToolsFramework { @@ -41,10 +40,9 @@ namespace AzFramework , public AZ::TransformBus::Handler , public AZ::TransformNotificationBus::Handler , private AZ::TransformHierarchyInformationBus::Handler - , public NetBindable { public: - AZ_COMPONENT(TransformComponent, AZ::TransformComponentTypeId, NetBindable, AZ::TransformInterface); + AZ_COMPONENT(TransformComponent, AZ::TransformComponentTypeId, AZ::TransformInterface); friend class AzToolsFramework::Components::TransformComponent; @@ -218,11 +216,5 @@ namespace AzFramework bool m_parentActive = false; ///< Keeps track of the state of the parent entity. bool m_onNewParentKeepWorldTM = true; ///< If set, recompute localTM instead of worldTM when parent becomes active. bool m_isStatic = false; ///< If true, the transform is static and doesn't move while entity is active. - - //! @deprecated - //! @{ - AZ::InterpolationMode m_interpolatePosition = AZ::InterpolationMode::NoInterpolation; - AZ::InterpolationMode m_interpolateRotation = AZ::InterpolationMode::NoInterpolation; - //! @} }; } // namespace AZ diff --git a/Code/Framework/AzFramework/AzFramework/Network/DynamicSerializableFieldMarshaler.h b/Code/Framework/AzFramework/AzFramework/Network/DynamicSerializableFieldMarshaler.h deleted file mode 100644 index 3e69454f59..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/DynamicSerializableFieldMarshaler.h +++ /dev/null @@ -1,146 +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 -#ifndef AZFRAMEWORK_NETWORK_DYNAMICSERIALIZABLEFIELDMARSHALER_H -#define AZFRAMEWORK_NETWORK_DYNAMICSERIALIZABLEFIELDMARSHALER_H - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace GridMate -{ - /** - * Marshaler for DynamicSerializableField, contains a template param for allocating the memory buffer that it's going to use to write to. - */ - template - class DynamicSerializableFieldMarshaler - { - public: - DynamicSerializableFieldMarshaler() - : m_serializeContext(nullptr) - { - EBUS_EVENT_RESULT(m_serializeContext, AZ::ComponentApplicationBus, GetSerializeContext); - } - - // Mainly here for unit test purposes. - DynamicSerializableFieldMarshaler(AZ::SerializeContext* context) - : m_serializeContext(context) - { - } - - AZ_FORCE_INLINE void Marshal(WriteBuffer& wb, const AZ::DynamicSerializableField& value) const - { - AZ_Error("DynamicSerializableFieldMarshaler", m_serializeContext, "Unknown SerializationContext. Aborting Marshal attempt.\n"); - if (m_serializeContext) - { - Marshaler sizeMarshaler; - Marshaler uuidMarshaler; - - AZStd::vector memoryBuffer(BufferSize); - - // Start buffer in write mode. - AZ::IO::ByteContainerStream memoryStream(&memoryBuffer); - - AZ::u32 bufferSize = 0; - - if (m_serializeContext->FindClassData(value.m_typeId)) - { - if (AZ::Utils::SaveObjectToStream(memoryStream, AZ::DataStream::StreamType::ST_BINARY, value.m_data, value.m_typeId, m_serializeContext)) - { - bufferSize = static_cast(memoryStream.GetCurPos()); - } - } - else - { - AZ_Error("DynamicSerializableFieldMarshaler", !value.IsValid(), "Could not save object to stream because type Id %s is not registered with the serializer.\n", value.m_typeId.ToString().c_str()); - } - - sizeMarshaler.Marshal(wb, bufferSize); - uuidMarshaler.Marshal(wb, value.m_typeId); - wb.WriteRaw(memoryBuffer.data(), bufferSize); - } - } - - AZ_FORCE_INLINE void Unmarshal(AZ::DynamicSerializableField& value, ReadBuffer& rb) const - { - value.DestroyData(m_serializeContext); - - AZ_Error("DynamicSerializableFieldMarshaler", m_serializeContext, "Unknown SerializationContext. Aborting Unmarshal attempt.\n"); - if (m_serializeContext) - { - Marshaler sizeMarshaler; - AZ::u32 marshaledBufferSize = 0; - sizeMarshaler.Unmarshal(marshaledBufferSize, rb); - - AZ_Assert(marshaledBufferSize <= BufferSize,"Trying to deserialize too much data for the allocated buffer size\n"); - - // Marshal out the TypeId so I can use it on the receiving end. - Marshaler uuidMarshaler; - uuidMarshaler.Unmarshal(value.m_typeId, rb); - - if (marshaledBufferSize > 0) - { - // See if there's some nice way to use this. - // - Can't make this a member variable, since both these methods are const. - AZStd::vector memoryBuffer(marshaledBufferSize + 1); - - if (rb.ReadRaw(memoryBuffer.data(), marshaledBufferSize)) - { - // Start buffer in read mode. - AZ::IO::ByteContainerStream memoryStream(&memoryBuffer); - - // we'll use a strict filter here, one that doesn't allow deserialization to automatically start loading assets, nor tolerates errors. - // this is becuase this is coming from a network interface and should always be error-free. - AZ::ObjectStream::FilterDescriptor filterToUse(&AZ::Data::AssetFilterNoAssetLoading, AZ::ObjectStream::FILTERFLAG_STRICT); - value.m_data = AZ::Utils::LoadObjectFromStream(memoryStream, m_serializeContext, &value.m_typeId, filterToUse); - } - } - } - } - - private: - AZ::SerializeContext* m_serializeContext; - }; - - /** - * Specialized marshaler for AZ::DynamicSerializableField - * Mainly here to hook into the DataSet Marshaler auto detection logic, and provide a default buffer size for the actual marshaler - */ - template<> - class Marshaler - : public DynamicSerializableFieldMarshaler<1024> - { - public: - - Marshaler() - { - } - - // Mainly here for unit test purposes. - Marshaler(AZ::SerializeContext* context) - : DynamicSerializableFieldMarshaler(context) - { - } - }; -} - -#endif diff --git a/Code/Framework/AzFramework/AzFramework/Network/EntityIdMarshaler.h b/Code/Framework/AzFramework/AzFramework/Network/EntityIdMarshaler.h deleted file mode 100644 index 0116020cc0..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/EntityIdMarshaler.h +++ /dev/null @@ -1,76 +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 -#ifndef AZFRAMEWORK_NETWORK_ENTITYIDMARSHALER_H -#define AZFRAMEWORK_NETWORK_ENTITYIDMARSHALER_H - -#include -#include - -#include -#include - -namespace GridMate -{ - template<> - class Marshaler - { - public: - AZ_TYPE_INFO_LEGACY( Marshaler, "{23F4722F-D104-4E30-9342-43F4DDD1894D}", AZ::EntityId ); - - void Marshal(GridMate::WriteBuffer& wb, const AZ::EntityId& source) const - { - Marshaler idMarshaler; - idMarshaler.Marshal(wb,static_cast(source)); - } - - void Unmarshal(AZ::EntityId& target, GridMate::ReadBuffer& rb) const - { - AZ::u64 id = 0; - - Marshaler idMarshaler; - idMarshaler.Unmarshal(id,rb); - - target = AZ::EntityId(id); - } - }; - - template<> - class Marshaler - { - public: - void Marshal(GridMate::WriteBuffer& wb, const AZ::NamedEntityId& source) const - { - Marshaler idMarshaler; - idMarshaler.Marshal(wb, static_cast(source)); - - Marshaler stringMarshaler; - stringMarshaler.Marshal(wb, source.GetName()); - } - - void Unmarshal(AZ::NamedEntityId& target, GridMate::ReadBuffer& rb) const - { - AZ::u64 id = 0; - - Marshaler idMarshaler; - idMarshaler.Unmarshal(id, rb); - - AZStd::string name; - Marshaler stringMarshaler; - stringMarshaler.Unmarshal(name, rb); - - target = AZ::NamedEntityId(AZ::EntityId(id), name); - } - }; -} - -#endif diff --git a/Code/Framework/AzFramework/AzFramework/Network/InterestManagerComponent.cpp b/Code/Framework/AzFramework/AzFramework/Network/InterestManagerComponent.cpp deleted file mode 100644 index 6aa32158f1..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/InterestManagerComponent.cpp +++ /dev/null @@ -1,187 +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 - -using namespace GridMate; - -namespace AzFramework -{ - void InterestManagerComponent::Reflect(AZ::ReflectContext* context) - { - if (context) - { - AZ::SerializeContext* serializeContext = azrtti_cast(context); - if (serializeContext) - { - serializeContext->Class() - ->Version(1); - - AZ::EditContext* editContext = serializeContext->GetEditContext(); - - if (editContext) - { - editContext->Class( - "InterestManagerComponent", "Interest manager instance") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System", 0xc94d118b)); - } - } - - // We need to register the chunk types for each handler here at reflect time - if (!GridMate::ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(GridMate::ReplicaChunkClassId(ProximityInterestChunk::GetChunkName()))) - { - GridMate::ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - } - - if (!GridMate::ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(GridMate::ReplicaChunkClassId(BitmaskInterestChunk::GetChunkName()))) - { - GridMate::ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - } - } - } - - void InterestManagerComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("InterestManager", 0x79993873)); - } - - void InterestManagerComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("InterestManager", 0x79993873)); - } - - - - InterestManagerComponent::InterestManagerComponent() - : m_im(nullptr) - , m_bitmaskHandler(nullptr) - , m_proximityHandler(nullptr) - , m_session(nullptr) - { - - } - - void InterestManagerComponent::Activate() - { - InterestManagerRequestsBus::Handler::BusConnect(); - NetBindingSystemEventsBus::Handler::BusConnect(); - AZ::SystemTickBus::Handler::BusConnect(); - } - - void InterestManagerComponent::Deactivate() - { - AZ::SystemTickBus::Handler::BusDisconnect(); - NetBindingSystemEventsBus::Handler::BusDisconnect(); - InterestManagerRequestsBus::Handler::BusDisconnect(); - - ShutdownInterestManager(); - } - - void InterestManagerComponent::OnSystemTick() - { - if (m_im && m_im->IsReady()) - { - m_im->Update(); - } - } - - InterestManager* InterestManagerComponent::GetInterestManager() - { - return m_im.get(); - } - - BitmaskInterestHandler* InterestManagerComponent::GetBitmaskInterest() - { - return m_bitmaskHandler.get(); - } - - ProximityInterestHandler* InterestManagerComponent::GetProximityInterest() - { - return m_proximityHandler.get(); - } - - void InterestManagerComponent::OnNetworkSessionActivated(GridSession* session) - { - AZ_Assert(m_session == nullptr, "Already bound to the session"); - - AZ_TracePrintf("AzFramework", "Interest manager hooked up to the session '%s'\n", session->GetId().c_str()); - - m_session = session; - m_session->GetReplicaMgr()->SetAutoBroadcast(false); - - InitInterestManager(); - } - - void InterestManagerComponent::OnNetworkSessionDeactivated(GridSession* session) - { - if (m_session && m_session == session) - { - AZ_TracePrintf("AzFramework", "Interest manager disconnected from the session '%s'\n", session ? session->GetId().c_str() : "nullptr"); - - if (m_session->GetReplicaMgr()) - { - m_session->GetReplicaMgr()->SetAutoBroadcast(true); - } - - m_session = nullptr; - ShutdownInterestManager(); - } - else - { - AZ_Warning("AzFramework", false, "Interest manager was never active for session '%s'\n", session ? session->GetId().c_str() : "nullptr"); - } - } - - void InterestManagerComponent::InitInterestManager() - { - AZ_Assert(m_im == nullptr, "Already initialized interest manager"); - m_im = AZStd::make_unique(); - - InterestManagerDesc desc; - desc.m_rm = m_session->GetReplicaMgr(); - m_im->Init(desc); - - m_bitmaskHandler = AZStd::make_unique(); - m_im->RegisterHandler(m_bitmaskHandler.get()); - - m_proximityHandler = AZStd::make_unique(); - m_im->RegisterHandler(m_proximityHandler.get()); - - InterestManagerEventsBus::Broadcast( - &InterestManagerEventsBus::Events::OnInterestManagerActivate, m_im.get()); - } - - void InterestManagerComponent::ShutdownInterestManager() - { - if (m_im) - { - InterestManagerEventsBus::Broadcast( - &InterestManagerEventsBus::Events::OnInterestManagerDeactivate, m_im.get()); - - m_im->UnregisterHandler(m_bitmaskHandler.get()); - m_im->UnregisterHandler(m_proximityHandler.get()); - - m_bitmaskHandler = nullptr; - m_proximityHandler = nullptr; - m_im = nullptr; - } - } -} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Network/InterestManagerComponent.h b/Code/Framework/AzFramework/AzFramework/Network/InterestManagerComponent.h deleted file mode 100644 index de45c78d43..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/InterestManagerComponent.h +++ /dev/null @@ -1,120 +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 AZFRAMEWORK_NET_INTERESTMANAGER_COMPONENT_H -#define AZFRAMEWORK_NET_INTERESTMANAGER_COMPONENT_H - - -#include -#include -#include - -#include - -#include - -namespace GridMate -{ - class InterestManager; - class GridSession; - class BitmaskInterestHandler; - class ProximityInterestHandler; -} - -namespace AzFramework -{ - class InterestManagerSystemRequests - : public AZ::EBusTraits - { - public: - virtual ~InterestManagerSystemRequests() {} - - // Returns interest manager instance - virtual GridMate::InterestManager* GetInterestManager() = 0; - - // Returns interest manager instance - virtual GridMate::BitmaskInterestHandler* GetBitmaskInterest() = 0; - - // Returns interest manager instance - virtual GridMate::ProximityInterestHandler* GetProximityInterest() = 0; - }; - - // Interface Bus - using InterestManagerRequestsBus = AZ::EBus; - - class InterestManagerEvents - : public AZ::EBusTraits - { - public: - virtual ~InterestManagerEvents() {} - - // Called when interest manager is initialized and ready to use - virtual void OnInterestManagerActivate(GridMate::InterestManager* im) { (void)im; } - - // Called when interest manager is deactivated - virtual void OnInterestManagerDeactivate(GridMate::InterestManager* im) { (void)im; } - }; - - // Interface Bus - using InterestManagerEventsBus = AZ::EBus; - - /** - * Interest manager component. - * When component is activated replicas will go through interest filtering before being sent to other peers - */ - class InterestManagerComponent - : public AZ::Component - , public AZ::SystemTickBus::Handler - , public InterestManagerRequestsBus::Handler - , public NetBindingSystemEventsBus::Handler - { - public: - AZ_COMPONENT(InterestManagerComponent, "{55371FA7-2942-4A3C-A3EA-27FF2C7DB6C5}"); - - static void Reflect(AZ::ReflectContext* context); - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); - - InterestManagerComponent(); - - void Activate() override; - void Deactivate() override; - - protected: - - // AZ::SystemTickBus::Listener interface implementation - void OnSystemTick() override; - - // InterestManagerSystemRequests implementation - GridMate::InterestManager* GetInterestManager() override; - GridMate::BitmaskInterestHandler* GetBitmaskInterest() override; - GridMate::ProximityInterestHandler* GetProximityInterest() override; - - // SessionEventBus - void OnNetworkSessionActivated(GridMate::GridSession* session) override; - void OnNetworkSessionDeactivated(GridMate::GridSession* session) override; - - void InitInterestManager(); - void ShutdownInterestManager(); - - // Interest handlers - AZStd::unique_ptr m_im; - AZStd::unique_ptr m_bitmaskHandler; - AZStd::unique_ptr m_proximityHandler; - - GridMate::GridSession* m_session; ///< currently bound session - - private: - InterestManagerComponent(const InterestManagerComponent&) = delete; //Cannot use default due to unique_ptr. - }; -} // namesapce AzFramework - -#endif // AZFRAMEWORK_NET_INTERESTMANAGER_COMPONENT_H diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindable.cpp b/Code/Framework/AzFramework/AzFramework/Network/NetBindable.cpp deleted file mode 100644 index eb0e6efa47..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindable.cpp +++ /dev/null @@ -1,111 +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 - -namespace AzFramework -{ - //////////////// - // NetBindable - //////////////// - - NetBindable::NetBindable() - : m_isSyncEnabled(true) - { - } - - NetBindable::~NetBindable() - { - if (m_chunk) - { - // NetBindable is a base class for handlers for replica chunks, so we have to clear the handler since this object is about to go away - m_chunk->SetHandler(nullptr); - m_chunk = nullptr; - } - } - - GridMate::ReplicaChunkPtr NetBindable::GetNetworkBinding() - { - NetworkContext* netContext = nullptr; - NetSystemRequestBus::BroadcastResult(netContext, &NetSystemRequestBus::Events::GetNetworkContext); - AZ_Assert(netContext, "Cannot bind objects to the network with no NetworkContext"); - if (netContext) - { - m_chunk = netContext->CreateReplicaChunk(azrtti_typeid(this)); - netContext->Bind(this, m_chunk, NetworkContextBindMode::Authoritative); - return m_chunk; - } - - return nullptr; - } - - void NetBindable::SetNetworkBinding (GridMate::ReplicaChunkPtr chunk) - { - m_chunk = chunk; - - NetworkContext* netContext = nullptr; - NetSystemRequestBus::BroadcastResult(netContext, &NetSystemRequestBus::Events::GetNetworkContext); - AZ_Assert(netContext, "Cannot bind objects to the network with no NetworkContext"); - if (netContext) - { - netContext->Bind(this, m_chunk, NetworkContextBindMode::NonAuthoritative); - } - } - - void NetBindable::UnbindFromNetwork() - { - if (m_chunk) - { - // NetworkContext-reflected chunks need access to the handler when they are being destroyed, so we won't null handler in here - m_chunk = nullptr; - } - } - - void NetBindable::NetInit() - { - NetworkContext* netContext = nullptr; - NetSystemRequestBus::BroadcastResult(netContext, &NetSystemRequestBus::Events::GetNetworkContext); - AZ_Assert(netContext, "Cannot bind objects to the network with no NetworkContext"); - if (netContext) - { - netContext->Bind(this, nullptr, NetworkContextBindMode::NonAuthoritative); - } - } - - void NetBindable::Reflect(AZ::ReflectContext* reflection) - { - AZ::SerializeContext* serializeContext = azrtti_cast(reflection); - if (serializeContext) - { - serializeContext->Class() - ->Field("m_isSyncEnabled", &NetBindable::m_isSyncEnabled); - - AZ::EditContext* editContext = serializeContext->GetEditContext(); - - if (editContext) - { - editContext->Class( - "Network Bindable", "Network-bindable components are synchronized over the network.") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Networking") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) - ->DataElement(AZ::Edit::UIHandlers::Default, &NetBindable::m_isSyncEnabled, "Bind To network", "Enable binding to the network."); - } - } - } -} diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindable.h b/Code/Framework/AzFramework/AzFramework/Network/NetBindable.h deleted file mode 100644 index 39a05c4fc1..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindable.h +++ /dev/null @@ -1,799 +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 AZFRAMEWORK_NET_BINDABLE_H -#define AZFRAMEWORK_NET_BINDABLE_H - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -/* - * Including common GridMate marshallers. - * Otherwise, users of NetBindable/NetworkContext have to find and include them themselves. - */ -#include -#include -#include -#include -#include -#include -#include - -namespace AZ -{ - class ReflectContext; - namespace Internal - { - template - class AzFrameworkNetBindableFieldContainer; - } -} - -namespace AzFramework -{ - using GridMate::DataSetBase; - using GridMate::DataSet; - using GridMate::Marshaler; - using GridMate::BasicThrottle; - using GridMate::RpcBase; - using GridMate::TimeContext; - using GridMate::RpcContext; - using GridMate::RpcDefaultTraits; - - enum class NetworkContextBindMode - { - Authoritative, - NonAuthoritative - }; - - /** - * Components that want to be synchronized over the network should implement NetBindable. - * The NetBindable interface is obtained via AZ_RTTI so components need to make sure to - * declare NetBindable as a base class in their AZ_RTTI declaration (or AZ_COMPONENT declaration), - * as well as to declare both AZ::Component and NetBindable as base classes in the reflection. - * - * For example, here is how to mark a component for network replication in its class declaration: - * - * class TestFieldComponent - * : public AZ::Component - * , public AzFramework::NetBindable - * { - * public: - * AZ_COMPONENT(TestFieldComponent, "{DD02A926-F6B3-4820-9587-62EED9EEBB3F}", NetBindable); - * - * static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) - * { - * required.push_back(AZ_CRC("ReplicaChunkService")); - * } - * - * Note, you should declare a dependency on NetBindingComponent as it is done above with "ReplicaChunkService." - * NetBindingComponent is required for an entity to be considered for network replication and replicate your NetBindable-components. - */ - class NetBindable - : public GridMate::ReplicaChunkInterface - { - public: - AZ_RTTI(NetBindable, "{80206665-D429-4703-B42E-94434F82F381}"); - - NetBindable(); - virtual ~NetBindable(); - - void NetInit(); - - //! Called during network binding on the master. The default implementation will use the - //! NetworkContext to create a chunk. User implementations should create and return a new binding. - virtual GridMate::ReplicaChunkPtr GetNetworkBinding(); - - //! Called during network binding on proxies. - virtual void SetNetworkBinding(GridMate::ReplicaChunkPtr chunk); - - //! Called when network is unbound. Implementations should release their references to the binding, if they held a reference. - virtual void UnbindFromNetwork(); - - static void Reflect(AZ::ReflectContext* reflection); - - template , typename ThrottlerType = BasicThrottle > - class Field; - - template , typename ThrottlerType = BasicThrottle > - class BoundField; - - template - class Rpc; - - inline bool IsSyncEnabled() const { return m_isSyncEnabled; } - //! Can be used to disabled net sync on a per component basis - inline void SetSyncEnabled(bool enabled) { m_isSyncEnabled = enabled; } - protected: - bool m_isSyncEnabled; - GridMate::ReplicaChunkPtr m_chunk = nullptr; - }; - - class NetBindableFieldBase - { - public: - virtual ~NetBindableFieldBase() = default; - virtual void Bind(DataSetBase* dataSet, NetworkContextBindMode mode) = 0; - }; - - /** - * \brief NetBindable provides a simplified network interface to mark a member variable inside AZ::Component - * as a network field that will be replicated by GridMate. - * - * \tparam DataType data type of the field, can be either a common C++ type or a custom type - * \tparam MarshalerType optional, marshaler type that provides custom marshal and unmarshal logic, i.e. how to write @DataType to the network and back, see @GridMate::Marshaler - * \tparam ThrottlerType optional, throttler provides the ability to detect if a value is to be considered changed significantly enough for GridMate to replicate its state, see @GridMate::BasicThrottle - * - * Example: - * - * class TestFieldComponent : public AZ::Component , public AzFramework::NetBindable - * { - * public: - * Field m_testInt; - * - * And it must be reflected to SerializeContext _and_ NetworkContext: - * - * void TestFieldComponent::Reflect(AZ::ReflectContext* context) - * { - * if (AZ::SerializeContext* serialize = azrtti_cast(context)) - * { - * serialize->Class() - * ->Field("Test Int", &TestFieldComponent::m_testInt) - * ->Version(1); - * } - * - * if (AzFramework::NetworkContext* net = azrtti_cast(context)) - * { - * net->Class() - * ->Field("Test Int", &TestFieldComponent::m_testInt); - * } - * } - * - * Then you can simply write to it as it was an integer: - * - * m_testInt = 3; - * // or - * m_testInt = *m_testInt + 1; - */ - template - class NetBindable::Field - : public NetBindableFieldBase - { - friend class AZ::Internal::AzFrameworkNetBindableFieldContainer >; - public: - using DataSetType = DataSet; - using ValueType = DataType; - - explicit Field(const DataType& value = DataType()) - : m_dataSet(nullptr) - , m_value(value) - {} - ~Field() override = default; - - /* - * Disabling copy and move constructors in order to allow for a common use of fields, for example: - * m_field = m_field + 1; - */ - Field (const Field& other) = delete; - Field (Field&& other) = delete; - Field& operator= (const Field& other) = delete; - Field& operator= (Field&& other) = delete; - - const DataType& Get() const - { - return m_dataSet ? m_dataSet->Get() : m_value; - } - - virtual operator const DataType&() const - { - return Get(); - } - - virtual const DataType& operator*() const - { - return Get(); - } - - virtual Field& operator=(const DataType& val) - { - if (m_dataSet) - { - m_dataSet->Set(val); - } - else - { - m_value = val; - } - return *this; - } - - virtual Field& operator=(const DataType&& val) - { - if (m_dataSet) - { - m_dataSet->Set(AZStd::forward(val)); - } - else - { - m_value = AZStd::move(val); - } - return *this; - } - - void Bind(DataSetBase* dataSet, NetworkContextBindMode mode) override - { - BindDataSet(static_cast(dataSet), mode); - } - - static void ConstructDataSet(void* mem, const char* name) - { - new (mem) DataSetType(name, DataType(), MarshalerType(), ThrottlerType()); - } - - static void DestructDataSet(void* mem) - { - DataSetType* dataSet = reinterpret_cast(mem); - dataSet->~DataSetType(); - } - - protected: - template - void BindDataSet(DST* dataSet, NetworkContextBindMode mode) - { - if (m_dataSet) - { - m_value = m_dataSet->Get(); - } - m_dataSet = dataSet; - if (m_dataSet) - { - if (mode == NetworkContextBindMode::Authoritative) - { - /* - * If we are binding Field<> or BoundField<> on a component of an authoritative entity, - * then we want to bring over the value of the field in the component. This occurs during GetNetworkBinding(). - * - * Whereas on a client's (non-authoritative entities and their components) dataSet already has the desired value - * and should not be overwritten here. - */ - m_dataSet->Set(AZStd::move(m_value)); - } - m_value = DataType(); - } - } - - DataType* CacheValue() - { - if (m_dataSet) - { - m_value = m_dataSet->Get(); - } - return &m_value; - } - - const DataType& GetCachedValue() const - { - return m_value; - } - - private: - DataSet* m_dataSet; - DataType m_value; - }; - - /** - * \brief An extension of @NetBindable::Field with an ability to invoke a callback whenever the value changes on both authoritative and non-authoritative components. - * Or in other terms, on both the server and clients (when GridMate is setup to run in server-authoritative mode). - * - * \tparam DataType data type, same as @NetBindable::Field - * \tparam InterfaceType Component type class that holds this @BoundField - * \tparam FuncPtr member function pointer to the callback to invoke when this value is updated on non-authoritative components. - * \tparam MarshalerType optional, same as @NetBindable::Field - * \tparam ThrottlerType optional, same as @NetBindable::Field - * - * Example: - * - * BoundField m_testInt; - * - * And it must be reflected to SerializeContext _and_ NetworkContext just like @NetBindable::Field - * - * void TestFieldComponent::Reflect(AZ::ReflectContext* context) - * { - * if (AZ::SerializeContext* serialize = azrtti_cast(context)) - * { - * serialize->Class() - * ->Field("Test Int", &TestFieldComponent::m_testInt) - * ->Version(1); - * } - * - * if (AzFramework::NetworkContext* net = azrtti_cast(context)) - * { - * net->Class() - * ->Field("Test Int", &TestFieldComponent::m_testInt); - * } - * } - */ - template - class NetBindable::BoundField - : public NetBindable::Field - { - using BaseClass = NetBindable::Field; - friend class AZ::Internal::AzFrameworkNetBindableFieldContainer >; - public: - AZ_TYPE_INFO_LEGACY(BoundField, "{5151CEAF-6AC0-45D7-AEDF-8B6C46CE07B9}", DataType, InterfaceType, MarshalerType, ThrottlerType); - using DataSetType = typename DataSet::template BindInterface; - - explicit BoundField(const DataType& value = DataType()) - : BaseClass(value) - {} - ~BoundField() override = default; - - /* - * Disabling copy and move constructors in order to allow for a common use of fields, for example: - * m_field = m_field + 1; - */ - BoundField (const BoundField& other) = delete; - BoundField (BoundField&& other) = delete; - BoundField& operator= (const BoundField& other) = delete; - BoundField& operator= (BoundField&& other) = delete; - - operator DataType() const - { - return BaseClass::Get(); - } - - const DataType& operator*() const override - { - return BaseClass::Get(); - } - - BaseClass& operator=(const DataType& val) override - { - BaseClass::operator=(val); - return *this; - } - - BaseClass& operator=(const DataType&& val) override - { - BaseClass::operator=(val); - return *this; - } - - void Bind(DataSetBase* dataSet, NetworkContextBindMode mode) override - { - BaseClass::BindDataSet(static_cast(dataSet), mode); - } - - static void ConstructDataSet(void* mem, const char* name) - { - new (mem) DataSetType(name, DataType(), MarshalerType(), ThrottlerType()); - } - - static void DestructDataSet(void* mem) - { - DataSetType* dataSet = reinterpret_cast(mem); - dataSet->~DataSetType(); - } - }; - - class NetBindableRpcBase - { - public: - virtual ~NetBindableRpcBase() = default; - virtual void Bind(RpcBase* rpc) = 0; - virtual void Bind(NetBindable* handler) = 0; - }; - - /** - * \brief NetBindable::Rpc::Binder should be used for any RPC in a NetBindable that you want - * to be able to call remotely. If the object is not network bound, RPC - * calls will dispatch directly, as if the object was authoritative. - * - * \tparam Args any custom parameters for the remote procedure calls. - * - * Here is an example: - * - * // callback - * bool OnRpc(float value, const GridMate::RpcContext& rc); - * - * // Rpc declaration - * Rpc::Binder m_testRpc; - * - * Rpc needs to be reflected in NetworkContext like this: - * - * void TestRPCComponent::Reflect(AZ::ReflectContext* context) - * { - * if (AZ::SerializeContext* serialize = azrtti_cast(context)) - * { - * serialize->Class() - * ->Version(1); - * } - * - * if (AzFramework::NetworkContext* net = azrtti_cast(context)) - * { - * net->Class() - * ->RPC("Test RPC", &TestRPCComponent::m_testRpc); - * } - * } - * - * It can be invoked as if it was a method: - * - * m_testRpc(deltaTime); - */ - template - class NetBindable::Rpc - { - public: - /** - * \brief Binds rpc callback to a pointer to member function of AZ::Component derived from AzFramework::NetBindable - * See @NetBindable::Rpc - */ - template - class Binder - : public NetBindableRpcBase - { - friend class NetworkContext; - public: - using BindInterfaceType = typename GridMate::Rpc...>::template BindInterface; - - Binder() - : m_rpc(nullptr) - , m_instance(nullptr) - {} - - void Bind(RpcBase* rpc) override - { - m_rpc = static_cast(rpc); - m_instance = nullptr; - } - - void Bind(NetBindable* bindable) override - { - m_instance = static_cast(bindable); - m_rpc = nullptr; - } - - template - void operator()(CallArgs&& ... args) - { - AZ_Assert(m_instance || m_rpc, "Cannot call an RPC without either a local instance or a network bound handler, did you forget to register with NetworkContext()?"); - if (m_rpc) // connected to network - { - (*m_rpc)(AZStd::forward(args) ...); - } - else if (m_instance) // local dispatch - { - (*m_instance.*FuncPtr)(AZStd::forward(args) ..., RpcContext()); - } - } - - protected: - static void ConstructRpc(void* mem, const char* name) - { - new (mem) BindInterfaceType(name); - } - - static void DestructRpc(void*) { } - - private: - BindInterfaceType* m_rpc; - InterfaceType* m_instance; - }; - - Rpc() = delete; - }; -} // namespace AzFramework - -namespace AZ -{ - AZ_TYPE_INFO_TEMPLATE_WITH_NAME(AzFramework::NetBindable::Field, "Field", "{00D56FA7-F8BD-402B-97FB-0E2599897056}", AZ_TYPE_INFO_CLASS, AZ_TYPE_INFO_TYPENAME, AZ_TYPE_INFO_TYPENAME); - - namespace Internal - { - template - class AzFrameworkNetBindableFieldContainer - : public SerializeContext::IDataContainer - { - using ValueType = typename FieldType::ValueType; - public: - AzFrameworkNetBindableFieldContainer() - { - m_classElement.m_name = GetDefaultElementName(); - m_classElement.m_nameCrc = GetDefaultElementNameCrc(); - m_classElement.m_dataSize = sizeof(ValueType); - m_classElement.m_offset = 0; - m_classElement.m_azRtti = GetRttiHelper(); - m_classElement.m_flags = AZStd::is_pointer::value ? SerializeContext::ClassElement::FLG_POINTER : 0; - m_classElement.m_genericClassInfo = SerializeGenericTypeInfo::GetGenericInfo(); - m_classElement.m_typeId = SerializeGenericTypeInfo::GetClassTypeId(); - m_classElement.m_editData = nullptr; - } - - /// Returns the element generic (offsets are mostly invalid 0xbad0ffe0, there are exceptions). Null if element with this name can't be found. - virtual const SerializeContext::ClassElement* GetElement(AZ::u32 elementNameCrc) const override - { - if (elementNameCrc == m_classElement.m_nameCrc) - { - return &m_classElement; - } - return nullptr; - } - - bool GetElement(SerializeContext::ClassElement& classElement, const SerializeContext::DataElement& dataElement) const override - { - if (dataElement.m_nameCrc == m_classElement.m_nameCrc) - { - classElement = m_classElement; - return true; - } - return false; - } - - /// Enumerate elements in the array - virtual void EnumElements(void* instance, const ElementCB& cb) override - { - FieldType* field = reinterpret_cast(instance); - // We can't mess with the internal storage of the dataset safely, so we copy it into - // the field's local value cache temporarily, then hand that to the callback - // This will modify the local value cache, but that shouldn't matter as it will never - // be used as long as a dataset is bound - // If this turns out to be a perf problem due to copies of complex types, then - // the easy solution is to get DataSets to expose a pointer to their underlying - // data storage, and then we can return a pointer to that and modify it directly - // if the field is bound to the network - ValueType* valPtr = field->CacheValue(); - cb(valPtr, m_classElement.m_typeId, m_classElement.m_genericClassInfo ? m_classElement.m_genericClassInfo->GetClassData() : nullptr, &m_classElement); - // Ensure that the dataset is updated if changes happened - *field = *valPtr; - } - - void EnumTypes(const ElementTypeCB& cb) override - { - cb(m_classElement.m_typeId, &m_classElement); - } - - /// Return number of elements in the container. - virtual size_t Size(void*) const override - { - return 1; - } - - /// Returns the capacity of the container. Returns 0 for objects without fixed capacity. - virtual size_t Capacity(void* instance) const override - { - (void)instance; - return 1; - } - - /// Returns true if elements pointers don't change on add/remove. If false you MUST enumerate all elements. - virtual bool IsStableElements() const override { return true; } - - /// Returns true if the container is fixed size, otherwise false. - virtual bool IsFixedSize() const override { return true; } - - /// Returns if the container is fixed capacity, otherwise false - virtual bool IsFixedCapacity() const override { return true; } - - /// Returns true if the container is a smart pointer. - virtual bool IsSmartPointer() const override { return true; } - - /// Returns true if the container elements can be addressed by index, otherwise false. - virtual bool CanAccessElementsByIndex() const override { return false; } - - /// Reserve element - virtual void* ReserveElement(void* instance, const SerializeContext::ClassElement*) override - { - FieldType* field = reinterpret_cast(instance); - *field = ValueType(); - return field->CacheValue(); // return the local value, should be accurate as the field will be unbound at serialization time - } - - /// Get an element's address by its index (called before the element is loaded). - virtual void* GetElementByIndex(void*, const SerializeContext::ClassElement*, size_t) override - { - return nullptr; - } - - /// Store element - virtual void StoreElement(void* instance, void*) override - { - // force store the value again, just in case the field is bound to a dataset - FieldType* field = reinterpret_cast(instance); - *field = field->GetCachedValue(); - } - - /// Remove element in the container. - virtual bool RemoveElement(void* instance, const void*, SerializeContext*) override - { - FieldType* field = reinterpret_cast(instance); - *field = ValueType(); - return false; // you can't remove element from this container. - } - - /// Remove elements (removed array of elements) regardless if the container is Stable or not (IsStableElements) - virtual size_t RemoveElements(void* instance, const void**, size_t, SerializeContext*) override - { - RemoveElement(instance, nullptr, nullptr); - return 0; // you can't remove elements from this container. - } - - /// Clear elements in the instance. - virtual void ClearElements(void* instance, SerializeContext*) override - { - RemoveElement(instance, nullptr, nullptr); - } - - SerializeContext::ClassElement m_classElement; ///< Generic class element covering as must as possible of the element (offset, and some other fields are invalid) - }; - } - - template - struct SerializeGenericTypeInfo< AzFramework::NetBindable::Field > - { - typedef typename AzFramework::NetBindable::Field ContainerType; - - class GenericClassNetBindableField - : public GenericClassInfo - { - public: - AZ_TYPE_INFO(GenericClassNetBindableField, "{C1D4DD97-5DD7-42ED-969C-7435F27F5D8C}"); - GenericClassNetBindableField() - : m_classData{ SerializeContext::ClassData::Create("AzFramework::NetBindable::Field", GetSpecializedTypeId(), Internal::NullFactory::GetInstance(), nullptr, &m_containerStorage) } - { - } - - SerializeContext::ClassData* GetClassData() override - { - return &m_classData; - } - - size_t GetNumTemplatedArguments() override - { - return 1; - } - - const Uuid& GetTemplatedTypeId(size_t) override - { - return SerializeGenericTypeInfo::GetClassTypeId(); - } - - const Uuid& GetSpecializedTypeId() const override - { - return azrtti_typeid(); - } - - const Uuid& GetGenericTypeId() const override - { - return TYPEINFO_Uuid(); - } - - const Uuid& GetLegacySpecializedTypeId() const override - { - return AZ::AzTypeInfo::template Uuid(); - } - - void Reflect(SerializeContext* serializeContext) - { - if (serializeContext) - { - serializeContext->RegisterGenericClassInfo(GetSpecializedTypeId(), this, &AnyTypeInfoConcept::CreateAny); - if (GenericClassInfo* containerGenericClassInfo = m_containerStorage.m_classElement.m_genericClassInfo) - { - containerGenericClassInfo->Reflect(serializeContext); - } - } - } - - protected: - Internal::AzFrameworkNetBindableFieldContainer m_containerStorage; - SerializeContext::ClassData m_classData; - }; - - using ClassInfoType = GenericClassNetBindableField; - - static ClassInfoType* GetGenericInfo() - { - return GetCurrentSerializeContextModule().CreateGenericClassInfo(); - } - - static const Uuid& GetClassTypeId() - { - return GetGenericInfo()->GetClassData()->m_typeId; - } - }; - - template - struct SerializeGenericTypeInfo< typename AzFramework::NetBindable::BoundField > - { - typedef typename AzFramework::NetBindable::BoundField ContainerType; - - class GenericClassNetBindableBoundField - : public GenericClassInfo - { - public: - AZ_TYPE_INFO(GenericClassNetBindableBoundField, "{EFD64FE7-9432-401A-B7A1-1767F4C5A7F0}"); - GenericClassNetBindableBoundField() - : m_classData{ SerializeContext::ClassData::Create("AzFramework::NetBindable::BoundField", GetSpecializedTypeId(), Internal::NullFactory::GetInstance(), nullptr, &m_containerStorage) } - { - } - - SerializeContext::ClassData* GetClassData() override - { - return &m_classData; - } - - size_t GetNumTemplatedArguments() override - { - return 1; - } - - const Uuid& GetTemplatedTypeId(size_t) override - { - return SerializeGenericTypeInfo::GetClassTypeId(); - } - - const Uuid& GetSpecializedTypeId() const override - { - return azrtti_typeid(); - } - - const Uuid& GetGenericTypeId() const override - { - return TYPEINFO_Uuid(); - } - - const Uuid& GetLegacySpecializedTypeId() const override - { - return AZ::AzTypeInfo::template Uuid(); - } - - void Reflect(SerializeContext* serializeContext) - { - if (serializeContext) - { - serializeContext->RegisterGenericClassInfo(GetSpecializedTypeId(), this, &AnyTypeInfoConcept::CreateAny); - if (GenericClassInfo* containerGenericClassInfo = m_containerStorage.m_classElement.m_genericClassInfo) - { - containerGenericClassInfo->Reflect(serializeContext); - } - } - } - - protected: - Internal::AzFrameworkNetBindableFieldContainer m_containerStorage; - SerializeContext::ClassData m_classData; - }; - - using ClassInfoType = GenericClassNetBindableBoundField; - - static ClassInfoType* GetGenericInfo() - { - return GetCurrentSerializeContextModule().CreateGenericClassInfo(); - } - - static const Uuid& GetClassTypeId() - { - return GetGenericInfo()->GetClassData()->m_typeId; - } - }; -} - -#endif // AZFRAMEWORK_NET_BINDABLE_H -#pragma once diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponent.cpp b/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponent.cpp deleted file mode 100644 index 90613daabe..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponent.cpp +++ /dev/null @@ -1,287 +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 -#include -#include - -namespace AzFramework -{ - void NetBindingComponent::Reflect(AZ::ReflectContext* reflection) - { - NetBindable::Reflect(reflection); - - AZ::SerializeContext* serializeContext = azrtti_cast(reflection); - if (serializeContext) - { - serializeContext->Class() - ; - - AZ::EditContext* editContext = serializeContext->GetEditContext(); - - if (editContext) - { - editContext->Class( - "Network Binding", "The Network Binding component marks an entity as able to be replicated across the network") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Networking") - ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/NetBinding.svg") - ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/NetBinding.png") - ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://docs.aws.amazon.com/lumberyard/latest/userguide/component-network-binding.html") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)); - } - } - - AZ::BehaviorContext* behaviorContext = azrtti_cast(reflection); - - if (behaviorContext) - { - behaviorContext->EBus("NetBindingHandlerBus") - ->Event("IsEntityBoundToNetwork", &NetBindingHandlerBus::Events::IsEntityBoundToNetwork) - ->Event("IsEntityAuthoritative", &NetBindingHandlerBus::Events::IsEntityAuthoritative) - - // Desired, but currently unsupported events. - // Seems to be an unsupported type(AZ::u16) - //->Event("SetReplicaPriority", &NetBindingHandlerBus::Events::SetReplicaPriority) - //->Event("GetReplicaPriority", &NetBindingHandlerBus::Events::GetReplicaPriority) - ; - } - - // We also need to register the chunk type, and this would be a good time to do so. - if (!GridMate::ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(GridMate::ReplicaChunkClassId(NetBindingComponentChunk::GetChunkName()))) - { - GridMate::ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - } - } - - NetBindingComponent::NetBindingComponent() - : m_isLevelSliceEntity(false) - { - } - - void NetBindingComponent::Activate() - { - NetBindingHandlerBus::Handler::BusConnect(GetEntityId()); - - if (!IsEntityBoundToNetwork()) - { - bool shouldBind = false; - NetBindingSystemBus::BroadcastResult( shouldBind, &NetBindingSystemBus::Events::ShouldBindToNetwork); - if (shouldBind) - { - BindToNetwork(nullptr); - } - else - { - /* - * This is the Editor path. We still need to call NetBindable::NetInit() in order - * to initialize NetworkContext Fields and RPCs, so that they behave as - * authoritative in game editor mode. Without this call RPCs callbacks won't invoke inside the Editor. - * For example: - * - * static void Reflect(...) - * { - * NetworkContext->Class()->RPC("my rpc", &MyNetworkComponent::m_myRpc); - * } - * ... - * m_myRpc(); // <--- will not invoke the callback inside the Editor unless NetInit() is called below. - */ - for (Component* component : GetEntity()->GetComponents()) - { - if (NetBindable* netBindable = azrtti_cast(component)) - { - netBindable->NetInit(); - } - } - } - } - } - - void NetBindingComponent::Deactivate() - { - NetBindingHandlerBus::Handler::BusDisconnect(); - if (IsEntityBoundToNetwork()) - { - static_cast(m_chunk.get())->SetBinding(nullptr); - if (m_chunk->IsMaster()) - { - m_chunk->GetReplica()->Destroy(); - } - m_chunk = nullptr; - } - } - - bool NetBindingComponent::IsEntityBoundToNetwork() - { - return m_chunk && m_chunk->GetReplica(); - } - - bool NetBindingComponent::IsEntityAuthoritative() - { - return !m_chunk || m_chunk->IsMaster(); - } - - void NetBindingComponent::BindToNetwork(GridMate::ReplicaPtr bindTo) - { - AZ_Assert(!IsEntityBoundToNetwork(), "We shouldn't be bound to the network if the network is just starting!"); - - if (bindTo) - { - NetBindingComponentChunkPtr bindingChunk = bindTo->FindReplicaChunk(); - AZ_Assert(bindingChunk, "Can't find NetBindingComponentChunk!"); - m_chunk = bindingChunk; - bindingChunk->SetBinding(this); - - GridMate::Replica* replica = bindingChunk->GetReplica(); - size_t nChunks = replica->GetNumChunks(); - size_t nBindings = bindingChunk->m_bindMap.Get().size(); - AZ_Assert(nChunks == nBindings, "Number of chunks received is not the same as the size of the bind map!"); - nBindings = AZ::GetMin(nBindings, nChunks); - for (size_t i = 0; i < nBindings; ++i) - { - AZ::ComponentId bindToId = bindingChunk->m_bindMap.Get()[i]; - if (bindToId != AZ::InvalidComponentId) - { - AZ::Component* component = GetEntity()->FindComponent(bindToId); - NetBindable* netBindable = azrtti_cast(component); - AZ_Assert(netBindable, "Can't find net bindable component with id %llu to be bound to chunk type %s!", bindToId, replica->GetChunkByIndex(i)->GetDescriptor()->GetChunkName()); - if (netBindable && netBindable->IsSyncEnabled()) - { - netBindable->SetNetworkBinding(replica->GetChunkByIndex(i)); - } - } - } - } - else - { - GridMate::ReplicaPtr replica = GridMate::Replica::CreateReplica(GetEntity()->GetName().c_str()); - NetBindingComponentChunk* chunk = GridMate::CreateReplicaChunk(); - m_chunk = chunk; - chunk->SetBinding(this); - replica->AttachReplicaChunk(chunk); - - chunk->m_bindMap.Modify([&](AZStd::vector& bindMap) - { - // Mark the chunks already in the replica as non-components. - bindMap.resize(replica->GetNumChunks(), AZ::InvalidComponentId); - - // Collect the bindings and add the to the replica - AZ::Entity* entity = GetEntity(); - for (Component* component : entity->GetComponents()) - { - NetBindable* netBindable = azrtti_cast(component); - if (netBindable && netBindable->IsSyncEnabled()) - { - GridMate::ReplicaChunkPtr bindingChunk = netBindable->GetNetworkBinding(); - if (bindingChunk) - { - bindMap.push_back(component->GetId()); - replica->AttachReplicaChunk(bindingChunk); - } - } - } - return true; - }); - - // Add replica to session replica manager (may be deferred) - NetBindingSystemBus::Broadcast( &NetBindingSystemBus::Events::AddReplicaMaster, GetEntity(), replica); - } - } - - void NetBindingComponent::UnbindFromNetwork() - { - if (m_chunk) - { - for (Component* component : GetEntity()->GetComponents()) - { - NetBindable* netBindable = azrtti_cast(component); - if (netBindable && netBindable->IsSyncEnabled()) - { - netBindable->UnbindFromNetwork(); - } - } - - NetBindingComponentChunkPtr chunk = static_cast(m_chunk.get()); - chunk->SetBinding(nullptr); - m_chunk = nullptr; - if (chunk->IsProxy()) - { - EntityContextId contextId = EntityContextId::CreateNull(); - EntityIdContextQueryBus::EventResult( contextId, GetEntityId(), &EntityIdContextQueryBus::Events::GetOwningContextId); - if (contextId.IsNull()) - { - delete GetEntity(); - } - else if (!IsLevelSliceEntity()) - { - NetBindingSystemBus::Broadcast( &NetBindingSystemBus::Events::UnbindGameEntity, GetEntityId(), m_sliceInstanceId); - } - } - } - } - - void NetBindingComponent::MarkAsLevelSliceEntity() - { - AZ_Assert(!IsEntityBoundToNetwork(), "MarkAsLevelSliceEntity() has to be called before the entity is bound to the network!"); - m_isLevelSliceEntity = true; - } - - void NetBindingComponent::SetSliceInstanceId(const AZ::SliceComponent::SliceInstanceId& sliceInstanceId) - { - m_sliceInstanceId = sliceInstanceId; - } - - void NetBindingComponent::RequestEntityChangeOwnership(GridMate::PeerId peerId) - { - if (m_chunk && m_chunk->GetReplica()) - { - m_chunk->GetReplica()->RequestChangeOwnership(peerId); - } - } - - void NetBindingComponent::SetReplicaPriority(GridMate::ReplicaPriority replicaPriority) - { - if (m_chunk) - { - m_chunk->SetPriority(replicaPriority); - } - } - - GridMate::ReplicaPriority NetBindingComponent::GetReplicaPriority() const - { - if (m_chunk && m_chunk->GetReplica()) - { - return m_chunk->GetReplica()->GetPriority(); - } - else - { - AZ_Error("NetBindingComponent",false,"Trying to gather ReplicaPriority without having a Replica."); - return GridMate::k_replicaPriorityLowest; - } - } - - bool NetBindingComponent::IsLevelSliceEntity() const - { - return m_isLevelSliceEntity; - } -} // namespace AzFramework - diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponent.h b/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponent.h deleted file mode 100644 index 5f4ec1c7f3..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponent.h +++ /dev/null @@ -1,85 +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 AZFRAMEWORK_NET_BINDING_COMPONENT_H -#define AZFRAMEWORK_NET_BINDING_COMPONENT_H - -#include -#include - -namespace AzFramework -{ - /** - * NetBindingComponent enables network synchronization for the entity. - * It works in conjunction with NetBindingComponentChunk and NetBindingSystemComponent - * to perform network binding and notifies other components on the entity to bind - * their ReplicaChunks via the NetBindable interface. - * - * Entities bound to proxy replicas will be automatically destroyed when they are - * unbound from the network. - */ - class NetBindingComponent - : public AZ::Component - , public NetBindingHandlerBus::Handler - { - friend class NetBindingComponentChunk; - - public: - AZ_COMPONENT(NetBindingComponent, "{E9CA5D63-ED2D-4B59-B3C4-EBCD4A0013E4}", NetBindingHandlerInterface); - - NetBindingComponent(); - - protected: - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("ReplicaChunkService", 0xf86b88a8)); - } - - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("ReplicaChunkService", 0xf86b88a8)); - } - - /////////////////////////////////////////////////////////////////////// - // AZ::Component - static void Reflect(AZ::ReflectContext* reflection); - void Activate() override; - void Deactivate() override; - /////////////////////////////////////////////////////////////////////// - - /////////////////////////////////////////////////////////////////////// - // NetBindingHandlerBus::Handler - void BindToNetwork(GridMate::ReplicaPtr bindTo) override; - void UnbindFromNetwork() override; - bool IsEntityBoundToNetwork() override; - bool IsEntityAuthoritative() override; - void MarkAsLevelSliceEntity() override; - void SetSliceInstanceId(const AZ::SliceComponent::SliceInstanceId& sliceInstanceId) override; - void RequestEntityChangeOwnership(GridMate::PeerId peerId = GridMate::InvalidReplicaPeerId) override; - - void SetReplicaPriority(GridMate::ReplicaPriority replicaPriority) override; - GridMate::ReplicaPriority GetReplicaPriority() const override; - /////////////////////////////////////////////////////////////////////// - - //! Returns if the entity belongs to the level slice for binding purposes. - bool IsLevelSliceEntity() const; - - //! Points to the NetBindingComponentChunk counterpart. - GridMate::ReplicaChunkPtr m_chunk; - bool m_isLevelSliceEntity; - AZ::SliceComponent::SliceInstanceId m_sliceInstanceId; - }; -} // namespace AzFramework - -#endif // AZFRAMEWORK_NET_BINDING_COMPONENT_H -#pragma once diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponentChunk.cpp b/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponentChunk.cpp deleted file mode 100644 index 6ebfe63507..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponentChunk.cpp +++ /dev/null @@ -1,254 +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 -#include -#include - -namespace AzFramework -{ - NetBindingComponentChunk::SpawnInfo::SpawnInfo() - : m_runtimeEntityId(AZ::EntityId::InvalidEntityId) - , m_owningContextId(UnspecifiedNetBindingContextSequence) - , m_staticEntityId(AZ::EntityId::InvalidEntityId) - , m_sliceInstanceId(UnspecifiedSliceInstanceId) - , m_sliceAssetId(UnspecifiedSliceInstanceId, 0) - { - } - - bool NetBindingComponentChunk::SpawnInfo::operator==(const SpawnInfo& rhs) - { - return m_owningContextId == rhs.m_owningContextId - && m_runtimeEntityId == rhs.m_runtimeEntityId - && m_staticEntityId == rhs.m_staticEntityId - && m_serializedState == rhs.m_serializedState - && m_sliceAssetId == rhs.m_sliceAssetId; - } - - bool NetBindingComponentChunk::SpawnInfo::ContainsSerializedState() const - { - return !m_serializedState.empty(); - } - - void NetBindingComponentChunk::SpawnInfo::Marshaler::Marshal(GridMate::WriteBuffer& wb, const SpawnInfo& data) - { - wb.Write(data.m_owningContextId, GridMate::VlqU32Marshaler()); - wb.Write(data.m_runtimeEntityId); - - bool useSerializedState = data.ContainsSerializedState(); - wb.Write(useSerializedState); - if (useSerializedState) - { - wb.Write(data.m_serializedState); - } - else - { - wb.Write(data.m_sliceAssetId); - wb.Write(data.m_staticEntityId); - wb.Write(data.m_sliceInstanceId); - } - } - - void NetBindingComponentChunk::SpawnInfo::Marshaler::Unmarshal(SpawnInfo& data, GridMate::ReadBuffer& rb) - { - rb.Read(data.m_owningContextId, GridMate::VlqU32Marshaler()); - rb.Read(data.m_runtimeEntityId); - - bool hasSerializedState = false; - rb.Read(hasSerializedState); - if (hasSerializedState) - { - rb.Read(data.m_serializedState); - } - else - { - rb.Read(data.m_sliceAssetId); - rb.Read(data.m_staticEntityId); - rb.Read(data.m_sliceInstanceId); - } - } - - NetBindingComponentChunk::NetBindingComponentChunk() - : m_bindingComponent(nullptr) - , m_spawnInfo("SpawnInfo") - , m_bindMap("ComponentBindMap") - { - m_spawnInfo.SetMaxIdleTime(0.f); - m_bindMap.SetMaxIdleTime(0.f); - } - - void NetBindingComponentChunk::OnReplicaActivate(const GridMate::ReplicaContext& rc) - { - (void)rc; - if (IsMaster()) - { - // Get and store entity spawn data - AZ_Assert(m_bindingComponent, "Entity binding is invalid!"); - - m_spawnInfo.Modify([&](SpawnInfo& spawnInfo) - { - spawnInfo.m_runtimeEntityId = static_cast(m_bindingComponent->GetEntity()->GetId()); - - bool isProceduralEntity = true; - AZ::SliceComponent::SliceInstanceAddress sliceInfo; - - EntityContextId contextId = EntityContextId::CreateNull(); - const AZ::EntityId bindingComponentEntityId = m_bindingComponent->GetEntityId(); - EntityIdContextQueryBus::EventResult(contextId, bindingComponentEntityId, - &EntityIdContextQueryBus::Events::GetOwningContextId); - if (!contextId.IsNull()) - { - EBUS_EVENT_RESULT(spawnInfo.m_owningContextId, NetBindingSystemBus, GetCurrentContextSequence); - SliceEntityRequestBus::EventResult(sliceInfo, bindingComponentEntityId, - &SliceEntityRequestBus::Events::GetOwningSlice); - bool isDynamicSliceEntity = sliceInfo.IsValid(); - - isProceduralEntity = !m_bindingComponent->IsLevelSliceEntity() && !isDynamicSliceEntity; - } - - if (isProceduralEntity) - { - // write cloning info - AZ::SerializeContext* sc = nullptr; - EBUS_EVENT_RESULT(sc, AZ::ComponentApplicationBus, GetSerializeContext); - AZ_Assert(sc, "Can't find SerializeContext!"); - AZ::IO::ByteContainerStream> spawnDataStream(&spawnInfo.m_serializedState); - AZ::ObjectStream* objStream = AZ::ObjectStream::Create(&spawnDataStream, *sc, AZ::DataStream::ST_BINARY); - objStream->WriteClass(m_bindingComponent->GetEntity()); - objStream->Finalize(); - } - else - { - // write slice info - if (sliceInfo.IsValid()) - { - AZ::Data::AssetId sliceAssetId = sliceInfo.GetReference()->GetSliceAsset().GetId(); - spawnInfo.m_sliceAssetId = AZStd::make_pair(sliceAssetId.m_guid, sliceAssetId.m_subId); - } - if (sliceInfo.GetInstance()) - { - spawnInfo.m_sliceInstanceId = sliceInfo.GetInstance()->GetId(); - } - - AZ::EntityId staticEntityId; - EBUS_EVENT_RESULT(staticEntityId, NetBindingSystemBus, GetStaticIdFromEntityId, m_bindingComponent->GetEntity()->GetId()); - spawnInfo.m_staticEntityId = static_cast(staticEntityId); - } - - return true; - }); - } - else - { - AZ::EntityId runtimeEntityId(m_spawnInfo.Get().m_runtimeEntityId); - NetBindingContextSequence owningContextId = m_spawnInfo.Get().m_owningContextId; - - //TODO Move to Filter Hook - // Reject and cancel sessions with duplicate MachineIds? - // Reject and cancel sessions with duplicate entity ID creation requests? - //Check MachineId collision - bool collision = AZ::Entity::GetProcessSignature() == (m_spawnInfo.Get().m_runtimeEntityId & 0xFFFFFFFF); - AZ_Error("GridMate", !collision, "Replica received with duplicate Entity Machine IDs. Ignoring"); - - if (!collision) - { - //Check EntityID collision - AZ::Entity* entity = nullptr; - EBUS_EVENT_RESULT(entity, AZ::ComponentApplicationBus, FindEntity, runtimeEntityId); - - /* - * Only false if no machine ID collision and no entity ID collision - * And the entity is already active, it's possible the entity already exists in deactivated state as a cache mechanism - */ - collision = (entity != nullptr) && (entity->GetState() == AZ::Entity::State::Active); - } - - /** - * Special case - static entities should not count as duplicates. - * Static entities are loaded with the level and will be bounded here. - */ - if (collision) - { - AZ::EntityId staticEntityId; - EBUS_EVENT_RESULT(staticEntityId, NetBindingSystemBus, GetStaticIdFromEntityId, runtimeEntityId); - if (staticEntityId == runtimeEntityId) - { - collision = false; - } - } - - if (!collision) //Ignore duplicate runtime entity IDs - { - if (m_spawnInfo.Get().ContainsSerializedState()) - { - // Spawn the entity from stream input data - AZ::IO::MemoryStream spawnData(m_spawnInfo.Get().m_serializedState.data(), m_spawnInfo.Get().m_serializedState.size()); - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromStream, spawnData, runtimeEntityId, GetReplicaId(), owningContextId); - } - else - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = owningContextId; - spawnContext.m_sliceAssetId = AZ::Data::AssetId(m_spawnInfo.Get().m_sliceAssetId.first, m_spawnInfo.Get().m_sliceAssetId.second); - spawnContext.m_runtimeEntityId = runtimeEntityId; - spawnContext.m_staticEntityId = AZ::EntityId(m_spawnInfo.Get().m_staticEntityId); - spawnContext.m_sliceInstanceId = m_spawnInfo.Get().m_sliceInstanceId; - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, GetReplicaId(), spawnContext); - } - } - else //Fail early to prevent unnecessary spawning of duplicate entity IDs - { - //Misconfiguration or potential cheating/DoS? - AZ_Warning("NetBinding", false, "Received duplicate Entity ID %llu. Ignoring.", runtimeEntityId); - } - } - } - - void NetBindingComponentChunk::OnReplicaDeactivate(const GridMate::ReplicaContext& rc) - { - (void)rc; - if (m_bindingComponent) - { - m_bindingComponent->UnbindFromNetwork(); - } - } - - bool NetBindingComponentChunk::AcceptChangeOwnership(GridMate::PeerId requestor, const GridMate::ReplicaContext& rc) - { - bool result = true; - - if (m_bindingComponent) - { - EBUS_EVENT_ID_RESULT(result, m_bindingComponent->GetEntityId(), NetBindingEventsBus, OnEntityAcceptChangeOwnership, requestor, rc); - } - - return result; - } - - void NetBindingComponentChunk::OnReplicaChangeOwnership(const GridMate::ReplicaContext& rc) - { - if (m_bindingComponent) - { - EBUS_EVENT_ID(m_bindingComponent->GetEntityId(), NetBindingEventsBus, OnEntityChangeOwnership, rc); - } - } -} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponentChunk.h b/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponentChunk.h deleted file mode 100644 index 5a0f023fa2..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponentChunk.h +++ /dev/null @@ -1,112 +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 AZFRAMEWORK_NET_BINDING_COMPONENT_CHUNK_H -#define AZFRAMEWORK_NET_BINDING_COMPONENT_CHUNK_H - -#include -#include -#include -#include -#include -#include -#include - -namespace AzFramework -{ - class NetBindingComponent; - class NetBindingComponentChunkDescriptor; - - /** - * NetBindingComponentChunk is the counterpart of NetBindingComponent on the network side. - * It contains entity spawn data. It is created by NetBindingComponent during network - * binding on the master and initiates entity creation and binding on the proxy side. - */ - class NetBindingComponentChunk - : public GridMate::ReplicaChunk - { - friend NetBindingComponent; - friend NetBindingComponentChunkDescriptor; - - public: - AZ_CLASS_ALLOCATOR(NetBindingComponentChunk, AZ::SystemAllocator, 0); - - static const char* GetChunkName() { return "NetBindingComponentChunk"; } - - NetBindingComponentChunk(); - - void SetBinding(NetBindingComponent* bindingComponent) { m_bindingComponent = bindingComponent; } - NetBindingComponent* GetBinding() const { return m_bindingComponent; } - - protected: - /////////////////////////////////////////////////////////////////////// - // ReplicaChunk - bool IsReplicaMigratable() override { return true; } - void OnReplicaActivate(const GridMate::ReplicaContext& rc) override; - void OnReplicaDeactivate(const GridMate::ReplicaContext& rc) override; - bool AcceptChangeOwnership(GridMate::PeerId requestor, const GridMate::ReplicaContext& rc) override; - void OnReplicaChangeOwnership(const GridMate::ReplicaContext& rc) override; - /////////////////////////////////////////////////////////////////////// - - NetBindingComponent* m_bindingComponent; - - class SpawnInfo - { - public: - class Marshaler - { - public: - void Marshal(GridMate::WriteBuffer& wb, const SpawnInfo& data); - void Unmarshal(SpawnInfo& data, GridMate::ReadBuffer& rb); - }; - - class Throttle - { - public: - //! Always return true because SpawnInfo never changes - bool WithinThreshold(const SpawnInfo&) const { return true; } - void UpdateBaseline(const SpawnInfo& baseline) { (void)baseline; } - }; - - SpawnInfo(); - - bool operator==(const SpawnInfo& rhs); - - bool ContainsSerializedState() const; - - /** - * \brief Same as m_staticEntityId on authoritative entity with master replica - */ - AZ::u64 m_runtimeEntityId; - NetBindingContextSequence m_owningContextId; - AZStd::vector m_serializedState; - - /** - * \brief EntityId of authoritative entity with master replica - */ - AZ::u64 m_staticEntityId; - - AZStd::pair m_sliceAssetId; - /** - * \brief uniquely identifies the slice instance that this entity is being replicated from - */ - AZ::SliceComponent::SliceInstanceId m_sliceInstanceId; - }; - - GridMate::DataSet m_spawnInfo; - GridMate::DataSet > m_bindMap; - }; - typedef AZStd::intrusive_ptr NetBindingComponentChunkPtr; -} // namespace AZ - -#endif // AZFRAMEWORK_NET_BINDING_COMPONENT_CHUNK_H -#pragma once diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingEventsBus.h b/Code/Framework/AzFramework/AzFramework/Network/NetBindingEventsBus.h deleted file mode 100644 index f3089947dc..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingEventsBus.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 AZFRAMEWORK_NET_BINDING_EVENTS_BUS_H -#define AZFRAMEWORK_NET_BINDING_EVENTS_BUS_H - -#include -#include -#include - -namespace AzFramework -{ - /** - * NetBindingEventsBus - * Throws networking related entity events - */ - class NetBindingEvents - : public AZ::EBusTraits - { - public: - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - typedef AZ::EntityId BusIdType; - - virtual ~NetBindingEvents() {} - - /** - * Called on authoritative(Master) entity when ownership of this entity is about to be transferred to another peer - * Returning false from this call will result in denying request for ownership transfer - */ - virtual bool OnEntityAcceptChangeOwnership(GridMate::PeerId requestor, const GridMate::ReplicaContext& rc) { (void)requestor; (void)rc; return true; } - - /** - * Called when ownership transfer of an entity is finished. - */ - virtual void OnEntityChangeOwnership(const GridMate::ReplicaContext& rc) { (void)rc; } - }; - - typedef AZ::EBus NetBindingEventsBus; -} // namespace AzFramework - -#endif // AZFRAMEWORK_NET_BINDING_EVENTS_BUS_H -#pragma once diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingHandlerBus.h b/Code/Framework/AzFramework/AzFramework/Network/NetBindingHandlerBus.h deleted file mode 100644 index 55fa4c0217..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingHandlerBus.h +++ /dev/null @@ -1,112 +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 AZFRAMEWORK_NET_BINDING_HANDLER_BUS_H -#define AZFRAMEWORK_NET_BINDING_HANDLER_BUS_H - -#include -#include -#include -#include -#include - -namespace AzFramework -{ - /** - * The NetBindingSystemComponent notifies net binding handlers of binding events on this bus. - * The net binding component implements this interface and listens on the NetBindingHandlerBus. - */ - class NetBindingHandlerInterface - : public AZ::EBusTraits - { - public: - AZ_RTTI(NetBindingHandlerInterface, "{9F84E9FE-81A0-4105-9C51-6C42C83FECAF}"); - - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - typedef AZ::EntityId BusIdType; - - virtual ~NetBindingHandlerInterface() {} - - /** - * Called to let the entity know that it should bind to the network. - * If bindTo is set, it means that the entity is a proxy and the handler - * should bind the entity to the specified - * replica, otherwise it should bind to a new replica and add it via - * NetBindingSystemBus::AddReplicaMaster. - */ - virtual void BindToNetwork(GridMate::ReplicaPtr bindTo) = 0; - - /** - * Called to let the entity know that it should unbind from the network. - */ - virtual void UnbindFromNetwork() = 0; - - /** - * Returns true if the entity is bound to the network. - */ - virtual bool IsEntityBoundToNetwork() = 0; - - /** - * Returns true if the entity is authoritative on the local node. - */ - virtual bool IsEntityAuthoritative() = 0; - - /** - * Flags the entity as part of the level slice. - */ - virtual void MarkAsLevelSliceEntity() = 0; - - /** - * Set the slice instance id that this entity was spawned by and belongs to. - */ - virtual void SetSliceInstanceId(const AZ::SliceComponent::SliceInstanceId& sliceInstanceId) = 0; - - /** - * Sets the Replica Priority - */ - virtual void SetReplicaPriority(GridMate::ReplicaPriority replicaPriority) = 0; - - /** - * Request entity ownership to a given peer (by default to local peer) - */ - virtual void RequestEntityChangeOwnership(GridMate::PeerId peerId = GridMate::InvalidReplicaPeerId) = 0; - - /** - * Gets the Replica Priority - */ - virtual GridMate::ReplicaPriority GetReplicaPriority() const = 0; - }; - typedef AZ::EBus NetBindingHandlerBus; - - /** - * Set of queries that might want to be made about the networking system - * mainly wraps up EBus calls to keep the implementing code a bit more readable - */ - class NetQuery - { - public: - AZ_RTTI(NetQuery, "{AA4C5699-889D-4A73-9AD2-53EB03D8BB99}"); - - virtual ~NetQuery() = default; - - static AZ_FORCE_INLINE bool IsEntityAuthoritative(AZ::EntityId entityId) - { - bool result = true; - EBUS_EVENT_ID_RESULT(result,entityId,NetBindingHandlerBus,IsEntityAuthoritative); - return result; - } - }; - -} // namespace AzFramework - -#endif // AZFRAMEWORK_NET_BINDING_HANDLER_BUS_H -#pragma once diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemBus.h b/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemBus.h deleted file mode 100644 index c26c6d6350..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemBus.h +++ /dev/null @@ -1,119 +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 - -#ifndef AZFRAMEWORK_NET_BINDING_SYSTEM_BUS_H -#define AZFRAMEWORK_NET_BINDING_SYSTEM_BUS_H - -#include -#include -#include -#include -#include -#include - -namespace AZ -{ - namespace IO - { - class GenericStream; - } -} - -namespace AzFramework -{ - const AZ::SliceComponent::SliceInstanceId UnspecifiedSliceInstanceId = AZ::Uuid::CreateNull(); - - /** - */ - typedef AZ::u32 NetBindingContextSequence; - const NetBindingContextSequence UnspecifiedNetBindingContextSequence = 0; - - /** - */ - struct NetBindingSliceContext - { - NetBindingContextSequence m_contextSequence; - AZ::Data::AssetId m_sliceAssetId; - AZ::EntityId m_staticEntityId; - AZ::EntityId m_runtimeEntityId; - /** - * \brief uniquely identifies the slice instance that this entity is being replicated from - */ - AZ::SliceComponent::SliceInstanceId m_sliceInstanceId; - }; - - /** - * The net binding system implements this interface and listens on the NetBindingSystemBus. - * - * Network binding is activated when OnNetworkSessionActivated event is received with the binding session, - * and is deactivated by the OnNetworkSessionDeactivated event. - */ - class NetBindingSystemInterface - : public AZ::EBusTraits - { - public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - virtual ~NetBindingSystemInterface() {} - - //! Returns true if a network session is available and entities should bind themselves to the network. - virtual bool ShouldBindToNetwork() = 0; - - //! Returns the current entity context sequence - virtual NetBindingContextSequence GetCurrentContextSequence() = 0; - - //! Get a level entity's static id. - virtual AZ::EntityId GetStaticIdFromEntityId(AZ::EntityId entity) = 0; - - //! Get a level entity's id based on the static id - virtual AZ::EntityId GetEntityIdFromStaticId(AZ::EntityId staticEntityId) = 0; - - //! Adds a bound replica to the network session as master. - virtual void AddReplicaMaster(AZ::Entity* entity, GridMate::ReplicaPtr replica) = 0; - - //! Spawn and bind an entity from a slice - virtual void SpawnEntityFromSlice(GridMate::ReplicaId bindTo, const NetBindingSliceContext& bindToContext) = 0; - - //! Spawn and bind an entity from stream - virtual void SpawnEntityFromStream(AZ::IO::GenericStream& spawnData, AZ::EntityId useEntityId, GridMate::ReplicaId bindTo, NetBindingContextSequence addToContext) = 0; - - //! De-spawn an entity: deactivates or removes the entity. - /** - * /note @sliceInstanceId is the slice instance that the entity belongs to. If it's a level entity, then this should be AZ::Uuid::CreateNull() - */ - virtual void UnbindGameEntity(AZ::EntityId entity, const AZ::SliceComponent::SliceInstanceId& sliceInstanceId) = 0; - }; - typedef AZ::EBus NetBindingSystemBus; - - class NetBindingSystemEvents - : public AZ::EBusTraits - { - public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - //! Notification that a network session is created - virtual void OnNetworkSessionCreated(GridMate::GridSession* session) { (void)session; } - - //! Notification that a network session is ready - virtual void OnNetworkSessionActivated(GridMate::GridSession* session) { (void)session; } - - //! Notification that a network session is no longer available - virtual void OnNetworkSessionDeactivated(GridMate::GridSession* session) { (void)session; } - }; - typedef AZ::EBus NetBindingSystemEventsBus; -} // namespace AzFramework - -#endif // AZFRAMEWORK_NET_BINDING_SYSTEM_BUS_H diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemComponent.cpp b/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemComponent.cpp deleted file mode 100644 index 85081d1637..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemComponent.cpp +++ /dev/null @@ -1,66 +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 - -namespace AzFramework -{ - NetBindingSystemComponent::NetBindingSystemComponent() - { - } - - NetBindingSystemComponent::~NetBindingSystemComponent() - { - } - - void NetBindingSystemComponent::Activate() - { - NetBindingSystemImpl::Init(); - } - - void NetBindingSystemComponent::Deactivate() - { - NetBindingSystemImpl::Shutdown(); - } - - void NetBindingSystemComponent::Reflect(AZ::ReflectContext* context) - { - NetBindingSystemImpl::Reflect(context); - - if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ; - - if (AZ::EditContext* editContext = serializeContext->GetEditContext()) - { - editContext->Class( - "NetBinding System", "Performs network binding for game entities.") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Engine") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System", 0xc94d118b)) - ; - } - } - } - - void NetBindingSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("NetBindingSystemService", 0xa0ad6656)); - } - - void NetBindingSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("NetBindingSystemService", 0xa0ad6656)); - } -} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemComponent.h b/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemComponent.h deleted file mode 100644 index 03ff6aa86f..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemComponent.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. -* -*/ - -#ifndef AZFRAMEWORK_NET_BINDING_SYSTEM_COMPONENT_H -#define AZFRAMEWORK_NET_BINDING_SYSTEM_COMPONENT_H - -#include -#include - -namespace AZ -{ - class ReflectContext; -} - -namespace AzFramework -{ - /** - * NetBindingSystemComponent exposes NetBindingSystemImpl as a component - */ - class NetBindingSystemComponent - : public AZ::Component - , public NetBindingSystemImpl - { - friend class NetBindingSystemContextData; - public: - AZ_COMPONENT(NetBindingSystemComponent, "{B96548CC-0866-4BB3-A87B-BF0C4F69E8AC}"); - - NetBindingSystemComponent(); - ~NetBindingSystemComponent() override; - - ////////////////////////////////////////////////////////////////////////// - // Component overrides - void Activate() override; - void Deactivate() override; - static void Reflect(AZ::ReflectContext* context); - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); - ////////////////////////////////////////////////////////////////////////// - }; -} // namespace AzFramework - -#endif // AZFRAMEWORK_NET_BINDING_SYSTEM_COMPONENT_H -#pragma once - diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemImpl.cpp b/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemImpl.cpp deleted file mode 100644 index bb40432ffb..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemImpl.cpp +++ /dev/null @@ -1,957 +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 -#include -#include -#include - -//#define Extra_Tracing -#undef Extra_Tracing - -#if defined(Extra_Tracing) -#include -#define AZ_ExtraTracePrintf(window, ...) AZ::Debug::Trace::Instance().Printf(window, __VA_ARGS__); -#else -#define AZ_ExtraTracePrintf(window, ...) -#endif - -namespace AzFramework -{ - const AZStd::chrono::milliseconds NetBindingSystemImpl::s_sliceBindingTimeout = AZStd::chrono::milliseconds(5000); - - namespace - { - NetBindingHandlerInterface* GetNetBindingHandler(AZ::Entity* entity) - { - NetBindingHandlerInterface* handler = nullptr; - for (AZ::Component* component : entity->GetComponents()) - { - handler = azrtti_cast(component); - if (handler) - { - break; - } - } - return handler; - } - } - - NetBindingSliceInstantiationHandler::~NetBindingSliceInstantiationHandler() - { - // m_bindRequests in NetBindingSystemImpl could be cleaned before slice instantiation finished - if (m_state == State::Spawning) - { - AzFramework::SliceInstantiationResultBus::Handler::BusDisconnect(); - SliceGameEntityOwnershipServiceRequestBus::Broadcast( - &SliceGameEntityOwnershipServiceRequests::CancelDynamicSliceInstantiation, m_ticket - ); - } - - for (AZ::Entity* entity : m_boundEntities) - { - AZ_ExtraTracePrintf("NetBindingSystemImpl", "Cleanup - deleting %llu\n", entity->GetId()); - EBUS_EVENT(GameEntityContextRequestBus, DestroyGameEntity, entity->GetId()); - } - } - - void NetBindingSliceInstantiationHandler::InstantiateEntities() - { - if (m_sliceAssetId.IsValid()) - { - AZ_ExtraTracePrintf("NetBindingSystemImpl", "InstantiateEntities sliceid %s\n", - m_sliceInstanceId.ToString(false, false).c_str()); - - if (AZ::Data::AssetManager::IsReady()) - { - auto remapFunc = [bindingQueue=m_bindingQueue](AZ::EntityId originalId, bool /*isEntityId*/, const AZStd::function&) -> AZ::EntityId - { - auto iter = bindingQueue.find(originalId); - if (iter != bindingQueue.end()) - { - return iter->second.m_desiredRuntimeEntityId; - } - return AZ::Entity::MakeId(); - }; - - AZ::Data::Asset asset = AZ::Data::AssetManager::Instance().FindOrCreateAsset(m_sliceAssetId, AZ::Data::AssetLoadBehavior::Default); - - SliceGameEntityOwnershipServiceRequestBus::BroadcastResult(m_ticket, - &SliceGameEntityOwnershipServiceRequests::InstantiateDynamicSlice, asset, AZ::Transform::Identity(), remapFunc); - SliceInstantiationResultBus::Handler::BusConnect(m_ticket); - - m_state = State::Spawning; - } - else - { - AZ_Warning("NetBindingSystemImpl", false, "AssetManager was not ready when attempting to instantiate sliceid %s\n", - m_sliceInstanceId.ToString(false, false).c_str()); - InstantiationFailureCleanup(); - } - } - } - - bool NetBindingSliceInstantiationHandler::IsInstantiated() const - { - return m_state == State::Spawned; - } - - bool NetBindingSliceInstantiationHandler::IsANewSliceRequest() const - { - return m_state == State::NewRequest && m_sliceAssetId.IsValid() && !m_ticket.IsValid(); - } - - bool NetBindingSliceInstantiationHandler::IsBindingComplete() const - { - return !SliceInstantiationResultBus::Handler::BusIsConnected() && m_bindingQueue.empty(); - } - - bool NetBindingSliceInstantiationHandler::HasActiveEntities() const - { - for (const AZ::Entity* entity : m_boundEntities) - { - if (entity->GetState() == AZ::Entity::State::Active) - { - return true; - } - } - - return false; - } - - void NetBindingSliceInstantiationHandler::OnSlicePreInstantiate(const AZ::Data::AssetId& /*sliceAssetId*/, const AZ::SliceComponent::SliceInstanceAddress& sliceAddress) - { - const auto& entityMapping = sliceAddress.GetInstance()->GetEntityIdToBaseMap(); - - const AZ::SliceComponent::EntityList& sliceEntities = sliceAddress.GetInstance()->GetInstantiated()->m_entities; - for (AZ::Entity *sliceEntity : sliceEntities) - { - auto it = entityMapping.find(sliceEntity->GetId()); - AZ_Assert(it != entityMapping.end(), "Failed to retrieve static entity id for a slice entity!"); - const AZ::EntityId staticEntityId = it->second; - - auto itBindRecord = m_bindingQueue.find(staticEntityId); - if (itBindRecord != m_bindingQueue.end()) - { - AZ_Assert(GetNetBindingHandler(sliceEntity), "Slice entity matched the static id of replicated entity, but there is no valid NetBindingHandlerInterface on it!"); - - itBindRecord->second.m_actualRuntimeEntityId = sliceEntity->GetId(); - } - else if (GetNetBindingHandler(sliceEntity)) - { - AZ_ExtraTracePrintf("NetBindingSystemImpl", "OnSlicePreInstantiate late bindRequest, slice %s, staticid %llu, spawned %llu\n", - m_sliceInstanceId.ToString(false, false).c_str(), - static_cast(staticEntityId), - static_cast(sliceEntity->GetId())); - - BindRequest& request = m_bindingQueue[staticEntityId]; - request.m_desiredRuntimeEntityId = staticEntityId; - request.m_actualRuntimeEntityId = sliceEntity->GetId(); - request.m_requestTime = m_bindTime; - request.m_state = BindRequest::State::PlaceholderBind; - } - - sliceEntity->SetRuntimeActiveByDefault(false); - } - } - - void NetBindingSliceInstantiationHandler::OnSliceInstantiated(const AZ::Data::AssetId& /*sliceAssetId*/, const AZ::SliceComponent::SliceInstanceAddress& sliceAddress) - { - SliceInstantiationResultBus::Handler::BusDisconnect(); - - CloseEntityMap(sliceAddress.GetInstance()->GetEntityIdMap()); - - const AZ::SliceComponent::EntityList sliceEntities = sliceAddress.GetInstance()->GetInstantiated()->m_entities; - for (AZ::Entity *sliceEntity : sliceEntities) - { - auto it = sliceAddress.GetInstance()->GetEntityIdToBaseMap().find(sliceEntity->GetId()); - AZ_Assert(it != sliceAddress.GetInstance()->GetEntityIdToBaseMap().end(), "Failed to retrieve static entity id for a slice entity!"); - const AZ::EntityId staticEntityId = it->second; - const auto itUnbound = m_bindingQueue.find(staticEntityId); - if (itUnbound == m_bindingQueue.end()) - { - /* - * Remove entities that aren't meant to be net bounded. - */ - if (!GetNetBindingHandler(sliceEntity)) - { - EBUS_EVENT(GameEntityContextRequestBus, DestroyGameEntity, sliceEntity->GetId()); - continue; - } - } - - AZ_ExtraTracePrintf("NetBindingSystemImpl", "Adding %llu \n", sliceEntity->GetId()); - m_boundEntities.push_back(sliceEntity); - } - - m_state = State::Spawned; - } - - void NetBindingSliceInstantiationHandler::OnSliceInstantiationFailed(const AZ::Data::AssetId& sliceAssetId) - { - SliceInstantiationResultBus::Handler::BusDisconnect(); - - AZ_UNUSED(sliceAssetId); - AZ_TracePrintf("NetBindingSystemImpl", "Failed to instantiate a slice %s!", sliceAssetId.ToString().c_str()); - - InstantiationFailureCleanup(); - } - - void NetBindingSliceInstantiationHandler::InstantiationFailureCleanup() - { - m_boundEntities.clear(); - m_bindingQueue.clear(); - - // With m_bindingQueue empty, this slice instance handler will be removed on the next tick of NetBindingSystemImpl - m_state = State::Failed; - } - - void NetBindingSliceInstantiationHandler::UseCacheFor(BindRequest& request, const AZ::EntityId& staticEntityId) - { - AZ_Warning("NetBindingSystemImpl", !m_staticToRuntimeEntityMap.empty(), "An empty slice, really? static %llu", - static_cast(staticEntityId)); - - const auto actualRuntimeIter = m_staticToRuntimeEntityMap.find(staticEntityId); - if (actualRuntimeIter == m_staticToRuntimeEntityMap.end()) - { - AZ_Warning("NetBindingSystemImpl", false, "Wrong mapping, expected cache to have entity %llu for slice %s \n", - static_cast(staticEntityId), - m_sliceInstanceId.ToString(false, false).c_str()); - -#if defined(Extra_Tracing) - for (auto& item: m_staticToRuntimeEntityMap) - { - AZ_UNUSED(item); - AZ_ExtraTracePrintf("NetBindingSystemImpl", "mapping had %llu to %llu \n", - static_cast(item.first), - static_cast(item.second)); - } -#endif - - return; - } - - const AZ::EntityId actualRuntimeEntityId = actualRuntimeIter->second; - const auto itCache = AZStd::find_if(m_boundEntities.begin(), m_boundEntities.end(), [&actualRuntimeEntityId](AZ::Entity* entity) { - return entity->GetId() == actualRuntimeEntityId; - }); - - if (itCache != m_boundEntities.end()) - { - AZ_ExtraTracePrintf("NetBindingSystemImpl", "OnSlicePreInstantiate late bindRequest, slice %s, staticid %llu, spawned %llu\n", - m_sliceInstanceId.ToString(false, false).c_str(), - static_cast(staticEntityId), - static_cast(actualRuntimeEntityId)); - - request.m_actualRuntimeEntityId = actualRuntimeEntityId; - request.m_desiredRuntimeEntityId = staticEntityId; - } - else - { - AZ_Warning("NetBindingSystemImpl", false, "Expected cache to have entity %llu for slice %s \n", - static_cast(request.m_desiredRuntimeEntityId), - m_sliceInstanceId.ToString(false, false).c_str()); - } - } - - void NetBindingSliceInstantiationHandler::CloseEntityMap( - const AZ::SliceComponent::EntityIdToEntityIdMap& staticToRuntimeMap) - { - m_staticToRuntimeEntityMap.clear(); - for (auto& item : staticToRuntimeMap) - { - m_staticToRuntimeEntityMap[item.first] = item.second; - } - } - - NetBindingSystemContextData::NetBindingSystemContextData() - : m_bindingContextSequence("BindingContextSequence", UnspecifiedNetBindingContextSequence) - { - } - - void NetBindingSystemContextData::OnReplicaActivate(const GridMate::ReplicaContext& rc) - { - (void)rc; - NetBindingSystemImpl* system = static_cast(NetBindingSystemBus::FindFirstHandler()); - AZ_Assert(system, "NetBindingSystemContextData requires a valid NetBindingSystemComponent to function!"); - system->OnContextDataActivated(this); - } - - void NetBindingSystemContextData::OnReplicaDeactivate(const GridMate::ReplicaContext& rc) - { - (void)rc; - NetBindingSystemImpl* system = static_cast(NetBindingSystemBus::FindFirstHandler()); - if (system) - { - system->OnContextDataDeactivated(this); - } - } - - - NetBindingSystemImpl::NetBindingSystemImpl() - : m_bindingSession(nullptr) - , m_currentBindingContextSequence(UnspecifiedNetBindingContextSequence) - , m_isAuthoritativeRootSliceLoad(false) - , m_overrideRootSliceLoadAuthoritative(false) - { - } - - NetBindingSystemImpl::~NetBindingSystemImpl() - { - } - - void NetBindingSystemImpl::Init() - { - NetBindingSystemBus::Handler::BusConnect(); - NetBindingSystemEventsBus::Handler::BusConnect(); - - // Start listening for game context events - EntityContextId gameContextId = EntityContextId::CreateNull(); - EBUS_EVENT_RESULT(gameContextId, GameEntityContextRequestBus, GetGameEntityContextId); - if (!gameContextId.IsNull()) - { - EntityContextEventBus::Handler::BusConnect(gameContextId); - } - } - - void NetBindingSystemImpl::Shutdown() - { - EntityContextEventBus::Handler::BusDisconnect(); - NetBindingSystemEventsBus::Handler::BusDisconnect(); - NetBindingSystemBus::Handler::BusDisconnect(); - - m_contextData.reset(); - } - - bool NetBindingSystemImpl::ShouldBindToNetwork() - { - return m_contextData && m_contextData->ShouldBindToNetwork(); - } - - NetBindingContextSequence NetBindingSystemImpl::GetCurrentContextSequence() - { - return m_currentBindingContextSequence; - } - - bool NetBindingSystemImpl::ReadyToAddReplica() const - { - return m_bindingSession && m_bindingSession->GetReplicaMgr(); - } - - void NetBindingSystemImpl::AddReplicaMaster(AZ::Entity* entity, GridMate::ReplicaPtr replica) - { - bool addReplica = ShouldBindToNetwork(); - AZ_Assert(addReplica, "Entities shouldn't be binding to the network right now!"); - if (addReplica) - { - if (ReadyToAddReplica()) - { - m_bindingSession->GetReplicaMgr()->AddMaster(replica); - } - else - { - m_addMasterRequests.push_back(AZStd::make_pair(entity->GetId(), replica)); - } - } - } - - - AZ::EntityId NetBindingSystemImpl::GetStaticIdFromEntityId(AZ::EntityId entityId) - { - AZ::EntityId staticId = entityId; // if no static id mapping is found, then the static id is the same as the runtime id - - // If entity came from a slice, try to get the mapping from it - AZ::SliceComponent::SliceInstanceAddress sliceInfo; - SliceEntityRequestBus::EventResult(sliceInfo, entityId, &SliceEntityRequestBus::Events::GetOwningSlice); - AZ::SliceComponent::SliceInstance* sliceInstance = sliceInfo.GetInstance(); - if (sliceInstance) - { - const auto it = sliceInstance->GetEntityIdToBaseMap().find(entityId); - if (it != sliceInstance->GetEntityIdToBaseMap().end()) - { - staticId = it->second; - } - } - - return staticId; - } - - AZ::EntityId NetBindingSystemImpl::GetEntityIdFromStaticId(AZ::EntityId staticEntityId) - { - AZ::EntityId runtimeId = AZ::EntityId(); - - // if we can find an entity with the static id, then the static id is the same as the runtime id. - AZ::Entity* entity = nullptr; - EBUS_EVENT(AZ::ComponentApplicationBus, FindEntity, staticEntityId); - if (entity) - { - runtimeId = staticEntityId; - } - - return runtimeId; - } - - void NetBindingSystemImpl::SpawnEntityFromSlice(GridMate::ReplicaId bindTo, const NetBindingSliceContext& bindToContext) - { - auto& sliceQueue = m_bindRequests[bindToContext.m_contextSequence]; - - const bool slicePresent = sliceQueue.find(bindToContext.m_sliceInstanceId) != sliceQueue.end(); - - auto iterSliceRequest = sliceQueue.insert_key(bindToContext.m_sliceInstanceId); - NetBindingSliceInstantiationHandler& sliceHandler = iterSliceRequest.first->second; - sliceHandler.m_sliceAssetId = bindToContext.m_sliceAssetId; - sliceHandler.m_sliceInstanceId = bindToContext.m_sliceInstanceId; - - BindRequest& request = sliceHandler.m_bindingQueue[bindToContext.m_staticEntityId]; - - if (!slicePresent) - { - request.m_state = BindRequest::State::FirstBindInSlice; - } - else - { - request.m_state = BindRequest::State::LateBind; - } - - AZ_ExtraTracePrintf("NetBindingSystemImpl", "SpawnEntityFromSlice late, slice %s, static %llu, desired %llu, state %d \n", - bindToContext.m_sliceInstanceId.ToString(false, false).c_str(), - static_cast(bindToContext.m_staticEntityId), - static_cast(bindToContext.m_runtimeEntityId), - request.m_state); - - sliceHandler.m_bindTime = Now(); - - request.m_bindTo = bindTo; - request.m_desiredRuntimeEntityId = bindToContext.m_runtimeEntityId; - request.m_requestTime = Now(); - - if (sliceHandler.IsInstantiated()) - { - // The slice has been instantiated now, thus we have to use the cache to populated the request with the entity. - sliceHandler.UseCacheFor(request, bindToContext.m_staticEntityId); - } - } - - void NetBindingSystemImpl::SpawnEntityFromStream(AZ::IO::GenericStream& spawnData, AZ::EntityId useEntityId, GridMate::ReplicaId bindTo, NetBindingContextSequence addToContext) - { - auto& requestQueue = m_spawnRequests[addToContext]; - requestQueue.push_back(); - SpawnRequest& request = requestQueue.back(); - request.m_bindTo = bindTo; - request.m_useEntityId = useEntityId; - request.m_spawnDataBuffer.resize_no_construct(spawnData.GetLength()); - spawnData.Read(request.m_spawnDataBuffer.size(), request.m_spawnDataBuffer.data()); - } - - void NetBindingSystemImpl::OnNetworkSessionActivated(GridMate::GridSession* session) - { - AZ_Assert(!m_bindingSession, "We already have an active session! Was the previous session deactivated?"); - if (!m_bindingSession) - { - m_bindingSession = session; - - if (m_bindingSession->IsHost()) - { - GridMate::Replica* replica = CreateSystemReplica(); - session->GetReplicaMgr()->AddMaster(replica); - } - } - } - - void NetBindingSystemImpl::OnNetworkSessionDeactivated(GridMate::GridSession* session) - { - if (session == m_bindingSession) - { - m_bindingSession = nullptr; - } - } - - void NetBindingSystemImpl::UnbindGameEntity(AZ::EntityId entityId, const AZ::SliceComponent::SliceInstanceId& sliceInstanceId) - { - if (!m_bindRequests.empty()) - { - const auto itCurrentContextQueue = m_bindRequests.lower_bound(GetCurrentContextSequence()); - - if (itCurrentContextQueue != m_bindRequests.end()) - { - if (itCurrentContextQueue->first == GetCurrentContextSequence()) - { - const auto itSliceHandler = itCurrentContextQueue->second.find(sliceInstanceId); - if (itSliceHandler != itCurrentContextQueue->second.end()) - { - NetBindingSliceInstantiationHandler& sliceHandler = itSliceHandler->second; - for (AZ::Entity* entity : sliceHandler.m_boundEntities) - { - if (entity->GetId() == entityId) - { - entity->Deactivate(); - return; - } - } - - // clean any relevant bind requests as well - const auto bindQueueItem = sliceHandler.m_bindingQueue.find(entityId); - if (bindQueueItem != sliceHandler.m_bindingQueue.end()) - { - sliceHandler.m_bindingQueue.erase(bindQueueItem); - return; - } - } - } - } - } - - AZ_ExtraTracePrintf("NetBindingSystemImpl", "Not in cache - deleting %llu \n", entityId); - EBUS_EVENT(GameEntityContextRequestBus, DestroyGameEntity, entityId); - } - - void NetBindingSystemImpl::OnEntityContextReset() - { - const bool isContextOwner = m_contextData && m_contextData->IsMaster() && m_bindingSession && m_bindingSession->IsHost(); - if (isContextOwner) - { - ++m_currentBindingContextSequence; - NetBindingSystemContextData* context = static_cast(m_contextData.get()); - context->m_bindingContextSequence.Set(m_currentBindingContextSequence); - } - } - - bool NetBindingSystemImpl::IsAuthoritateLoad() const - { - if (m_overrideRootSliceLoadAuthoritative) - { - return m_isAuthoritativeRootSliceLoad; - } - - return !m_bindingSession || m_bindingSession->IsHost(); - } - - void NetBindingSystemImpl::UpdateClock(float deltaTime) - { - m_currentTime += AZStd::chrono::milliseconds(aznumeric_cast(deltaTime * AZStd::milli::den)); - } - - AZStd::chrono::system_clock::time_point NetBindingSystemImpl::Now() const - { - return m_currentTime; - } - - void NetBindingSystemImpl::OnEntityContextLoadedFromStream(const AZ::SliceComponent::EntityList& contextEntities) - { - const bool isAuthoritativeLoad = IsAuthoritateLoad(); - - for (AZ::Entity* entity : contextEntities) - { - NetBindingHandlerInterface* netBinder = GetNetBindingHandler(entity); - if (netBinder) - { - netBinder->MarkAsLevelSliceEntity(); - } - - if (!isAuthoritativeLoad && netBinder) - { - entity->SetRuntimeActiveByDefault(false); - - auto& slicesQueue = m_bindRequests[GetCurrentContextSequence()]; - auto& sliceHandler = slicesQueue[UnspecifiedSliceInstanceId]; - BindRequest& request = sliceHandler.m_bindingQueue[entity->GetId()]; - request.m_actualRuntimeEntityId = entity->GetId(); - request.m_requestTime = Now(); - } - } - } - - void NetBindingSystemImpl::OnTick(float deltaTime, AZ::ScriptTimePoint time) - { - AZ_UNUSED(time); - - UpdateClock(deltaTime); - UpdateContextSequence(); - -#if defined(Extra_Tracing) - static AZ::Debug::Timer sTimer; - sTimer.Stamp(); -#endif - ProcessBindRequests(); -#if defined(Extra_Tracing) - const float seconds = sTimer.StampAndGetDeltaTimeInSeconds(); - - static float debugPeriod = 2.f; - static float accumulator = 0; - static float totalTimeTaken = 0; - static AZ::u32 totalTicks = 0; - accumulator += deltaTime; - totalTimeTaken += seconds; - totalTicks++; - - if (accumulator >= debugPeriod) - { - AZ_ExtraTracePrintf("NetBindingSystemImpl", "ProcessBindRequests() took %f sec \n", totalTicks > 0 ? totalTimeTaken / totalTicks : 0); - - accumulator -= debugPeriod; - totalTimeTaken = 0; - totalTicks = 0; - } -#endif - - ProcessSpawnRequests(); - } - - int NetBindingSystemImpl::GetTickOrder() - { - return AZ::TICK_PLACEMENT + 1; - } - - void NetBindingSystemImpl::UpdateContextSequence() - { - NetBindingSystemContextData* contextChunk = static_cast(m_contextData.get()); - if (m_currentBindingContextSequence != contextChunk->m_bindingContextSequence.Get()) - { - m_currentBindingContextSequence = contextChunk->m_bindingContextSequence.Get(); - } - } - - GridMate::Replica* NetBindingSystemImpl::CreateSystemReplica() - { - AZ_Assert(m_bindingSession->IsHost(), "CreateSystemReplica should only be called on the host!"); - GridMate::Replica* replica = GridMate::Replica::CreateReplica("NetBindingSystem"); - NetBindingSystemContextData* contextChunk = GridMate::CreateReplicaChunk(); - replica->AttachReplicaChunk(contextChunk); - - return replica; - } - - void NetBindingSystemImpl::OnContextDataActivated(GridMate::ReplicaChunkPtr contextData) - { - AZ_Assert(!m_contextData, "We already have our context!"); - m_contextData = contextData; - - // Make sure we always have the unspecified entry. This should also - // be the lower_bound in the map and assuming it is always there - // makes things simpler. - m_spawnRequests.insert(UnspecifiedNetBindingContextSequence); - m_bindRequests.insert(UnspecifiedNetBindingContextSequence); - - if (contextData->IsMaster()) - { - ++m_currentBindingContextSequence; - static_cast(contextData.get())->m_bindingContextSequence.Set(m_currentBindingContextSequence); - } - else - { - UpdateContextSequence(); - } - AZ::TickBus::Handler::BusConnect(); - EBUS_EVENT(AzFramework::NetBindingHandlerBus, BindToNetwork, nullptr); - } - - void NetBindingSystemImpl::OnContextDataDeactivated(GridMate::ReplicaChunkPtr contextData) - { - AZ_Assert(m_contextData == contextData, "This is not our context!"); - m_contextData = nullptr; - - AZ::TickBus::Handler::BusDisconnect(); - m_spawnRequests.clear(); - m_bindRequests.clear(); - m_addMasterRequests.clear(); - m_currentBindingContextSequence = UnspecifiedNetBindingContextSequence; - } - - void NetBindingSystemImpl::ProcessSpawnRequests() - { - AZ::SerializeContext* serializeContext = nullptr; - EBUS_EVENT_RESULT(serializeContext, AZ::ComponentApplicationBus, GetSerializeContext); - AZ_Assert(serializeContext, "NetBindingSystemComponent requires a valid SerializeContext in order to spawn entities!"); - const auto spawnFunc = [=](SpawnRequest& spawnData, AZ::EntityId useEntityId, bool addToContext) - { - AZ::Entity* proxyEntity = nullptr; - AZ::ObjectStream::ClassReadyCB readyCB([&](void* classPtr, const AZ::Uuid& classId, AZ::SerializeContext* sc) - { - (void)classId; - (void)sc; - proxyEntity = static_cast(classPtr); - }); - AZ::IO::ByteContainerStream > stream(&spawnData.m_spawnDataBuffer); - AZ::ObjectStream::LoadBlocking(&stream, *serializeContext, readyCB); - - AZ_Warning("NetBindingSystemImpl", proxyEntity, "Could not spawn entity from stream %llu", useEntityId); - if (proxyEntity) - { - proxyEntity->SetId(useEntityId); - if (!BindAndActivate(proxyEntity, spawnData.m_bindTo, addToContext, AZ::Uuid::CreateNull())) - { - AzFramework::EntityContextId contextId = AzFramework::EntityContextId::CreateNull(); - AzFramework::EntityIdContextQueryBus::EventResult( - contextId, proxyEntity->GetId(), &AzFramework::EntityIdContextQueryBus::Events::GetOwningContextId); - - if (contextId.IsNull()) - { - delete proxyEntity; - } - else - { - GameEntityContextRequestBus::Broadcast( - &GameEntityContextRequestBus::Events::DestroyGameEntity, proxyEntity->GetId()); - } - - } - } - }; - - if (!m_spawnRequests.empty()) - { - SpawnRequestContextContainerType::iterator itContextQueue = m_spawnRequests.lower_bound(UnspecifiedNetBindingContextSequence); - AZ_Assert(itContextQueue->first == UnspecifiedNetBindingContextSequence, "We should always have the unspecified (aka global entity) spawn queue!");// - - // Process requests for global entities (not part of any context) - SpawnRequestContainerType& globalQueue = itContextQueue->second; - for (SpawnRequest& request : globalQueue) - { - spawnFunc(request, request.m_useEntityId, false); - } - globalQueue.clear(); - - if (GetCurrentContextSequence() != UnspecifiedNetBindingContextSequence) - { - ++itContextQueue; - - // Clear any obsolete requests (any contexts below the current context sequence) - SpawnRequestContextContainerType::iterator itCurrentContextQueue = m_spawnRequests.lower_bound(GetCurrentContextSequence()); - if (itContextQueue != itCurrentContextQueue) - { - m_spawnRequests.erase(itContextQueue, itCurrentContextQueue); - } - - // Spawn any entities for the current context - if (itCurrentContextQueue != m_spawnRequests.end()) - { - if (itCurrentContextQueue->first == GetCurrentContextSequence()) - { - for (SpawnRequest& request : itCurrentContextQueue->second) - { - spawnFunc(request, request.m_useEntityId, true); - } - itCurrentContextQueue->second.clear(); - } - } - } - } - } - - void NetBindingSystemImpl::ProcessBindRequests() - { - AZ::SerializeContext* serializeContext = nullptr; - EBUS_EVENT_RESULT(serializeContext, AZ::ComponentApplicationBus, GetSerializeContext); - AZ_Assert(serializeContext, "NetBindingSystemComponent requires a valid SerializeContext in order to spawn entities!"); - - if (!m_bindRequests.empty()) - { - BindRequestContextContainerType::iterator itContextQueue = m_bindRequests.lower_bound(UnspecifiedNetBindingContextSequence); - AZ_Assert(itContextQueue->first == UnspecifiedNetBindingContextSequence, "We should always have the unspecified/global spawn queue!"); - - if (GetCurrentContextSequence() != UnspecifiedNetBindingContextSequence) - { - ++itContextQueue; - - // Clear any obsolete requests (any contexts below the current context sequence) - BindRequestContextContainerType::iterator itCurrentContextQueue = m_bindRequests.lower_bound(GetCurrentContextSequence()); - if (itContextQueue != itCurrentContextQueue) - { - m_bindRequests.erase(itContextQueue, itCurrentContextQueue); - } - - // Spawn any proxy entities for the current context - if (itCurrentContextQueue != m_bindRequests.end()) - { - if (itCurrentContextQueue->first == GetCurrentContextSequence()) - { - for (auto itSliceHandler = itCurrentContextQueue->second.begin(); itSliceHandler != itCurrentContextQueue->second.end(); /*++itSliceHandler*/) - { - NetBindingSliceInstantiationHandler& sliceHandler = itSliceHandler->second; - - // If this is a new slice request, instantiate it - if (sliceHandler.IsANewSliceRequest()) - { - sliceHandler.InstantiateEntities(); - } - /* - * A slice instance is kept alive for caching purposes. As we check each bind request for its readiness, - * we are also going to check if the slice instance itself has become inactive and needs to be removed. - */ - bool mightBeInactiveSlice = true; - if (sliceHandler.m_bindingQueue.empty() && sliceHandler.HasActiveEntities()) - { - // The slice instance is spawned and full bound. - mightBeInactiveSlice = false; - } - - // If the entity is ready to be bound to the network, bind it. - // NOTE: It is possible for entities spawned from a slice containing multiple entities with net binding - // to never receive their replica counterpart, either because the replica was destroyed, or was interest - // filtered. We don't have a very good pipeline to prevent these slices from being authored, so if we - // encounter them, we will delete them after a timeout. - for (auto itRequest = sliceHandler.m_bindingQueue.begin(); itRequest != sliceHandler.m_bindingQueue.end(); /*++itRequest*/) - { - BindRequest& request = itRequest->second; - - if (request.m_bindTo != GridMate::InvalidReplicaId && request.m_actualRuntimeEntityId.IsValid()) - { - AZ::Entity* proxyEntity = nullptr; - EBUS_EVENT_RESULT(proxyEntity, AZ::ComponentApplicationBus, FindEntity, request.m_actualRuntimeEntityId); - AZ_Warning("NetBindingSystemImpl", proxyEntity, "Could not find entity for binding %llu", request.m_actualRuntimeEntityId); - if (proxyEntity) - { - AZ_ExtraTracePrintf("NetBindingSystemImpl", "BindAndActivate desired id %llu, actual %llu, slice %s \n", - static_cast(request.m_desiredRuntimeEntityId), - static_cast(request.m_actualRuntimeEntityId), - sliceHandler.m_sliceInstanceId.ToString(false, false).c_str()); - - BindAndActivate(proxyEntity, request.m_bindTo, false, sliceHandler.m_sliceInstanceId); - } - itRequest = sliceHandler.m_bindingQueue.erase(itRequest); - - // The slice instance is not fully bound. It may remain for a while for caching purposes. - mightBeInactiveSlice = false; - } - else if (AZStd::chrono::milliseconds(Now() - request.m_requestTime) > s_sliceBindingTimeout) - { - // If the real request never showed up, then no need for a trace - if (request.m_state == BindRequest::State::FirstBindInSlice || - request.m_state == BindRequest::State::LateBind) - { - AZ_TracePrintf("NetBindingSystemImpl", "Entity with static id [%llu], slice [%s]\n is still unbound after %llu ms. Discarding unbound entity.\n", - static_cast(request.m_actualRuntimeEntityId), - sliceHandler.m_sliceInstanceId.ToString(false, false).c_str(), - s_sliceBindingTimeout.count()); - } - - switch (sliceHandler.m_state) - { - case NetBindingSliceInstantiationHandler::State::NewRequest: - case NetBindingSliceInstantiationHandler::State::Spawning: - // The slice instance isn't ready yet. We will wait to consider the timing logic until it is ready. - mightBeInactiveSlice = false; - break; - case NetBindingSliceInstantiationHandler::State::Spawned: - case NetBindingSliceInstantiationHandler::State::Failed: - // Now the timing logic for removing the slice instance becomes valid. - mightBeInactiveSlice = true; - break; - default: - break; - } - - ++itRequest; - } - else - { - mightBeInactiveSlice = false; - ++itRequest; - } - } - - if (mightBeInactiveSlice && !sliceHandler.HasActiveEntities()) - { - AZ_ExtraTracePrintf("NetBindingSystemImpl", "Removing inactive slice %s \n", - sliceHandler.m_sliceInstanceId.ToString(false, false).c_str()); - - itSliceHandler = itCurrentContextQueue->second.erase(itSliceHandler); - } - else - { - ++itSliceHandler; - } - } - } - } - } - } - - // Spawn replicas for any local entities that are still valid - for (auto& addRequest : m_addMasterRequests) - { - AZ::Entity* entity = nullptr; - EBUS_EVENT_RESULT(entity, AZ::ComponentApplicationBus, FindEntity, addRequest.first); - if (entity) - { - m_bindingSession->GetReplicaMgr()->AddMaster(addRequest.second); - } - } - m_addMasterRequests.clear(); - } - - bool NetBindingSystemImpl::BindAndActivate(AZ::Entity* entity, GridMate::ReplicaId replicaId, bool addToContext, - const AZ::SliceComponent::SliceInstanceId& sliceInstanceId) - { - bool success = false; - - if ( ShouldBindToNetwork() ) - { - const GridMate::ReplicaPtr bindTo = m_contextData->GetReplicaManager()->FindReplica(replicaId); - if (bindTo) - { - if (addToContext) - { - EBUS_EVENT(GameEntityContextRequestBus, AddGameEntity, entity); - } - - if (entity->GetState() == AZ::Entity::State::Constructed) - { - entity->Init(); - } - - NetBindingHandlerInterface* binding = GetNetBindingHandler(entity); - AZ_Warning("NetBindingSystemImpl", binding, "Can't find NetBindingComponent on entity %llu (%s)!", static_cast(entity->GetId()), entity->GetName().c_str()); - if (binding) - { - binding->BindToNetwork(bindTo); - binding->SetSliceInstanceId(sliceInstanceId); - - entity->Activate(); - success = true; - } - } - else - { - // NOTE: It is possible for entities spawned from a slice containing multiple entities with net binding - // to never receive their replica counterpart, either because the replica was destroyed, or was interest - // filtered. - AZ_ExtraTracePrintf("NetBindingSystemImpl", "Failed to bind entity %llu - could not find replica %u", entity->GetId(), replicaId); - } - } - - return success; - } - - void NetBindingSystemImpl::Reflect(AZ::ReflectContext* context) - { - if (context) - { - // We need to register the chunk type, and this would be a good time to do so. - if (!GridMate::ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(GridMate::ReplicaChunkClassId(NetBindingSystemContextData::GetChunkName()))) - { - GridMate::ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - } - } - } -} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemImpl.h b/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemImpl.h deleted file mode 100644 index 543d9544ce..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemImpl.h +++ /dev/null @@ -1,311 +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 -#include -#include -#include - -namespace AzFramework -{ - /** - * \brief Represents a request to bind a particular replica to an entity - */ - class BindRequest - { - public: - BindRequest() - : m_bindTo(GridMate::InvalidReplicaId) - , m_state(State::None) - { - } - - GridMate::ReplicaId m_bindTo; - AZ::EntityId m_desiredRuntimeEntityId; - AZ::EntityId m_actualRuntimeEntityId; - AZStd::chrono::system_clock::time_point m_requestTime; - - /** - * \brief Represents the state of this bind request and it's relation to the slice instantiation process - */ - enum class State : AZ::u8 - { - None, - /** - * \brief This is the first request that led to instantiating a slice - */ - FirstBindInSlice, - /** - * \brief The request is a placeholder in case a real bind request arrives later. - * Some part of the slice may never be bound (e.g. if a replica is omitted by Interest Manager) - */ - PlaceholderBind, - /** - * \brief The real request did arrive to replace a placeholder request. - */ - LateBind, - }; - - State m_state; - }; - - typedef AZStd::unordered_map BindRequestContainerType; - - /** - * \brief Represents a slice instance being instantiated and bound to replicas - * \note It's possible that only some of the entities are activated and bound to replicas. - */ - class NetBindingSliceInstantiationHandler - : public SliceInstantiationResultBus::Handler - { - public: - ~NetBindingSliceInstantiationHandler() override; - - void InstantiateEntities(); - bool IsInstantiated() const; - bool IsANewSliceRequest() const; - bool IsBindingComplete() const; - - /** - * \note Returns false if there are no entities in the slice or the slice instance isn't ready yet. - * \return true if any of the entities from the slice are active - */ - bool HasActiveEntities() const; - - ////////////////////////////////////////////////////////////////////////// - // SliceInstantiationResultBus - void OnSlicePreInstantiate(const AZ::Data::AssetId& sliceAssetId, const AZ::SliceComponent::SliceInstanceAddress& sliceAddress) override; - void OnSliceInstantiated(const AZ::Data::AssetId& sliceAssetId, const AZ::SliceComponent::SliceInstanceAddress& sliceAddress) override; - void OnSliceInstantiationFailed(const AZ::Data::AssetId& sliceAssetId) override; - ////////////////////////////////////////////////////////////////////////// - - void InstantiationFailureCleanup(); - void UseCacheFor(BindRequest& request, const AZ::EntityId& staticEntityId); - void CloseEntityMap(const AZ::SliceComponent::EntityIdToEntityIdMap& staticToRuntimeMap); - - AZ::Data::AssetId m_sliceAssetId; - BindRequestContainerType m_bindingQueue; - SliceInstantiationTicket m_ticket; - - /** - * \breif a cache of entities that might be networked at some point - * \note they might be bound and unbound if their replicas leave and come back in the view - */ - AZStd::vector m_boundEntities; - - /** - * \brief identifies which slice instance the instantiation will be performed for - */ - AZ::SliceComponent::SliceInstanceId m_sliceInstanceId; - /** - * \brief when was the request to spawn a slice and bind it made - */ - AZStd::chrono::system_clock::time_point m_bindTime; - - AZ::SliceComponent::EntityIdToEntityIdMap m_staticToRuntimeEntityMap; - - /** - * \brief The state of the slice instance. - */ - enum class State - { - /** - * \brief Has not started instantiating the slice instance. - */ - NewRequest, - /** - * \brief Waiting on the slice to spawn. - */ - Spawning, - /** - * \brief Successfully spawned the slice assets. - */ - Spawned, - /** - * \brief Failed to spawn the slice. - */ - Failed - }; - - State m_state = State::NewRequest; - }; - - /** - * NetBindingSystemImpl works in conjunction with NetBindingComponent and - * NetBindingComponentChunk to perform network binding for game entities. - * - * It is responsible for adding entity replicas to the network on the master side - * and servicing entity spawn requests from the network on the proxy side, as - * well as detecting network availability and triggering network binding/unbinding. - * - * The system is first activated on the host side when OnNetworkSessionActivated event - * is received, and NetBindingSystemContextData is created. - * The system becomes fully operational when the NetBindingSystemContextData is activated - * and bound to the system, and remains operational as long as the NetBindingSystemContextData - * remains valid. - * - * Level switching is tracked by a monotonically increasing context sequence number controlled - * by the host. Spawn and bind operations are deferred until the correct sequence number - * is reached. Spawning is always performed from the game thread. - */ - class NetBindingSystemImpl - : public NetBindingSystemBus::Handler - , public NetBindingSystemEventsBus::Handler - , public EntityContextEventBus::Handler - , public AZ::TickBus::Handler - { - friend class NetBindingSystemContextData; - - public: - NetBindingSystemImpl(); - ~NetBindingSystemImpl() override; - - static void Reflect(AZ::ReflectContext* context); - - virtual void Init(); - virtual void Shutdown(); - - static const AZStd::chrono::milliseconds s_sliceBindingTimeout; - - ////////////////////////////////////////////////////////////////////////// - // NetBindingSystemBus - bool ShouldBindToNetwork() override; - NetBindingContextSequence GetCurrentContextSequence() override; - void AddReplicaMaster(AZ::Entity* entity, GridMate::ReplicaPtr replica) override; - AZ::EntityId GetStaticIdFromEntityId(AZ::EntityId entity) override; - AZ::EntityId GetEntityIdFromStaticId(AZ::EntityId staticEntityId) override; - void SpawnEntityFromSlice(GridMate::ReplicaId bindTo, const NetBindingSliceContext& bindToContext) override; - void SpawnEntityFromStream(AZ::IO::GenericStream& spawnData, AZ::EntityId useEntityId, GridMate::ReplicaId bindTo, NetBindingContextSequence addToContext) override; - void OnNetworkSessionActivated(GridMate::GridSession* session) override; - void OnNetworkSessionDeactivated(GridMate::GridSession* session) override; - void UnbindGameEntity(AZ::EntityId entity, const AZ::SliceComponent::SliceInstanceId& sliceInstanceId) override; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // EntityContextEventBus::Handler - void OnEntityContextReset() override; - void OnEntityContextLoadedFromStream(const AZ::SliceComponent::EntityList& contextEntities) override; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // TickBus::Handler - void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - int GetTickOrder() override; - ////////////////////////////////////////////////////////////////////////// - - protected: - //! Called by the NetBindingContext chunk when it is activated - void OnContextDataActivated(GridMate::ReplicaChunkPtr contextData); - - //! Called by the NetBindingContext chunk when it is deactivated - void OnContextDataDeactivated(GridMate::ReplicaChunkPtr contextData); - - //! Update the current binding context sequence - virtual void UpdateContextSequence(); - - //! Process pending spawn requests - virtual void ProcessSpawnRequests(); - - //! Process pending bind requests - virtual void ProcessBindRequests(); - - //! Performs final stage of entity spawning process - virtual bool BindAndActivate(AZ::Entity* entity, GridMate::ReplicaId replicaId, bool addToContext, const AZ::SliceComponent::SliceInstanceId& sliceInstanceId); - - //! Called on the host to spawn the net binding system replica - virtual GridMate::Replica* CreateSystemReplica(); - - AZ_FORCE_INLINE bool ReadyToAddReplica() const; - - class SpawnRequest - { - public: - GridMate::ReplicaId m_bindTo; - AZ::EntityId m_useEntityId; - AZStd::vector m_spawnDataBuffer; - }; - - typedef AZStd::list SpawnRequestContainerType; - typedef AZStd::map SpawnRequestContextContainerType; - - typedef AZStd::unordered_map SliceRequestContainerType; - typedef AZStd::map BindRequestContextContainerType; - - GridMate::GridSession* m_bindingSession; - GridMate::ReplicaChunkPtr m_contextData; - NetBindingContextSequence m_currentBindingContextSequence; - SpawnRequestContextContainerType m_spawnRequests; - BindRequestContextContainerType m_bindRequests; - AZStd::list> m_addMasterRequests; - - /** - * \brief override how root slice entities' replicas should be loaded - * - * We occasionally get GameContextBridge replica (that tells us what level to load) before we get - * a replica that tells us that we are connecting to a network sessions, thus we may not figure out in time if we - * need to load the root slice entities with NetBindingComponent as master replicas or proxy replicas. - * This is a fix until proper order is established. - * - * \param isAuthoritative true if root slice entities with NetBindingComponents to be loaded authoritatively - */ - void OverrideRootSliceLoadMode(bool isAuthoritative) - { - m_isAuthoritativeRootSliceLoad = isAuthoritative; - m_overrideRootSliceLoadAuthoritative = true; - } - - private: - /** - * \brief True if the root slice is to be loaded authoritatively - */ - bool m_isAuthoritativeRootSliceLoad; - /** - * \brief True if root slice loading mode was overriden, otherwise the mode would be determined via m_bindingSession - */ - bool m_overrideRootSliceLoadAuthoritative; - /** - * \brief A helper method to figure the mode of loading root slice entities' replicas - * \return True if the root slice entities is to be loaded authoritatively - */ - bool IsAuthoritateLoad() const; - - void UpdateClock(float deltaTime); - AZStd::chrono::system_clock::time_point Now() const; - - AZStd::chrono::system_clock::time_point m_currentTime; - }; - - class NetBindingSystemContextData - : public GridMate::ReplicaChunk - { - public: - AZ_CLASS_ALLOCATOR(NetBindingSystemContextData, AZ::SystemAllocator, 0); - - static const char* GetChunkName() { return "NetBindingSystemContextData"; } - - NetBindingSystemContextData(); - - bool IsReplicaMigratable() override { return true; } - bool IsBroadcast() override { return true; } - - void OnReplicaActivate(const GridMate::ReplicaContext& rc) override; - - void OnReplicaDeactivate(const GridMate::ReplicaContext& rc) override; - - GridMate::DataSet m_bindingContextSequence; - }; -} // namespace AzFramework - diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetSystemBus.h b/Code/Framework/AzFramework/AzFramework/Network/NetSystemBus.h deleted file mode 100644 index 788eacf8b5..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetSystemBus.h +++ /dev/null @@ -1,38 +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 NetworkContext; - - /** - * The NetSystemRequestBus services requests for global networking systems in AzFramework - */ - class NetSystemRequests - : public AZ::EBusTraits - { - public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - NetSystemRequests() = default; - virtual ~NetSystemRequests() = default; - - virtual NetworkContext* GetNetworkContext() = 0; - }; - - using NetSystemRequestBus = AZ::EBus; -} diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetworkContext.cpp b/Code/Framework/AzFramework/AzFramework/Network/NetworkContext.cpp deleted file mode 100644 index 98ef897d29..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetworkContext.cpp +++ /dev/null @@ -1,378 +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 - - -namespace AzFramework -{ - NetworkContext::DescBase::DescBase(const char* name, ptrdiff_t offset) - : m_name(name) - , m_offset(offset) - { - } - - NetworkContext::FieldDescBase::FieldDescBase(const char* name, ptrdiff_t offset) - : DescBase(name, offset) - , m_dataSetIdx(static_cast(-1)) - { - } - - NetworkContext::RpcDescBase::RpcDescBase(const char* name, ptrdiff_t offset) - : DescBase(name, offset) - , m_rpcIdx(static_cast(-1)) - { - } - - NetworkContext::CtorDataBase::CtorDataBase(const char* name) - : m_name(name) - { - } - - NetworkContext::ClassBuilder::ClassBuilder(NetworkContext* context, ClassDescPtr binding) - : m_binding(binding) - , m_context(context) - { - } - - NetworkContext::ClassBuilder::~ClassBuilder() - { - if (m_context->IsRemovingReflection()) - { - if (m_binding->UnregisterChunkType) - { - m_binding->UnregisterChunkType(); - } - } - else - { - if (m_binding->RegisterChunkType) - { - m_binding->RegisterChunkType(); - } - } - } - - NetworkContext::ClassDesc::ClassDesc(const char* name, const AZ::Uuid& typeId /* = AZ::Uuid() */) - : m_name(name) - , m_typeId(typeId) - { - } - - /////////////////////////////////////////////////////////////////////////// - /// NetworkContext - /////////////////////////////////////////////////////////////////////////// - NetworkContext::NetworkContext() - { - } - - NetworkContext::~NetworkContext() - { - } - - size_t NetworkContext::GetReflectedChunkSize(const AZ::Uuid& typeId) const - { - size_t totalSize = 0; - auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - ClassDescPtr binding = it->second; - for (const auto& field : binding->m_chunkDesc.m_fields) - { - totalSize += field->GetDataSetSize(); - } - - for (const auto& rpc : binding->m_chunkDesc.m_rpcs) - { - totalSize += rpc->GetRpcSize(); - } - } - - return totalSize; - } - - bool NetworkContext::UsesSelfAsChunk(const AZ::Uuid& typeId) const - { - auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - ClassDescPtr binding = it->second; - return !binding->m_chunkDesc.m_external && binding->m_chunkDesc.m_fields.size() > 0; - } - return false; - } - - bool NetworkContext::UsesExternalChunk(const AZ::Uuid& typeId) const - { - auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - ClassDescPtr binding = it->second; - return binding->m_chunkDesc.m_external && (AZ::u32(binding->m_chunkDesc.m_chunkId) != 0); - } - return false; - } - - ReplicaChunkBase* NetworkContext::CreateReplicaChunk(const AZ::Uuid& typeId) - { - const auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - const ClassDescPtr binding = it->second; - if (binding->CreateReplicaChunk) - { - ReplicaChunkDescriptor* descriptor = ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(binding->m_chunkDesc.m_chunkId); - AZ_Assert(descriptor, "NetworkContext cannot find replica chunk descriptor for %s. Did you remember to register the chunk type?", binding->m_name); - ReplicaChunkDescriptorTable::Get().BeginConstructReplicaChunk(descriptor); - ReplicaChunkBase* chunk = binding->CreateReplicaChunk(); - ReplicaChunkDescriptorTable::Get().EndConstructReplicaChunk(); - chunk->Init(descriptor); - return chunk; - } - } - - /* - * Special case: empty declarations such as: - * - * static void Reflect() { - * .... - * NetworkContext->Class(); - * } - * - * Result in no ReplicaChunks being created. It's treated as a no-op. No replication will be performed. - */ - return nullptr; - } - - void NetworkContext::DestroyReplicaChunk(ReplicaChunkBase* chunk) - { - ReplicaChunkClassId chunkId = chunk->GetDescriptor()->GetChunkTypeId(); - auto it = m_chunkBindings.find(chunkId); - if (it != m_chunkBindings.end()) - { - ClassDescPtr binding = it->second; - binding->DestroyReplicaChunk(chunk); - return; - } - - AZ_Warning("NetworkContext", false, "DestroyReplicaChunk could not find a binding for %s", chunk->GetDescriptor()->GetChunkName()); - } - - void NetworkContext::Bind(NetBindable* instance, ReplicaChunkPtr chunk, NetworkContextBindMode mode) - { - const AZ::Uuid& typeId = instance->RTTI_GetType(); - auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - ClassDescPtr binding = it->second; - if (chunk) - { - ReplicaChunkClassId chunkId = chunk->GetDescriptor()->GetChunkTypeId(); - AZ_Assert(binding->m_chunkDesc.m_chunkId == chunkId, "NetworkContext detected a type mismatch while trying to bind an instance to a ReplicaChunk"); - if (binding->m_chunkDesc.m_chunkId == chunkId) - { - if (!binding->m_chunkDesc.m_external) - { - ReflectedReplicaChunkBase* refChunk = static_cast(chunk.get()); - refChunk->Bind(instance, mode); - } - } - } - else - { - if (binding->BindRpcs) - { - binding->BindRpcs(instance); - } - } - } - } - - void NetworkContext::EnumerateFields(const ReplicaChunkClassId& chunkId, FieldVisitor visitor) const - { - auto it = m_chunkBindings.find(chunkId); - if (it != m_chunkBindings.end()) - { - const ChunkDesc& chunkDesc = it->second->m_chunkDesc; - for (const auto& field : chunkDesc.m_fields) - { - visitor(field.get()); - } - } - } - - void NetworkContext::EnumerateFields(const AZ::Uuid& typeId, FieldVisitor visitor) const - { - auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - const ChunkDesc& chunkDesc = it->second->m_chunkDesc; - for (const auto& field : chunkDesc.m_fields) - { - visitor(field.get()); - } - } - } - - void NetworkContext::EnumerateRpcs(const ReplicaChunkClassId& chunkId, RpcVisitor visitor) const - { - auto it = m_chunkBindings.find(chunkId); - if (it != m_chunkBindings.end()) - { - const ChunkDesc& chunkDesc = it->second->m_chunkDesc; - for (const auto& rpc : chunkDesc.m_rpcs) - { - visitor(rpc.get()); - } - } - } - - void NetworkContext::EnumerateRpcs(const AZ::Uuid& typeId, RpcVisitor visitor) const - { - auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - const ChunkDesc& chunkDesc = it->second->m_chunkDesc; - for (const auto& rpc : chunkDesc.m_rpcs) - { - visitor(rpc.get()); - } - } - } - - void NetworkContext::EnumerateCtorData(const ReplicaChunkClassId& chunkId, CtorVisitor visitor) const - { - auto it = m_chunkBindings.find(chunkId); - if (it != m_chunkBindings.end()) - { - const ChunkDesc& chunkDesc = it->second->m_chunkDesc; - for (const auto& ctor : chunkDesc.m_ctors) - { - visitor(ctor.get()); - } - } - } - - void NetworkContext::EnumerateCtorData(const AZ::Uuid& typeId, CtorVisitor visitor) const - { - auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - const ChunkDesc& chunkDesc = it->second->m_chunkDesc; - for (const auto& ctor : chunkDesc.m_ctors) - { - visitor(ctor.get()); - } - } - } - - /////////////////////////////////////////////////////////////////////////// - ReflectedReplicaChunkBase::ReflectedReplicaChunkBase() - : m_ctorBuffer(GridMate::EndianType::IgnoreEndian, 0) - { - } - - /////////////////////////////////////////////////////////////////////////// - NetworkContextChunkDescriptor::NetworkContextChunkDescriptor(const char* name, size_t size, const AZ::Uuid& typeId) - : ReplicaChunkDescriptor(name, size) - , m_typeId(typeId) - { - } - - ReplicaChunkBase* NetworkContextChunkDescriptor::CreateFromStream(UnmarshalContext& ctx) - { - AZ_Assert(!m_typeId.IsNull(), "No typeid associated with NetworkContextChunkDescriptor, cannot spawn Chunk"); - if (!m_typeId.IsNull()) - { - NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - AZ_Assert(netContext, "No NetworkContext found while trying to construct ReflectedReplicaChunk"); - - ReplicaChunkBase* replicaChunk = netContext->CreateReplicaChunk(m_typeId); - if (ctx.m_hasCtorData && ctx.m_iBuf) - { - NetworkContextChunkDescriptor* netChunkDesc = static_cast(replicaChunk->GetDescriptor()); - if (netChunkDesc->IsAuto()) - { - // copy each ctor data field into the ctor buffer - ReflectedReplicaChunkBase* refChunk = static_cast(replicaChunk); - netContext->EnumerateCtorData(m_typeId, - [&ctx, refChunk](NetworkContext::CtorDataBase* ctorData) - { - ctorData->Copy(*ctx.m_iBuf, refChunk->m_ctorBuffer); - }); - } - } - return replicaChunk; - } - return nullptr; - } - - void NetworkContextChunkDescriptor::DeleteReplicaChunk(ReplicaChunkBase* chunk) - { - NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - AZ_Assert(netContext, "No NetworkContext found while trying to destroy ReflectedReplicaChunk"); - netContext->DestroyReplicaChunk(chunk); - } - - void NetworkContextChunkDescriptor::MarshalCtorData(ReplicaChunkBase* chunk, WriteBuffer& buffer) - { - NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - AZ_Assert(netContext, "No NetworkContext found while trying to collect ctor data for ReflectedReplicaChunk"); - NetBindable* netBindable = static_cast(chunk->GetHandler()); - NetworkContextChunkDescriptor* netChunkDesc = static_cast(chunk->GetDescriptor()); - if (!netChunkDesc->IsAuto()) - { - return; - } - - if (netBindable) // chunk is bound, get source data from the netBindable - { - netContext->EnumerateCtorData(m_typeId, - [netBindable, &buffer](NetworkContext::CtorDataBase* ctorData) - { - ctorData->Marshal(netBindable, buffer); - }); - } - else // chunk is not bound yet, copy the ctor data for forwarding - { - ReflectedReplicaChunkBase* refChunk = static_cast(chunk); - ReadBuffer src(refChunk->m_ctorBuffer.GetEndianType(), refChunk->m_ctorBuffer.Get(), refChunk->m_ctorBuffer.Size()); - netContext->EnumerateCtorData(m_typeId, - [&src, &buffer](NetworkContext::CtorDataBase* ctorData) - { - ctorData->Copy(src, buffer); - }); - } - } - - void NetworkContextChunkDescriptor::DiscardCtorStream(UnmarshalContext& ctx) - { - NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - AZ_Assert(netContext, "No NetworkContext found while trying to skip ctor data for ReflectedReplicaChunk"); - if (ctx.m_hasCtorData) - { - // Iterate over all of the ctor data and unmarshal it with no destination, - // which will advance the buffer past the ctor data for this object - netContext->EnumerateCtorData(m_typeId, - [&ctx](NetworkContext::CtorDataBase* ctorData) - { - ctorData->Unmarshal(*ctx.m_iBuf, nullptr); - }); - } - } -} diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetworkContext.h b/Code/Framework/AzFramework/AzFramework/Network/NetworkContext.h deleted file mode 100644 index 5b6d420a79..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetworkContext.h +++ /dev/null @@ -1,969 +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 -#include - -#include -#include -#include -#include - -namespace AzFramework -{ - class NetBindable; - - using GridMate::ReplicaChunkInterface; - using GridMate::ReplicaChunkBase; - using GridMate::ReplicaChunk; - using GridMate::ReplicaChunkDescriptor; - using GridMate::DefaultReplicaChunkDescriptor; - using GridMate::ReplicaChunkDescriptorTable; - using GridMate::ReplicaChunkClassId; - using GridMate::ReplicaChunkPtr; - using GridMate::Rpc; - using GridMate::ZoneMask; - using GridMate::ZoneMask_All; - using GridMate::UnmarshalContext; - using GridMate::ReadBuffer; - using GridMate::WriteBuffer; - using GridMate::WriteBufferDynamic; - - /////////////////////////////////////////////////////////////////////////// - // GridMate ReplicaChunk/ReplicaChunkDescriptors - /////////////////////////////////////////////////////////////////////////// - class ReflectedReplicaChunkBase - : public ReplicaChunkBase - , public ReplicaChunkInterface - { - friend NetworkContext; - public: - ReflectedReplicaChunkBase(); - bool IsReplicaMigratable() override { return true; } - - /// Returns the chunk type name, e.g. "ReflectedReplicaChunk" - virtual const char* GetName() const = 0; - /// Returns the linear size of the chunk including DataSets and RPCs - virtual size_t GetSize() const = 0; - /// Returns a pointer to the start of the DataSet/RPC storage allocated with the chunk - virtual AZ::u8* GetDataStart() const = 0; - /// Binds an instance of the reflected class to this chunk - virtual void Bind(NetBindable* instance, NetworkContextBindMode mode) = 0; - /// Removes network bindings from the bound NetBindable - virtual void Unbind() = 0; - - WriteBufferDynamic m_ctorBuffer; ///< Buffer to hold ctor data before the chunk is bound - }; - - /// This will be the header for a blob in memory: - /// The layout looks like: - /// * ReflectedReplicaChunk - /// * DataSets - /// * RPCs - template - class ReflectedReplicaChunk - : public ReflectedReplicaChunkBase - { - friend NetworkContext; - public: - static const char* GetChunkName(); - static size_t GetChunkSize(); - - public: - AZ_CLASS_ALLOCATOR(ReflectedReplicaChunk, AZ::SystemAllocator, 0); - ReflectedReplicaChunk() - : m_dataSets(reinterpret_cast(this) + sizeof(*this)) - { - } - - const char* GetName() const override { return GetChunkName(); } - size_t GetSize() const override { return GetChunkSize(); } - AZ::u8* GetDataStart() const override { return const_cast(m_dataSets); } - void Bind(NetBindable* instance, NetworkContextBindMode mode) override; - void Unbind() override; - - private: - const AZ::u8* m_dataSets; ///< Points to the beginning of the datasets for this chunk - }; - - class NetworkContextChunkDescriptor - : public ReplicaChunkDescriptor - { - public: - NetworkContextChunkDescriptor(const char* name, size_t size, const AZ::Uuid& typeId = AZ::Uuid()); - - ReplicaChunkBase* CreateFromStream(UnmarshalContext& ctx) override; - void DeleteReplicaChunk(ReplicaChunkBase* chunkInstance) override; - void DiscardCtorStream(UnmarshalContext&) override; - void MarshalCtorData(ReplicaChunkBase*, WriteBuffer&) override; - - void Bind(const AZ::Uuid& typeId) { m_typeId = typeId; } - virtual bool IsAuto() const { return false; } - - private: - AZ::Uuid m_typeId; ///< TypeId of the class this descriptor represents (not the chunk type) - }; - - template - class AutoChunkDescriptor - : public NetworkContextChunkDescriptor - { - public: - AutoChunkDescriptor() - : NetworkContextChunkDescriptor(ReflectedReplicaChunk::GetChunkName(), ReflectedReplicaChunk::GetChunkSize(), AZ::RttiTypeId()) - { - } - - ZoneMask GetZoneMask() const override { return mask; } - - bool IsAuto() const override { return true; } - }; - - template - class ExternalChunkDescriptor - : public NetworkContextChunkDescriptor - { - public: - ExternalChunkDescriptor() - : NetworkContextChunkDescriptor(ChunkType::GetChunkName(), sizeof(ChunkType)) - {} - - ZoneMask GetZoneMask() const override { return mask; } - }; - - /////////////////////////////////////////////////////////////////////////// - /// NetworkContext can be used to reflect classes for network serialization - /// It will automatically generate ReplicaChunks and bind them to instances - /// when requested. It also serves as a binding registry for binding a class - /// to the ReplicaChunk that should be used to replicate it. - /////////////////////////////////////////////////////////////////////////// - class NetworkContext - : public AZ::ReflectContext - { - public: - /// @cond EXCLUDE_DOCS - class ClassBuilder; - class ClassDesc; - using ClassDescPtr = AZStd::intrusive_ptr; - using ClassBuilderPtr = AZStd::intrusive_ptr; - using ClassBindings = AZStd::unordered_map; - using ChunkBindings = AZStd::unordered_map; - using ClassInfo = ClassBuilder; ///< @deprecated Use NetworkContext::ClassBuilder - using ClassInfoPtr = ClassBuilderPtr; ///< @deprecated Use NetworkContext::ClassBuilderPtr - /// @endcond - - class IntrusiveRefCounted - { - public: - virtual ~IntrusiveRefCounted() {} - private: - // refcount - template - friend struct AZStd::IntrusivePtrCountPolicy; - mutable unsigned int m_refCount = 0; - AZ_FORCE_INLINE void add_ref() { ++m_refCount; } - AZ_FORCE_INLINE void release() - { - AZ_Assert(m_refCount > 0, "Reference count logic error, trying to remove reference when refcount is 0"); - if (--m_refCount == 0) - { - delete this; - } - } - }; - - /** - * Interface for recording classes, chunks, and datasets - * When destructed at the end of reflection, it will register/unregister the ChunkDescriptor - */ - class ClassBuilder - : public IntrusiveRefCounted - { - friend class NetworkContext; - - protected: - AZ_CLASS_ALLOCATOR(ClassBuilder, AZ::SystemAllocator, 0); - ClassBuilder(NetworkContext* context, ClassDescPtr binding); - - public: - ~ClassBuilder(); - ClassBuilderPtr operator->() { return this; } - - /// Bind a ReplicaChunk type to this class for network serialization - template > - ClassBuilderPtr Chunk(); - - /// Bind a NetBindable's Field - template - typename AZStd::enable_if::value, ClassBuilderPtr>::type - Field(const char* name, FieldType ClassType::* address); - - /// Declare an external chunk's DataSet - template - typename AZStd::enable_if::value, ClassBuilderPtr>::type - Field(const char* name, DataSetType ClassType::* address); - - /// Bind an Rpc::BindInterface for this chunk - template ::template BindInterface > - typename AZStd::enable_if::value, ClassBuilderPtr>::type - RPC(const char* name, RpcBindType ClassType::* rpc); - - /// Bind a NetBindable::Rpc for this NetBindable - template ::template Bind > - typename AZStd::enable_if::value, ClassBuilderPtr>::type - RPC(const char* name, RpcBindType ClassType::* rpc); - -#define CTOR_DATA_OVERLOAD(_getsig, _setsig) \ - template > \ - ClassBuilderPtr CtorData(const char* name, _getsig, _setsig, const MarshalerType&marshaler = MarshalerType()) \ - { \ - return CtorDataImpl(name, getter, setter, marshaler); \ - } - - /// Bind a getter/setter pair for data required during object construction - // this has to be done via overload so that the user does not have to explicitly provide - // the template arguments, they can be divined from the function call - CTOR_DATA_OVERLOAD(DataType(ClassType::* getter)(), void (ClassType::* setter)(const DataType&)); - CTOR_DATA_OVERLOAD(DataType(ClassType::* getter)() const, void (ClassType::* setter)(const DataType&)); - CTOR_DATA_OVERLOAD(DataType & (ClassType::* getter)(), void (ClassType::* setter)(const DataType&)); - CTOR_DATA_OVERLOAD(DataType & (ClassType::* getter)() const, void (ClassType::* setter)(const DataType&)); - CTOR_DATA_OVERLOAD(const DataType&(ClassType::* getter)(), void (ClassType::* setter)(const DataType&)); - CTOR_DATA_OVERLOAD(const DataType&(ClassType::* getter)() const, void (ClassType::* setter)(const DataType&)); - CTOR_DATA_OVERLOAD(DataType(ClassType::* getter)(), void (ClassType::* setter)(DataType)); - CTOR_DATA_OVERLOAD(DataType(ClassType::* getter)() const, void (ClassType::* setter)(DataType)); - CTOR_DATA_OVERLOAD(DataType & (ClassType::* getter)(), void (ClassType::* setter)(DataType)); - CTOR_DATA_OVERLOAD(DataType & (ClassType::* getter)() const, void (ClassType::* setter)(DataType)); - CTOR_DATA_OVERLOAD(const DataType&(ClassType::* getter)(), void (ClassType::* setter)(DataType)); - CTOR_DATA_OVERLOAD(const DataType&(ClassType::* getter)() const, void (ClassType::* setter)(DataType)); -#undef CTOR_DATA_OVERLOAD - - private: - template > - ClassBuilderPtr CtorDataImpl(const char* name, GetterFunction getter, SetterFunction setter, const MarshalerType& marshaler = MarshalerType()); - - private: - ClassDescPtr m_binding; - NetworkContext* m_context; - }; - - class DescBase - : public IntrusiveRefCounted - { - friend class NetworkContext; - public: - AZ_CLASS_ALLOCATOR(DescBase, AZ::SystemAllocator, 0); - DescBase(const char* name, ptrdiff_t offset); - virtual ~DescBase() {} - - const char* GetName() const { return m_name; } - ptrdiff_t GetOffset() const { return m_offset; } - protected: - const char* m_name; ///< Field name, will be used as DataSet debug name - ptrdiff_t m_offset; ///< Offset from an instance pointer (a ReplicaChunk or the actual class instance) - }; - - class FieldDescBase - : public DescBase - { - friend class NetworkContext; - - public: - AZ_CLASS_ALLOCATOR(FieldDescBase, AZ::SystemAllocator, 0); - FieldDescBase(const char* name, ptrdiff_t offset); - virtual ~FieldDescBase() {} - - virtual void ConstructDataSet(void*) const = 0; - virtual void DestructDataSet(void*) const = 0; - virtual size_t GetDataSetSize() const = 0; - - size_t GetDataSetIndex() const { return m_dataSetIdx; } - - protected: - size_t m_dataSetIdx; - }; - - /** - * Represents a DataSet in a chunk or class - * NOTE: m_offset in this class is the offset from ReplicaChunk* -> DataSet - */ - template - class DataSetDesc - : public FieldDescBase - { - public: - AZ_CLASS_ALLOCATOR(DataSetDesc, AZ::SystemAllocator, 0); - DataSetDesc(const char* name, ptrdiff_t offset); - - void ConstructDataSet(void*) const override {} - void DestructDataSet(void*) const override {} - size_t GetDataSetSize() const override { return sizeof(DataSetType); } - }; - - /** - * Represents a field in a chunk, responsible for creating a DataSet - * that represents the field - * NOTE: m_offset in this class is the offset from NetBindable* -> NetBindable::Field - */ - template - class NetBindableFieldDesc - : public FieldDescBase - { - public: - using DataSetType = typename FieldType::DataSetType; - - public: - AZ_CLASS_ALLOCATOR(NetBindableFieldDesc, AZ::SystemAllocator, 0); - NetBindableFieldDesc(const char* name, ptrdiff_t offset); - - void ConstructDataSet(void* mem) const override { FieldType::ConstructDataSet(mem, m_name); } - void DestructDataSet(void* mem) const override { FieldType::DestructDataSet(mem); } - size_t GetDataSetSize() const override { return sizeof(DataSetType); } - }; - - class RpcDescBase - : public DescBase - { - friend class NetworkContext; - public: - AZ_CLASS_ALLOCATOR(RpcDescBase, AZ::SystemAllocator, 0); - RpcDescBase(const char* name, ptrdiff_t offset); - virtual ~RpcDescBase() {} - - virtual void ConstructRpc(void*) const {} - virtual void DestructRpc(void*) const {} - virtual size_t GetRpcSize() const { return 0; } - - size_t GetRpcIndex() const { return m_rpcIdx; } - - protected: - size_t m_rpcIdx; - }; - - template - class NetBindableRpcDesc - : public RpcDescBase - { - friend class NetworkContext; - public: - AZ_CLASS_ALLOCATOR(NetBindableRpcDesc, AZ::SystemAllocator, 0); - NetBindableRpcDesc(const char* name, ptrdiff_t offset) - : RpcDescBase(name, offset) - { - static_assert((AZStd::is_base_of::value), "NetBindableRpcDesc is intended for use only with NetBindableRpcs"); - } - - void ConstructRpc(void* mem) const override { RpcBindType::ConstructRpc(mem, m_name); } - void DestructRpc(void* mem) const override { RpcBindType::DestructRpc(mem); } - size_t GetRpcSize() const override { return sizeof(typename RpcBindType::BindInterfaceType); } - }; - - class CtorDataBase - : public IntrusiveRefCounted - { - public: - AZ_CLASS_ALLOCATOR(CtorDataBase, AZ::SystemAllocator, 0); - CtorDataBase(const char* name); - virtual ~CtorDataBase() {} - - virtual void Marshal(NetBindable* netBindable, WriteBuffer& buffer) const = 0; - virtual void Unmarshal(ReadBuffer& buffer, NetBindable* netBindable) const = 0; - virtual void Copy(ReadBuffer& src, WriteBuffer& dest) const = 0; - - protected: - const char* m_name; - }; - - template - class CtorDataDesc - : public CtorDataBase - { - using GetterFunction = AZStd::function; - using SetterFunction = AZStd::function; - public: - AZ_CLASS_ALLOCATOR(CtorDataDesc, AZ::SystemAllocator, 0); - CtorDataDesc(const char* name, GetterFunction get, SetterFunction set) - : CtorDataBase(name) - , m_get(get) - , m_set(set) - {} - - CtorDataDesc(const char* name, DataType(ClassType::* getter)(), void (ClassType::* setter)(const DataType&)) - : CtorDataBase(name) - , m_get(AZStd::bind(getter, AZStd::placeholders::_1)) - , m_set(AZStd::bind(setter, AZStd::placeholders::_1, AZStd::placeholders::_2)) - {} - - void Marshal(NetBindable* netBindable, WriteBuffer& buffer) const override; - void Unmarshal(ReadBuffer& buffer, NetBindable* netBindable) const override; - virtual void Copy(ReadBuffer& src, WriteBuffer& dest) const override; - - GetterFunction m_get; - SetterFunction m_set; - MarshalerType m_marshaler; - }; - - struct ChunkDesc - { - public: - using Fields = AZStd::vector >; - using Rpcs = AZStd::vector >; - using Ctors = AZStd::vector >; - - const char* m_name = nullptr; ///< The name of the chunk - ReplicaChunkClassId m_chunkId; ///< The registered id of the ReplicaChunk this class will use - Fields m_fields; ///< list of data fields in the ReplicaChunk - Rpcs m_rpcs; ///< list of RPCs in the ReplicaChunk - Ctors m_ctors; ///< list of ctor callbacks to gather/apply ctor data - bool m_external = false; ///< If true, this chunk is separate from the class bound to it - }; - - /** - * Contains the chunk factory and field descriptions for a given class - */ - class ClassDesc - : public IntrusiveRefCounted - { - public: - - AZ_CLASS_ALLOCATOR(ClassDesc, AZ::SystemAllocator, 0); - ClassDesc(const char* name = nullptr, const AZ::Uuid& typeId = AZ::Uuid()); - - public: - const char* m_name; ///< The name of the class that is bound - AZ::Uuid m_typeId; ///< The type that this binding represents (null for chunks) - ChunkDesc m_chunkDesc; ///< Descriptor for the chunk for this type - - /// Functor which will register the ReplicaChunkDescriptor with the global registry - AZStd::function RegisterChunkType; - /// Functor to unregister the ReplicaChunkDescriptor (during reflection removal) - AZStd::function UnregisterChunkType; - /// Functor which will create a ReplicaChunk and bind it to the given instance - AZStd::function CreateReplicaChunk; - /// Functor which can destroy a ReplicaChunk and free its memory - AZStd::function DestroyReplicaChunk; - /// Functor which binds an instance of this class to its RPCs for local dispatch - AZStd::function BindRpcs; - }; - - AZ_CLASS_ALLOCATOR(NetworkContext, AZ::SystemAllocator, 0); - AZ_RTTI(NetworkContext, "{B1172D4A-EA1B-441D-AAE6-A9933DAECA8A}", AZ::ReflectContext); - - NetworkContext(); - virtual ~NetworkContext(); - - /// Register a class with the NetworkContext for replication - template - ClassBuilderPtr Class(); - - /// Create a replica chunk for a given class - ReplicaChunkBase* CreateReplicaChunk(const AZ::Uuid& typeId); - - /// Create a replica chunk for a given class, template version - template - ReplicaChunkBase* CreateReplicaChunk(); - - /// Destroy a replica chunk for a given class - void DestroyReplicaChunk(ReplicaChunkBase * chunk); - - /// Bind an instance and a chunk to each other - void Bind(NetBindable * instance, ReplicaChunkPtr chunk, NetworkContextBindMode mode); - - /// Returns whether or not a given type uses a reflected (automatic) ReplicaChunk - bool UsesSelfAsChunk(const AZ::Uuid & typeId) const; - - /// Returns whether or not a given type uses a custom ReplicaChunk - bool UsesExternalChunk(const AZ::Uuid & typeId) const; - - /// Return the size of the the chunk which will represent the given type - size_t GetReflectedChunkSize(const AZ::Uuid & typeId) const; - - using FieldVisitor = AZStd::function; - void EnumerateFields(const ReplicaChunkClassId&chunkId, FieldVisitor visitor) const; - void EnumerateFields(const AZ::Uuid & typeId, FieldVisitor visitor) const; - - using RpcVisitor = AZStd::function; - void EnumerateRpcs(const ReplicaChunkClassId&chunkId, RpcVisitor visitor) const; - void EnumerateRpcs(const AZ::Uuid & typeId, RpcVisitor visitor) const; - - using CtorVisitor = AZStd::function; - void EnumerateCtorData(const ReplicaChunkClassId&chunkId, CtorVisitor visitor) const; - void EnumerateCtorData(const AZ::Uuid & typeId, CtorVisitor visitor) const; - - private: - template - void InitReflectedChunkBinding(ClassDescPtr binding); - - template > - void InitExternalChunkBinding(ClassDescPtr binding); - - private: - ClassBindings m_classBindings; - ChunkBindings m_chunkBindings; - }; - - /////////////////////////////////////////////////////////////////////////// - template - NetworkContext::ClassBuilderPtr NetworkContext::Class() - { - static_assert((AZStd::is_base_of::value), "Classes reflected through NetworkContext must be derived from NetBindable"); - const AZ::Uuid& typeId = AZ::AzTypeInfo::Uuid(); - ClassDescPtr binding = nullptr; - if (IsRemovingReflection()) // Just remove the entire class definition - { - auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - binding = it->second; - m_chunkBindings.erase(binding->m_chunkDesc.m_chunkId); - m_classBindings.erase(it); - } - } - else - { - auto ret = m_classBindings.insert_key(typeId); - AZ_Assert(ret.second, "Cannot register more than one type with the same Uuid in the NetworkContext"); - binding = ret.first->second = aznew ClassDesc(AZ::AzTypeInfo::Name(), AZ::AzTypeInfo::Uuid()); - } - - return aznew ClassBuilder(this, binding); - } - - template - void NetworkContext::InitReflectedChunkBinding(ClassDescPtr binding) - { - if (!binding->RegisterChunkType) - { - binding->m_chunkDesc.m_name = ReflectedReplicaChunk::GetChunkName(); - ReplicaChunkClassId chunkClassId = ReplicaChunkClassId(binding->m_chunkDesc.m_name); - m_chunkBindings[chunkClassId] = binding; - NetworkContext* netContext = this; - - binding->RegisterChunkType = [chunkClassId, netContext]() - { - bool result = ReplicaChunkDescriptorTable::Get().RegisterChunkType, AutoChunkDescriptor >(); - ReplicaChunkDescriptor* desc = ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(chunkClassId); - ReplicaChunkDescriptorTable::Get().BeginConstructReplicaChunk(desc); - // The offset recorded in NetBindableFields is the offset in the NetBindable - // We must compute the offset of the generated DataSets here and record the - // index from the descriptor - ptrdiff_t offset = sizeof(ReflectedReplicaChunk); // data sets are right after the ReflectedReplicaChunk<> in memory - netContext->EnumerateFields(chunkClassId, - [desc, &offset](FieldDescBase* field) - { - desc->RegisterDataSet(field->m_name, offset); - field->m_dataSetIdx = desc->GetDataSetIndex(offset); - offset += field->GetDataSetSize(); - }); - netContext->EnumerateRpcs(chunkClassId, - [desc, &offset](RpcDescBase* rpc) - { - desc->RegisterRPC(rpc->m_name, offset); - rpc->m_rpcIdx = desc->GetRpcIndex(offset); - offset += rpc->GetRpcSize(); - }); - AZ_Assert(offset == static_cast(ReflectedReplicaChunk::GetChunkSize()), "Overflow/underflow while registering DataSets for %s", ReflectedReplicaChunk::GetChunkName()); - ReplicaChunkDescriptorTable::Get().EndConstructReplicaChunk(); - return result; - }; - - binding->UnregisterChunkType = [chunkClassId]() - { - ReplicaChunkDescriptorTable::Get().UnregisterReplicaChunkDescriptor(chunkClassId); - }; - - binding->CreateReplicaChunk = [netContext, chunkClassId]() - { - ReflectedReplicaChunkBase* chunk = new(azmalloc(ReflectedReplicaChunk::GetChunkSize(), AZStd::alignment_of >::value, AZ::SystemAllocator, ReflectedReplicaChunk::GetChunkName()))ReflectedReplicaChunk(); - AZ::u8* dataStart = chunk->GetDataStart(); - AZ::u8* dataEnd = reinterpret_cast(chunk) + chunk->GetSize(); - ptrdiff_t offset = 0; - netContext->EnumerateFields(chunkClassId, - [&offset, dataStart, dataEnd](FieldDescBase* field) - { - AZ_Assert((dataStart + offset) < dataEnd, "Overflow in NetworkContext::CreateReplicaChunk while creating %s", ReflectedReplicaChunk::GetChunkName()); - void* dataSetMem = reinterpret_cast(dataStart + offset); - field->ConstructDataSet(dataSetMem); - offset += field->GetDataSetSize(); - }); - netContext->EnumerateRpcs(chunkClassId, - [&offset, dataStart, dataEnd](RpcDescBase* rpc) - { - AZ_Assert((dataStart + offset) < dataEnd, "Overflow in NetworkContext::CreateReplicaChunk while creating %s", ReflectedReplicaChunk::GetChunkName()); - void* rpcMem = reinterpret_cast(dataStart + offset); - rpc->ConstructRpc(rpcMem); - offset += rpc->GetRpcSize(); - }); - AZ_Assert((dataStart + offset) == dataEnd, "Overflow/underflow in NetworkContext::CreateReplicaChunk while creating %s", ReflectedReplicaChunk::GetChunkName()); - return chunk; - }; - - binding->DestroyReplicaChunk = [netContext, chunkClassId](ReplicaChunkBase* chunkBase) - { - AZ_Assert(chunkBase->GetDescriptor()->GetChunkTypeId() == chunkClassId, "Mismatched chunk type id for %s (0x%p)", ReflectedReplicaChunk::GetChunkName(), chunkBase); - ReflectedReplicaChunkBase* chunk = static_cast(chunkBase); - chunk->Unbind(); - - AZ::u8* dataStart = chunk->GetDataStart(); - AZ::u8* dataEnd = reinterpret_cast(chunk) + chunk->GetSize(); - ptrdiff_t offset = 0; - netContext->EnumerateFields(chunkClassId, - [&offset, dataStart, dataEnd](FieldDescBase* field) - { - AZ_Assert((dataStart + offset) < dataEnd, "Overflow in dtor while destroying %s", ReflectedReplicaChunk::GetChunkName()); - void* dataSetMem = reinterpret_cast(dataStart + offset); - field->DestructDataSet(dataSetMem); - offset += field->GetDataSetSize(); - }); - netContext->EnumerateRpcs(chunkClassId, - [&offset, dataStart, dataEnd](RpcDescBase* rpc) - { - AZ_Assert((dataStart + offset) < dataEnd, "Overflow in NetworkContext::CreateReplicaChunk while creating %s", ReflectedReplicaChunk::GetChunkName()); - void* rpcMem = reinterpret_cast(dataStart + offset); - rpc->DestructRpc(rpcMem); - offset += rpc->GetRpcSize(); - }); - AZ_Assert((dataStart + offset) == dataEnd, "Overflow/underflow in dtor while destroying %s", ReflectedReplicaChunk::GetChunkName()); - chunk->~ReflectedReplicaChunkBase(); - azfree(chunk, AZ::SystemAllocator, ReflectedReplicaChunk::GetChunkSize(), AZStd::alignment_of >::value); - }; - - binding->BindRpcs = [netContext, chunkClassId](NetBindable* bindable) - { - ClassType* derivedInstance = static_cast(bindable); - netContext->EnumerateRpcs(chunkClassId, - [derivedInstance](const RpcDescBase* rpc) - { - NetBindableRpcBase* bindableRpc = reinterpret_cast(reinterpret_cast(derivedInstance) + rpc->GetOffset()); - bindableRpc->Bind(derivedInstance); - }); - }; - - binding->m_chunkDesc.m_chunkId = chunkClassId; - } - } - - template - void NetworkContext::InitExternalChunkBinding(ClassDescPtr binding) - { - if (!binding->RegisterChunkType) - { - binding->m_chunkDesc.m_name = ChunkType::GetChunkName(); - ReplicaChunkClassId chunkClassId = ReplicaChunkClassId(binding->m_chunkDesc.m_name); - m_chunkBindings[chunkClassId] = binding; - const AZ::Uuid& typeId = binding->m_typeId; - NetworkContext* netContext = this; - binding->RegisterChunkType = [chunkClassId, typeId, netContext]() - { - bool result = ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - NetworkContextChunkDescriptor* desc = static_cast(ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(chunkClassId)); - desc->Bind(typeId); - netContext->EnumerateFields(chunkClassId, - [desc](FieldDescBase* field) - { - desc->RegisterDataSet(field->m_name, field->m_offset); - field->m_dataSetIdx = desc->GetDataSetIndex(field->m_offset); - }); - netContext->EnumerateRpcs(chunkClassId, - [desc](RpcDescBase* rpc) - { - desc->RegisterRPC(rpc->m_name, rpc->m_offset); - }); - return result; - }; - - binding->UnregisterChunkType = [chunkClassId]() - { - return ReplicaChunkDescriptorTable::Get().UnregisterReplicaChunkDescriptor(chunkClassId); - }; - - binding->CreateReplicaChunk = []() - { - return aznew ChunkType(); - }; - - binding->DestroyReplicaChunk = [](ReplicaChunkBase* chunk) - { - delete chunk; - }; - - binding->m_chunkDesc.m_chunkId = chunkClassId; - } - } - - template - ReplicaChunkBase* NetworkContext::CreateReplicaChunk() - { - return CreateReplicaChunk(AZ::AzTypeInfo::Uuid()); - } - - /////////////////////////////////////////////////////////////////////////// - template - NetworkContext::DataSetDesc::DataSetDesc(const char* name, ptrdiff_t offset) - : NetworkContext::FieldDescBase(name, offset) - { - } - - /////////////////////////////////////////////////////////////////////////// - template - NetworkContext::NetBindableFieldDesc::NetBindableFieldDesc(const char* name, ptrdiff_t offset) - : NetworkContext::FieldDescBase(name, offset) - { - } - - /////////////////////////////////////////////////////////////////////////// - template - void NetworkContext::CtorDataDesc::Marshal(NetBindable* netBindable, WriteBuffer& buffer) const - { - ClassType* instance = static_cast(netBindable); - DataType data = m_get(instance); - buffer.Write(data, m_marshaler); - } - - template - void NetworkContext::CtorDataDesc::Unmarshal(ReadBuffer& buffer, NetBindable* netBindable) const - { - ClassType* instance = static_cast(netBindable); - DataType data; - buffer.Read(data, m_marshaler); - if (instance) - { - m_set(instance, data); - } - } - - template - void NetworkContext::CtorDataDesc::Copy(ReadBuffer& src, WriteBuffer& dest) const - { - DataType data; - src.Read(data, m_marshaler); - dest.Write(data, m_marshaler); - } - - /////////////////////////////////////////////////////////////////////////// - template - NetworkContext::ClassBuilderPtr NetworkContext::ClassBuilder::Chunk() - { - if (!m_context->IsRemovingReflection()) - { - static_assert((AZStd::is_base_of::value), "ReplicaChunks being registered with the NetworkContext must derive from ReplicaChunk"); - static_assert((AZStd::is_base_of::value), "Chunk bindings via NetworkContext must use a NetworkContextChunkDescriptor derived descriptor"); - AZ_Assert(!m_binding->m_typeId.IsNull(), "Cannot register a ReplicaChunk for a class which has not been declared to the NetworkContext"); - AZ_Assert(!m_binding->m_chunkDesc.m_chunkId, "Cannot register more than one ReplicaChunk binding for a class in the NetworkContext"); - - m_context->InitExternalChunkBinding(m_binding); - m_binding->m_chunkDesc.m_external = true; - } - return this; - } - - template - typename AZStd::enable_if::value, NetworkContext::ClassBuilderPtr>::type - NetworkContext::ClassBuilder::Field(const char* name, FieldType ClassType::* address) - { - if (!m_context->IsRemovingReflection()) - { - AZ_Assert(!m_binding->m_typeId.IsNull(), "Cannot register a field for a class which has not been declared to the NetworkContext"); - AZ_Assert(!m_binding->m_chunkDesc.m_external, "Cannot register a NetBindable::Field from within an external chunk"); - - m_context->InitReflectedChunkBinding(m_binding); - ptrdiff_t offset = reinterpret_cast(&(reinterpret_cast(0)->*address)); - m_binding->m_chunkDesc.m_fields.push_back(aznew NetBindableFieldDesc(name, offset)); - } - - return this; - } - - template - typename AZStd::enable_if::value, NetworkContext::ClassBuilderPtr>::type - NetworkContext::ClassBuilder::Field(const char* name, DataSetType ClassType::* address) - { - if (!m_context->IsRemovingReflection()) - { - AZ_Assert(!m_binding->m_typeId.IsNull(), "Cannot register a field for a class which has not been declared to the NetworkContext"); - - ptrdiff_t offset = reinterpret_cast(&(reinterpret_cast(0)->*address)); - m_binding->m_chunkDesc.m_fields.push_back(aznew DataSetDesc(name, offset)); - } - - return this; - } - - template - typename AZStd::enable_if::value, NetworkContext::ClassBuilderPtr>::type - NetworkContext::ClassBuilder::RPC(const char* name, RpcBindType ClassType::* rpc) - { - if (!m_context->IsRemovingReflection()) - { - static_assert((AZStd::is_base_of::value), "Cannot bind an RPC call to an object which is not a ReplicaChunkInterface"); - AZ_Assert(!m_binding->m_typeId.IsNull(), "Cannot register an RPC for a class which has not been declared to the NetworkContext"); - - ptrdiff_t offset = reinterpret_cast(&(reinterpret_cast(0)->*rpc)); - m_binding->m_chunkDesc.m_rpcs.push_back(aznew RpcDescBase(name, offset)); - } - - return this; - } - - template - typename AZStd::enable_if::value, NetworkContext::ClassBuilderPtr>::type - NetworkContext::ClassBuilder::RPC(const char* name, RpcBindType ClassType::* rpc) - { - if (!m_context->IsRemovingReflection()) - { - static_assert((AZStd::is_base_of::value), "Cannot bind an RPC call to an object which is not a ReplicaChunkInterface"); - AZ_Assert(!m_binding->m_typeId.IsNull(), "Cannot register an RPC for a class which has not been declared to the NetworkContext"); - - m_context->InitReflectedChunkBinding(m_binding); - - ptrdiff_t offset = reinterpret_cast(&(reinterpret_cast(0)->*rpc)); - m_binding->m_chunkDesc.m_rpcs.push_back(aznew NetBindableRpcDesc(name, offset)); - } - - return this; - } - - template - NetworkContext::ClassBuilderPtr NetworkContext::ClassBuilder::CtorDataImpl(const char* name, GetterFunction getter, SetterFunction setter, const MarshalerType&) - { - if (!m_context->IsRemovingReflection()) - { - m_context->InitReflectedChunkBinding(m_binding); - - auto get = [getter](NetBindable* nb) -> DataType { return (*static_cast(nb).*getter)(); }; - auto set = [setter](NetBindable* nb, const DataType& data) { (*static_cast(nb).*setter)(data); }; - m_binding->m_chunkDesc.m_ctors.push_back(aznew CtorDataDesc(name, get, set)); - } - - return this; - } - - /////////////////////////////////////////////////////////////////////////// - template - const char* ReflectedReplicaChunk::GetChunkName() - { - static char name[128] = { 0 }; - if (!name[0]) - { - AZ::Internal::AzTypeInfoSafeCat(name, AZ_ARRAY_SIZE(name), "ReflectedReplicaChunk<"); - AZ::Internal::AzTypeInfoSafeCat(name, AZ_ARRAY_SIZE(name), AZ::AzTypeInfo::Name()); - AZ::Internal::AzTypeInfoSafeCat(name, AZ_ARRAY_SIZE(name), ">"); - } - return name; - } - - template - size_t ReflectedReplicaChunk::GetChunkSize() - { - static size_t chunkSize = 0; - if (chunkSize == 0) - { - NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - AZ_Assert(netContext, "No NetworkContext found while trying to compute chunk size"); - if (!netContext) - { - return 0; - } - chunkSize = sizeof(ReflectedReplicaChunk) + netContext->GetReflectedChunkSize(AZ::AzTypeInfo::Uuid()); - } - - return chunkSize; - } - - template - void ReflectedReplicaChunk::Bind(NetBindable* instance, NetworkContextBindMode mode) - { - SetHandler(instance); - ClassType* derivedInstance = azrtti_cast(instance); - AZ_Assert(derivedInstance, "Unable to convert NetBindable to %s", AZ::AzTypeInfo::Name()); - ReplicaChunkDescriptor* desc = GetDescriptor(); - NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - netContext->EnumerateFields(desc->GetChunkTypeId(), - [this, derivedInstance, desc, mode](NetworkContext::FieldDescBase* field) - { - NetBindableFieldBase* bindableField = reinterpret_cast(reinterpret_cast(derivedInstance) + field->GetOffset()); - DataSetBase* dataSet = desc->GetDataSet(this, field->GetDataSetIndex()); - bindableField->Bind(dataSet, mode); - }); - netContext->EnumerateRpcs(desc->GetChunkTypeId(), - [this, derivedInstance, desc](NetworkContext::RpcDescBase* rpc) - { - NetBindableRpcBase* bindableRpc = reinterpret_cast(reinterpret_cast(derivedInstance) + rpc->GetOffset()); - RpcBase* rpcBase = desc->GetRpc(this, rpc->GetRpcIndex()); - bindableRpc->Bind(rpcBase); - }); - - // Transfer any stored ctor data from the buffer -> NetBindable instance - if (m_ctorBuffer.Size() > 0) - { - ReadBuffer ctorBuffer(m_ctorBuffer.GetEndianType(), m_ctorBuffer.Get(), m_ctorBuffer.Size()); - netContext->EnumerateCtorData(desc->GetChunkTypeId(), - [instance, &ctorBuffer](NetworkContext::CtorDataBase* ctorData) - { - ctorData->Unmarshal(ctorBuffer, instance); - }); - } - } - - template - void ReflectedReplicaChunk::Unbind() - { - ReplicaChunkInterface* handler = GetHandler(); - if (!handler || handler == this) - { - return; - } - - NetBindable* netBindable = static_cast(handler); - ClassType* derivedInstance = azrtti_cast(netBindable); - AZ_Assert(derivedInstance, "Unable to convert NetBindable to %s. Have you forgotten to derive your component from AzFramework::NetBindable?", AZ::AzTypeInfo::Name()); - if (derivedInstance) - { - ReplicaChunkDescriptor* desc = GetDescriptor(); - NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - netContext->EnumerateFields(desc->GetChunkTypeId(), - [derivedInstance](NetworkContext::FieldDescBase* field) - { - NetBindableFieldBase* bindableField = reinterpret_cast(reinterpret_cast(derivedInstance) + field->GetOffset()); - bindableField->Bind(nullptr, NetworkContextBindMode::NonAuthoritative); - }); - netContext->EnumerateRpcs(desc->GetChunkTypeId(), - [derivedInstance](NetworkContext::RpcDescBase* rpc) - { - NetBindableRpcBase* bindableRpc = reinterpret_cast(reinterpret_cast(derivedInstance) + rpc->GetOffset()); - bindableRpc->Bind(derivedInstance); - }); - } - - // We have disconnected from the handler and erased any connections from DataFields or Rpcs - SetHandler(nullptr); - } -} // namespace AZ diff --git a/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.cpp b/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.cpp index 838ab0b6e2..30343b1322 100644 --- a/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.cpp @@ -26,12 +26,9 @@ #include #include -#include -#include #include -#include #include @@ -429,83 +426,60 @@ namespace AzFramework { LSV_BEGIN(lua, 1); - // calling format __index(table,key) - ScriptNetBindingTable* netBindingTable = reinterpret_cast(lua_touserdata(lua, lua_upvalueindex(1))); - - bool readValue = false; - - if (netBindingTable != nullptr) + AZ::ScriptContext::FromNativeContext(lua)->Error(AZ::ScriptContext::ErrorType::Warning, true, + "Property %s not found in entity table. Please push this property to your slice to avoid decrease in performance.", lua_tostring(lua, -1)); + int lookupKey = lua_gettop(lua); + + int lookupTable = lookupKey - 1; + // This is a slow function and it's made slow so we don't cache any extra data. + // This is done because this function will be called only the exported components + // and script are not in sync and we added new properties. + lua_getmetatable(lua, -2); // get the metatable which will be the top property table + int entityProperties = lua_gettop(lua); + if (lua_getmetatable(lua, -1) == 0) // get the metatable of the property which will be the original table { - AZ_Error("ScriptComponent",netBindingTable->GetScriptContext() != nullptr,"ScriptNetBindingTable is missing ScriptContext."); - AZ_Error("ScriptComponent",netBindingTable->GetScriptContext() == nullptr || netBindingTable->GetScriptContext()->NativeContext() == lua,"Trying to use a NetBindingTable in wrong lua context"); - - AZ::ScriptContext* scriptContext = netBindingTable->GetScriptContext(); - - if (scriptContext) - { - AZ::ScriptDataContext stackContext; - scriptContext->ReadStack(stackContext); - - readValue = netBindingTable->InspectTableValue(stackContext); - } + // we are looking at top level properties + lua_pushvalue(lua, -2); // copy the key + lua_rawget(lua, -2); // read the value } - - if (!readValue) + else { - AZ::ScriptContext::FromNativeContext(lua)->Error(AZ::ScriptContext::ErrorType::Warning, true, - "Property %s not found in entity table. Please push this property to your slice to avoid decrease in performance.", lua_tostring(lua, -1)); - int lookupKey = lua_gettop(lua); - - int lookupTable = lookupKey - 1; - // This is a slow function and it's made slow so we don't cache any extra data. - // This is done because this function will be called only the exported components - // and script are not in sync and we added new properties. - lua_getmetatable(lua, -2); // get the metatable which will be the top property table - int entityProperties = lua_gettop(lua); - if (lua_getmetatable(lua, -1) == 0) // get the metatable of the property which will be the original table + // we are looking into the sub table, so do a slow traversal + int scriptProperties = lua_gettop(lua); + if (!Properties__IndexFindSubtable(lua, lookupTable, entityProperties, scriptProperties)) { - // we are looking at top level properties - lua_pushvalue(lua, -2); // copy the key - lua_rawget(lua, -2); // read the value + lua_pushnil(lua); + return 1; // we did not find the table } else { - // we are looking into the sub table, so do a slow traversal - int scriptProperties = lua_gettop(lua); - if (!Properties__IndexFindSubtable(lua, lookupTable, entityProperties, scriptProperties)) - { - lua_pushnil(lua); - return 1; // we did not find the table - } - else - { - lua_pushvalue(lua, lookupKey); - lua_rawget(lua, -2); - } + lua_pushvalue(lua, lookupKey); + lua_rawget(lua, -2); } + } - if (lua_istable(lua, -1)) + if (lua_istable(lua, -1)) + { + // if we are here the target table is on the top if the stack + lua_pushstring(lua, ScriptComponent::DefaultFieldName); + lua_rawget(lua, -2); + if (lua_isnil(lua, -1)) { - // if we are here the target table is on the top if the stack - lua_pushstring(lua, ScriptComponent::DefaultFieldName); - lua_rawget(lua, -2); - if (lua_isnil(lua, -1)) - { - // parent table is a group, pop the value and return the table - lua_pop(lua, 1); - } + // parent table is a group, pop the value and return the table + lua_pop(lua, 1); } + } - // Duplicate the value, so once the storage is done its on top of the stack, and returned - lua_pushvalue(lua, -1); + // Duplicate the value, so once the storage is done its on top of the stack, and returned + lua_pushvalue(lua, -1); - // Push key, and then move it below the value - lua_pushvalue(lua, lookupKey); - lua_insert(lua, -2); + // Push key, and then move it below the value + lua_pushvalue(lua, lookupKey); + lua_insert(lua, -2); + + // Cache the value so that subsequent accesses to this property don't result in warnings + lua_rawset(lua, lookupTable); - // Cache the value so that subsequent accesses to this property don't result in warnings - lua_rawset(lua, lookupTable); - } return 1; } //========================================================================= @@ -515,30 +489,7 @@ namespace AzFramework { LSV_BEGIN_VARIABLE(lua); - // calling format __newindex(table,key,value) - ScriptNetBindingTable* netBindingTable = reinterpret_cast(lua_touserdata(lua, lua_upvalueindex(1))); - if (netBindingTable != nullptr) - { - AZ_Error("ScriptContext",netBindingTable->GetScriptContext() != nullptr,"ScriptNetBindingTable is missing ScriptContext."); - AZ_Error("ScriptContext",netBindingTable->GetScriptContext() == nullptr || netBindingTable->GetScriptContext()->NativeContext() == lua,"Trying to use a NetBindingTable in wrong lua context"); - - AZ::ScriptContext* scriptContext = netBindingTable->GetScriptContext(); - if (scriptContext) - { - AZ::ScriptDataContext stackContext; - scriptContext->ReadStack(stackContext); - - const bool assignedValue = netBindingTable->AssignTableValue(stackContext); - if (assignedValue) - { - LSV_END_VARIABLE(0); - return 0; - } - } - } - - // If we didn't assign the value above, we want - // to raw set the value to avoid coming back in here. + // We want to raw set the value to avoid coming back in here. lua_rawset(lua, 1); LSV_END_VARIABLE(-2); return 0; @@ -553,7 +504,6 @@ namespace AzFramework // [8/9/2013] //========================================================================= - const char* ScriptComponent::NetRPCFieldName = "NetRPCs"; const char* ScriptComponent::DefaultFieldName = "default"; ScriptComponent::ScriptComponent() @@ -561,7 +511,6 @@ namespace AzFramework , m_contextId(AZ::ScriptContextIds::DefaultScriptContextId) , m_script(AZ::Data::AssetLoadBehavior::PreLoad) , m_table(LUA_NOREF) - , m_netBindingTable(nullptr) { m_properties.m_name = "Properties"; } @@ -573,8 +522,6 @@ namespace AzFramework ScriptComponent::~ScriptComponent() { m_properties.Clear(); - - delete m_netBindingTable; } //========================================================================= @@ -604,11 +551,6 @@ namespace AzFramework return m_properties.GetProperty(propertyName); } - const AZ::ScriptProperty* ScriptComponent::GetNetworkedScriptProperty(const char* propertyName) const - { - return m_netBindingTable->FindScriptProperty(propertyName); - } - void ScriptComponent::Init() { // Grab the script context @@ -622,11 +564,6 @@ namespace AzFramework //========================================================================= void ScriptComponent::Activate() { - if (m_isSyncEnabled && m_netBindingTable == nullptr) - { - m_netBindingTable = aznew ScriptNetBindingTable(); - } - // if we have valid asset listen for script asset events, like reload if (m_script.GetId().IsValid()) { @@ -681,43 +618,6 @@ namespace AzFramework LoadScript(); } - //========================================================================= - // ScriptComponent::GetNetworkBinding - //========================================================================= - GridMate::ReplicaChunkPtr ScriptComponent::GetNetworkBinding() - { - if (m_netBindingTable == nullptr) - { - m_netBindingTable = aznew ScriptNetBindingTable(); - } - - return m_netBindingTable->GetNetworkBinding(); - } - - //========================================================================= - // ScriptComponent::SetNetworkBinding - //========================================================================= - void ScriptComponent::SetNetworkBinding(GridMate::ReplicaChunkPtr chunk) - { - if (m_netBindingTable == nullptr) - { - m_netBindingTable = aznew ScriptNetBindingTable(); - } - - m_netBindingTable->SetNetworkBinding(chunk); - } - - //========================================================================= - // ScriptComponent::UnbindFromNetwork - //========================================================================= - void ScriptComponent::UnbindFromNetwork() - { - if (m_netBindingTable) - { - m_netBindingTable->UnbindFromNetwork(); - } - } - //========================================================================= // LoadScript //========================================================================= @@ -741,11 +641,6 @@ namespace AzFramework AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::Script, "Unload: %s", m_script.GetHint().c_str()); DestroyEntityTable(); - - if (m_netBindingTable) - { - m_netBindingTable->Unload(); - } } //========================================================================= @@ -798,12 +693,10 @@ namespace AzFramework // set the __index so we can read values in case we change the script // after we export the component lua_pushliteral(lua, "__index"); - lua_pushlightuserdata(lua, m_netBindingTable); lua_pushcclosure(lua, &Internal::Properties__Index, 1); lua_rawset(lua, -3); lua_pushliteral(lua, "__newindex"); - lua_pushlightuserdata(lua, m_netBindingTable); lua_pushcclosure(lua, &Internal::Properties__NewIndex, 1); lua_rawset(lua, -3); } @@ -835,8 +728,7 @@ namespace AzFramework { const char* tableName = lua_tolstring(lua, -2, nullptr); if (strncmp(tableName, "__", 2) == 0 || // skip metatables - strcmp(tableName, propertyTableName) == 0 || // Skip the Properties table - strcmp(tableName, ScriptComponent::NetRPCFieldName) == 0) // Want to skip the RPC table as well + strcmp(tableName, propertyTableName) == 0) // Skip the Properties table { break; } @@ -904,13 +796,10 @@ namespace AzFramework } lua_createtable(lua, 0, 1); // Create entity table; - int entityStackIndex = lua_gettop(lua); + [[maybe_unused]] int entityStackIndex = lua_gettop(lua); // Stack: ScriptRootTable PropertiesTable EntityTable - // Create our network binding. - CreateNetworkBindingTable(baseStackIndex, entityStackIndex); - if (basePropertyTable > -1) // if property table exists { CreatePropertyGroup(m_properties, basePropertyTable, lua_gettop(lua), basePropertyTable, true); @@ -932,11 +821,6 @@ namespace AzFramework // Keep the entity table in the registry m_table = luaL_ref(lua, LUA_REGISTRYINDEX); - if (m_netBindingTable) - { - m_netBindingTable->FinalizeNetworkTable(m_context, m_table); - } - // call OnActivate lua_pushliteral(lua, "OnActivate"); lua_rawget(lua, baseStackIndex); // ScriptTable[OnActivate] @@ -993,18 +877,6 @@ namespace AzFramework } } - //========================================================================= - // CreateNetworkBindingTable - // [6/27/2016] - //========================================================================= - void ScriptComponent::CreateNetworkBindingTable(int baseStackIndex, int entityStackIndex) - { - if (m_netBindingTable) - { - m_netBindingTable->CreateNetworkBindingTable(m_context, baseStackIndex, entityStackIndex); - } - } - //========================================================================= // CreatePropertyGroup // [3/3/2014] @@ -1028,12 +900,10 @@ namespace AzFramework // Ensure that this instance of Properties table has the proper __index and __newIndex metamethods. lua_newtable(lua); // This new table will become the Properties instance metatable. Stack: ScriptRootTable PropertiesTable EntityTable "Properties" {} {} lua_pushliteral(lua, "__index"); // Stack: ScriptRootTable PropertiesTable EntityTable "Properties" {} {} __index - lua_pushlightuserdata(lua, m_netBindingTable); // Stack: ScriptRootTable PropertiesTable EntityTable "Properties" {} {} __index m_netBinding lua_pushcclosure(lua, &Internal::Properties__Index, 1); // Stack: ScriptRootTable PropertiesTable EntityTable "Properties" {} {} __index function lua_rawset(lua, -3); // Stack: ScriptRootTable PropertiesTable EntityTable "Properties" {} {__index=Internal::Properties__Index} lua_pushliteral(lua, "__newindex"); - lua_pushlightuserdata(lua, m_netBindingTable); lua_pushcclosure(lua, &Internal::Properties__NewIndex, 1); lua_rawset(lua, -3); // Stack: ScriptRootTable PropertiesTable EntityTable "Properties" {} {__index=Internal::Properties__Index __newindex=Internal::Properties__NewIndex} lua_setmetatable(lua, -2); // Stack: ScriptRootTable PropertiesTable EntityTable "Properties" {Meta{__index=Internal::Properties__Index __newindex=Internal::Properties__NewIndex} } @@ -1050,55 +920,6 @@ namespace AzFramework { AZ::ScriptProperty* prop = group.m_properties[i]; - if (m_netBindingTable != nullptr) - { - lua_pushlstring(lua, prop->m_name.c_str(), prop->m_name.length()); - lua_rawget(lua, propertyGroupTableIndex); - - // Stack: ... SomePropertyInThePropertiesTable. This may be any basic lua type (number, string, table etc) - if (lua_istable(lua, -1)) - { - bool isNetworkedProperty = false; - - AZ::ScriptDataContext stackContext; - - // If we find a table value. We want to inspect it for information. - if (m_context->ReadStack(stackContext)) - { - // check if the current property, which is a table, has a sub-table called "netSynched" - lua_pushliteral(lua, "netSynched"); // Stack: ... SomePropertyInThePropertiesTable netSynched - lua_rawget(lua, -2); // Stack: ... SomePropertyInThePropertiesTable NetSynchedSubTable/nil - if (stackContext.IsTable(-1)) - { - AZ::ScriptDataContext networkTableContext; - if (stackContext.InspectTable(-1, networkTableContext)) // Stack: ... SomePropertyInThePropertiesTable NetSynchedSubTable NetSynchedSubTable nil nil - { - // RegisterDataSet will make sure our __NewIndex function callback will be triggered whenever modifying netSynched Properties. - //isNetworkedProperty = true; - isNetworkedProperty = m_netBindingTable->RegisterDataSet(networkTableContext, prop); - } - } - - // Network binding table - lua_pop(lua, 1); // Stack: ... SomePropertyInThePropertiesTable - } - - // Pop this PropertiesTable's property - lua_pop(lua, 1); - - // If the property is networked, we don't want to copy it over into the table. - if (isNetworkedProperty) - { - continue; - } - } - else - { - // Remove the value we just pushed onto the stack - lua_pop(lua, 1); - } - } - lua_pushlstring(lua, prop->m_name.c_str(), prop->m_name.length()); if (prop->Write(*m_context)) { @@ -1157,7 +978,7 @@ namespace AzFramework return true; }; - serializeContext->Class() + serializeContext->Class() ->Version(3, converter) ->Field("ContextID", &ScriptComponent::m_contextId) ->Field("Properties", &ScriptComponent::m_properties) @@ -1174,8 +995,6 @@ namespace AzFramework AZ::ScriptProperties::Reflect(reflection); } } - - ScriptNetBindingTable::Reflect(reflection); } //========================================================================= diff --git a/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.h b/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.h index 4d15bc527d..8294f3849c 100644 --- a/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.h +++ b/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.h @@ -20,8 +20,6 @@ #include #include -#include - namespace AZ { class ScriptProperty; @@ -37,8 +35,6 @@ namespace AzToolsFramework namespace AzFramework { - class ScriptNetBindingTable; - struct ScriptCompileRequest; using WriteFunction = AZStd::function< AZ::Outcome(const ScriptCompileRequest&, AZ::IO::GenericStream& in, AZ::IO::GenericStream& out) >; @@ -92,15 +88,13 @@ namespace AzFramework class ScriptComponent : public AZ::Component , private AZ::Data::AssetBus::Handler - , public AzFramework::NetBindable { friend class AzToolsFramework::Components::ScriptEditorComponent; public: - static const char* NetRPCFieldName; static const char* DefaultFieldName; - AZ_COMPONENT(AzFramework::ScriptComponent, "{8D1BC97E-C55D-4D34-A460-E63C57CD0D4B}", NetBindable); + AZ_COMPONENT(AzFramework::ScriptComponent, "{8D1BC97E-C55D-4D34-A460-E63C57CD0D4B}", AZ::Component); /// \red ComponentDescriptor::Reflect static void Reflect(AZ::ReflectContext* reflection); @@ -116,7 +110,6 @@ namespace AzFramework // Methods used for unit tests AZ::ScriptProperty* GetScriptProperty(const char* propertyName); - const AZ::ScriptProperty* GetNetworkedScriptProperty(const char* propertyName) const; protected: ScriptComponent(const ScriptComponent&) = delete; @@ -133,13 +126,6 @@ namespace AzFramework void OnAssetReloaded(AZ::Data::Asset asset) override; ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - // NetBindable - GridMate::ReplicaChunkPtr GetNetworkBinding() override; - void SetNetworkBinding(GridMate::ReplicaChunkPtr chunk) override; - void UnbindFromNetwork() override; - ////////////////////////////////////////////////////////////////////////// - /// Load script (unless already by other instances) and creates the script instance into the VM void LoadScript(); /// Removes the script instance and unloads the script (unless needed by other instances) @@ -152,8 +138,6 @@ namespace AzFramework void CreateEntityTable(); void DestroyEntityTable(); - void CreateNetworkBindingTable(int baseStackIndex, int entityStackIndex); - void CreatePropertyGroup(const ScriptPropertyGroup& group, int propertyGroupTableIndex, int parentIndex, int metatableIndex, bool isRoot); AZ::ScriptContext* m_context; ///< Context in which the script will be running @@ -161,7 +145,6 @@ namespace AzFramework AZ::Data::Asset m_script; ///< Reference to the script asset used for this component. int m_table; ///< Cached table index ScriptPropertyGroup m_properties; ///< List with all properties that were tweaked in the editor and should override values in the m_sourceScriptName class inside m_script. - ScriptNetBindingTable* m_netBindingTable; ///< Table that will hold our networked script values, and manage callbacks }; } // namespace AZ diff --git a/Code/Framework/AzFramework/AzFramework/Script/ScriptMarshal.cpp b/Code/Framework/AzFramework/AzFramework/Script/ScriptMarshal.cpp deleted file mode 100644 index f02e050e74..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Script/ScriptMarshal.cpp +++ /dev/null @@ -1,573 +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 - -#include "AzFramework/Script/ScriptMarshal.h" - -namespace AzFramework -{ - //////////////////////////// - // ScriptPropertyMarshaler - //////////////////////////// - - template - bool UnmarshalGenericType(AZ::DynamicSerializableField& serializableField, GridMate::ReadBuffer& rb) - { - bool valueChanged = true; - - GridMate::Marshaler serializableFieldMarshaler; - - // Store the old value, to compare with the unmarshaled value, to signal - T oldValue = (*serializableField.Get()); - - serializableFieldMarshaler.Unmarshal(serializableField,rb); - - // If our type hasn't changed, compare the values. - if (serializableField.m_typeId == T::TYPEINFO_Uuid()) - { - valueChanged = !(oldValue == (*serializableField.Get())); - } - - return valueChanged; - } - - class ScriptPropertyTableMarshalerHelper - { - public: - template - static void MarshalScriptPropertyGenericMap(const ScriptPropertyMarshaler& scriptPropertyMarshaler, GridMate::WriteBuffer& wb, const AZ::ScriptPropertyTable* scriptPropertyTable) - { - GridMate::Marshaler sizeMarshaler; - - auto mapIter = scriptPropertyTable->m_genericMapping.find(T::TYPEINFO_Uuid()); - - if (mapIter != scriptPropertyTable->m_genericMapping.end()) - { - AZ::ScriptPropertyGenericClassMapImpl* genericClassKeyMap = static_cast*>(mapIter->second); - - auto& valueMap = genericClassKeyMap->GetPairMapping(); - - // We will write out all of our keys. Since it is easier to write out nil values for the properties. - sizeMarshaler.Marshal(wb,static_cast(valueMap.size())); - - GridMate::Marshaler keyMarshaler; - - for (auto& mapPair : valueMap) - { - keyMarshaler.Marshal(wb,mapPair.first); - scriptPropertyMarshaler.Marshal(wb,mapPair.second.m_valueProperty); - } - } - else - { - sizeMarshaler.Marshal(wb,0); - } - } - - template - static bool UnmarshalScriptPropertyGenericMap(const ScriptPropertyMarshaler& scriptPropertyMarshaler, AZ::ScriptPropertyTable* scriptPropertyTable, GridMate::ReadBuffer& rb) - { - bool valueChanged = false; - - AZ::SerializeContext* useContext = nullptr; - EBUS_EVENT_RESULT(useContext, AZ::ComponentApplicationBus, GetSerializeContext); - - if (useContext) - { - const AZ::SerializeContext::ClassData* classData = useContext->FindClassData(T::TYPEINFO_Uuid()); - - if (classData && classData->m_factory) - { - auto mapIter = scriptPropertyTable->m_genericMapping.find(T::TYPEINFO_Uuid()); - - if (mapIter != scriptPropertyTable->m_genericMapping.end()) - { - // This whole thing is an in-place map update. - // to try to minimize the number of allocations. We try to re-use objects as much as possible. - // - // Two phase approach: Step one, update all of the existing properties, while keeping track of all of the used keys. - // Step two, go through and delete any unupdated keys from the mapping. - AZ::ScriptPropertyGenericClassMapImpl* genericClassKeyMap = static_cast*>(mapIter->second); - - AZStd::unordered_set newKeys; - - GridMate::Marshaler sizeMarshaler; - - AZ::u32 mapSize; - sizeMarshaler.Unmarshal(mapSize,rb); - - auto& valueMap = genericClassKeyMap->GetPairMapping(); - - GridMate::Marshaler keyMarshaler; - - for (unsigned int i=0; i < mapSize; ++i) - { - T propertyKey; - keyMarshaler.Unmarshal(propertyKey,rb); - - newKeys.insert(propertyKey); - - auto valueIter = valueMap.find(propertyKey); - - if (valueIter != valueMap.end()) - { - if (scriptPropertyMarshaler.UnmarshalToPointer(valueIter->second.m_valueProperty,rb)) - { - valueChanged = true; - } - } - else - { - valueChanged = true; - - AZ::ScriptProperty* newValueProperty = nullptr; - scriptPropertyMarshaler.UnmarshalToPointer(newValueProperty,rb); - - AZ::ScriptPropertyGenericClassMap::MapValuePair newPair; - - newPair.m_valueProperty = newValueProperty; - - T* serializableData = nullptr; - serializableData = static_cast(classData->m_factory->Create("ScriptProperty")); - (*serializableData) = propertyKey; - - AZ::ScriptPropertyGenericClass* genericPropertyClass = aznew AZ::ScriptPropertyGenericClass(); - - genericPropertyClass->Set(serializableData); - - newPair.m_keyProperty = genericPropertyClass; - - valueMap.emplace(propertyKey,newPair); - } - } - - // Delete all of the unused keyes from the map - auto valueIter = valueMap.begin(); - - while (valueIter != valueMap.end()) - { - if (newKeys.find(valueIter->first) == newKeys.end()) - { - valueChanged = true; - valueIter->second.Destroy(); - valueIter = valueMap.erase(valueIter); - } - else - { - ++valueIter; - } - } - } - } - } - - return valueChanged; - } - }; - - - - void ScriptPropertyMarshaler::Marshal(GridMate::WriteBuffer& wb, AZ::ScriptProperty*const& property) const - { - GridMate::Marshaler typeMarshaler; - GridMate::Marshaler idMarshaler; - GridMate::Marshaler nameMarshaler; - - if (property == nullptr) - { - // Write out a nil property if we have a nullptr property - nameMarshaler.Marshal(wb,""); - idMarshaler.Marshal(wb,0); - typeMarshaler.Marshal(wb,AZ::ScriptPropertyNil::RTTI_Type()); - return; - } - - // Common points: - // Always going to marshal the uuid of the type(or something similar) - // so we know what type we have on the other side. - // - // Next need to pass along the name field. - const AZ::Uuid& typeId = azrtti_typeid(property); - - nameMarshaler.Marshal(wb,property->m_name); - idMarshaler.Marshal(wb,property->m_id); - - // Method 1: - // - Allow each ScriptProperty to marshal itself. - // - Currently unavailable since the ScriptProperties live in AZCore - // and the WriteBuffer is in GridMate. - // cont.Marshal(wb); - - // Method 2: - // - Process all of our known marshallable types and use the appropriate marshaler - if (typeId == AZ::ScriptPropertyBoolean::RTTI_Type()) - { - typeMarshaler.Marshal(wb,typeId); - - GridMate::Marshaler boolMarshaler; - boolMarshaler.Marshal(wb,static_cast(property)->m_value); - } - else if (typeId == AZ::ScriptPropertyNumber::RTTI_Type()) - { - typeMarshaler.Marshal(wb,typeId); - - GridMate::Marshaler doubleMarshaler; - doubleMarshaler.Marshal(wb,static_cast(property)->m_value); - } - else if (typeId == AZ::ScriptPropertyString::RTTI_Type()) - { - typeMarshaler.Marshal(wb,typeId); - - GridMate::Marshaler stringMarshaler; - stringMarshaler.Marshal(wb,static_cast(property)->m_value); - } - else if (typeId == AZ::ScriptPropertyGenericClass::RTTI_Type()) - { - const AZ::DynamicSerializableField& serializableField = static_cast(property)->GetSerializableField(); - - typeMarshaler.Marshal(wb,typeId); - - GridMate::Marshaler serializableFieldMarshaler; - serializableFieldMarshaler.Marshal(wb,serializableField); - } - else if (typeId == AZ::ScriptPropertyTable::TYPEINFO_Uuid()) - { - const AZ::ScriptPropertyTable* scriptPropertyTable = static_cast(property); - - typeMarshaler.Marshal(wb,typeId); - - GridMate::Marshaler mapSizeMarshaler; - mapSizeMarshaler.Marshal(wb,static_cast(scriptPropertyTable->m_indexMapping.size())); - - GridMate::Marshaler indexMarshaler; - - // Currently only support integers as keys inside of the table. - for (auto& mapPair : scriptPropertyTable->m_indexMapping) - { - indexMarshaler.Marshal(wb,mapPair.first); - this->Marshal(wb,mapPair.second); - } - - mapSizeMarshaler.Marshal(wb, static_cast(scriptPropertyTable->m_keyMapping.size())); - - GridMate::Marshaler hashMarshaler; - - for (auto& mapPair : scriptPropertyTable->m_keyMapping) - { - // For hashed values. The name of the script property is the same as the hash it should be using. - // We still synchronize the Crc so we can unmarshal in place on the other side. - hashMarshaler.Marshal(wb,mapPair.first); - Marshal(wb,mapPair.second); - } - - // EntityId's - ScriptPropertyTableMarshalerHelper::MarshalScriptPropertyGenericMap((*this), wb, scriptPropertyTable); - } - else - { - typeMarshaler.Marshal(wb,AZ::ScriptPropertyNil::RTTI_Type()); - } - } - - bool ScriptPropertyMarshaler::UnmarshalToPointer(AZ::ScriptProperty*& target, GridMate::ReadBuffer& rb) const - { - bool typeChanged = false; - AZ::Uuid typeId; - AZ::u64 id; - AZStd::string name; - - GridMate::Marshaler typeMarshaler; - GridMate::Marshaler idMarshaler; - GridMate::Marshaler nameMarshaler; - - nameMarshaler.Unmarshal(name,rb); - idMarshaler.Unmarshal(id,rb); - typeMarshaler.Unmarshal(typeId,rb); - - if (target == nullptr || typeId != azrtti_typeid(target)) - { - typeChanged = true; - - AZ::ScriptProperty* actualScriptProperty = nullptr; - if (typeId == AZ::ScriptPropertyBoolean::RTTI_Type()) - { - actualScriptProperty = aznew AZ::ScriptPropertyBoolean(); - } - else if (typeId == AZ::ScriptPropertyNumber::RTTI_Type()) - { - actualScriptProperty = aznew AZ::ScriptPropertyNumber(); - } - else if (typeId == AZ::ScriptPropertyString::RTTI_Type()) - { - actualScriptProperty = aznew AZ::ScriptPropertyString(); - } - else if (typeId == AZ::ScriptPropertyGenericClass::RTTI_Type()) - { - actualScriptProperty = aznew AZ::ScriptPropertyGenericClass(); - } - else if (typeId == AZ::ScriptPropertyTable::RTTI_Type()) - { - actualScriptProperty = aznew AZ::ScriptPropertyTable(); - } - else - { - actualScriptProperty = aznew AZ::ScriptPropertyNil(); - } - - actualScriptProperty->m_name = name; - delete target; - - target = actualScriptProperty; - } - - // Update our ID - target->m_id = id; - - // Method 1: - // - Allow each ScriptProperty to unmarshal itself - // - Currently unavailable since the ScriptProperties live in AZCore - // and the WriteBuffer is in GridMate - // actualScriptProperty->Unmarshal(rb); - // - // Method 2: - // - Process all of our known marshallable types and use the appropriate marshaler - - bool valueChanged = false; - - if (typeId == AZ::ScriptPropertyBoolean::RTTI_Type()) - { - AZ::ScriptPropertyBoolean* booleanProperty = static_cast(target); - bool oldValue = booleanProperty->m_value; - - GridMate::Marshaler boolMarshaler; - boolMarshaler.Unmarshal(booleanProperty->m_value,rb); - - valueChanged = !(oldValue == booleanProperty->m_value); - } - else if (typeId == AZ::ScriptPropertyString::RTTI_Type()) - { - AZ::ScriptPropertyString* stringProperty = static_cast(target); - AZStd::string oldValue = stringProperty->m_value; - - GridMate::Marshaler stringMarshaler; - stringMarshaler.Unmarshal(stringProperty->m_value,rb); - - valueChanged = !(oldValue == stringProperty->m_value); - } - else if (typeId == AZ::ScriptPropertyNumber::RTTI_Type()) - { - AZ::ScriptPropertyNumber* numberProperty = static_cast(target); - double oldValue = numberProperty->m_value; - - GridMate::Marshaler numberMarshaler; - numberMarshaler.Unmarshal(numberProperty->m_value,rb); - - valueChanged = !(oldValue == numberProperty->m_value); - } - else if (typeId == AZ::ScriptPropertyGenericClass::RTTI_Type()) - { - AZ::ScriptPropertyGenericClass* genericProperty = static_cast(target); - - AZ::DynamicSerializableField& serializableField = genericProperty->m_value; - - AZ::DynamicSerializableField oldField; - - oldField.CopyDataFrom(serializableField); - - GridMate::Marshaler serializableFieldMarshaler; - serializableFieldMarshaler.Unmarshal(serializableField,rb); - - // If our type hasn't changed, compare the values. - valueChanged = !oldField.IsEqualTo(serializableField); - } - else if (typeId == AZ::ScriptPropertyTable::RTTI_Type()) - { - AZ::ScriptPropertyTable* scriptPropertyTable = static_cast(target); - GridMate::Marshaler mapSizeMarshaler; - - // Unmarshal all of the indexes properties - { - AZ::u32 mapSize = 0; - mapSizeMarshaler.Unmarshal(mapSize, rb); - - AZStd::unordered_set newIndexes; - GridMate::Marshaler indexMarshaler; - - for (AZ::u32 i=0; i < mapSize; ++i) - { - int index = 0; - indexMarshaler.Unmarshal(index,rb); - - auto mapIter = scriptPropertyTable->m_indexMapping.find(index); - - if (mapIter != scriptPropertyTable->m_indexMapping.end()) - { - if (UnmarshalToPointer(mapIter->second,rb)) - { - valueChanged = true; - } - } - else - { - valueChanged = true; - - AZ::ScriptProperty* scriptProperty = nullptr; - UnmarshalToPointer(scriptProperty,rb); - auto insertResult = scriptPropertyTable->m_indexMapping.emplace(index,scriptProperty); - mapIter = insertResult.first; - } - - if (mapIter->second == nullptr || azrtti_istypeof(mapIter->second)) - { - valueChanged = true; - - delete mapIter->second; - scriptPropertyTable->m_indexMapping.erase(mapIter); - } - else - { - newIndexes.insert(index); - } - } - - auto mapIter = scriptPropertyTable->m_indexMapping.begin(); - - while (mapIter != scriptPropertyTable->m_indexMapping.end()) - { - if (newIndexes.find(mapIter->first) == newIndexes.end()) - { - valueChanged = true; - - delete mapIter->second; - mapIter = scriptPropertyTable->m_indexMapping.erase(mapIter); - } - else - { - ++mapIter; - } - } - } - - // Unmarshal all of the hashed values - { - AZ::u32 mapSize = 0; - mapSizeMarshaler.Unmarshal(mapSize, rb); - - AZStd::unordered_set newHashes; - GridMate::Marshaler hashMarshaler; - - for (AZ::u32 i=0; i < mapSize; ++i) - { - AZ::u32 newHash; - hashMarshaler.Unmarshal(newHash, rb); - - auto mapIter = scriptPropertyTable->m_keyMapping.find(newHash); - - if (mapIter != scriptPropertyTable->m_keyMapping.end()) - { - if (UnmarshalToPointer(mapIter->second,rb)) - { - valueChanged = true; - } - } - else - { - valueChanged = true; - - AZ::ScriptProperty* scriptProperty = nullptr; - UnmarshalToPointer(scriptProperty,rb); - auto emplaceResult = scriptPropertyTable->m_keyMapping.emplace(newHash,scriptProperty); - mapIter = emplaceResult.first; - } - - if (mapIter->second == nullptr || azrtti_istypeof(mapIter->second)) - { - valueChanged = true; - - delete mapIter->second; - scriptPropertyTable->m_keyMapping.erase(mapIter); - } - else - { - newHashes.insert(newHash); - } - } - - auto mapIter = scriptPropertyTable->m_keyMapping.begin(); - - while (mapIter != scriptPropertyTable->m_keyMapping.end()) - { - if (newHashes.find(mapIter->first) == newHashes.end()) - { - valueChanged = true; - - delete mapIter->second; - mapIter = scriptPropertyTable->m_keyMapping.erase(mapIter); - } - else - { - ++mapIter; - } - } - } - - // Unmarshal all of the generic properties - - // EntityId's - if (ScriptPropertyTableMarshalerHelper::UnmarshalScriptPropertyGenericMap((*this), scriptPropertyTable, rb)) - { - valueChanged = true; - } - } - - return typeChanged || valueChanged; - } - - //////////////////////////// - // ScriptPropertyThrottler - //////////////////////////// - - ScriptPropertyThrottler::ScriptPropertyThrottler() - : m_isDirty(true) - { - - } - - void ScriptPropertyThrottler::SignalDirty() - { - m_isDirty = true; - } - - bool ScriptPropertyThrottler::WithinThreshold(AZ::ScriptProperty* newValue) const - { - return newValue == nullptr || !m_isDirty; - } - - void ScriptPropertyThrottler::UpdateBaseline(AZ::ScriptProperty* baseline) - { - (void)baseline; - - m_isDirty = false; - } -} diff --git a/Code/Framework/AzFramework/AzFramework/Script/ScriptMarshal.h b/Code/Framework/AzFramework/AzFramework/Script/ScriptMarshal.h deleted file mode 100644 index c13749d46b..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Script/ScriptMarshal.h +++ /dev/null @@ -1,94 +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 AZFRAMEWORK_SCRIPT_SCRIPTMARSHAL_H -#define AZFRAMEWORK_SCRIPT_SCRIPTMARSHAL_H - -#include - -#include - -namespace AZ -{ - class ScriptProperty; -} - -namespace AzFramework -{ - /** - * Specalized helper marshaler for ScriptProperty class - */ - class ScriptPropertyMarshaler - { - public: - void Marshal(GridMate::WriteBuffer& wb, AZ::ScriptProperty*const& cont) const; - bool UnmarshalToPointer(AZ::ScriptProperty*& target, GridMate::ReadBuffer& rb) const; - }; - - class ScriptPropertyThrottler - { - public: - ScriptPropertyThrottler(); - - void SignalDirty(); - bool WithinThreshold(AZ::ScriptProperty* newValue) const; - void UpdateBaseline(AZ::ScriptProperty* baseline); - - private: - bool m_isDirty; - }; - - /** - * Specialized helper marshaler to help with the vector creation/destruction - */ - class ScriptRPCMarshaler - { - public: - - typedef AZStd::vector< AZ::ScriptProperty* > Container; - - ScriptRPCMarshaler() - { - } - - AZ_FORCE_INLINE void Marshal(GridMate::WriteBuffer& wb, const Container& container) const - { - AZ_Assert(container.size() < USHRT_MAX, "Container has too many elements for marshaling!"); - AZ::u16 size = static_cast(container.size()); - wb.Write(size); - for (const auto& i : container) - { - m_marshaler.Marshal(wb, i); - } - } - - AZ_FORCE_INLINE void Unmarshal(Container& container, GridMate::ReadBuffer& rb) const - { - container.clear(); - - AZ::u16 size; - rb.Read(size); - container.reserve(size); - - for (AZ::u16 i = 0; i < size; ++i) - { - AZ::ScriptProperty* readProperty = nullptr; - m_marshaler.UnmarshalToPointer(readProperty, rb); - container.insert(container.end(), readProperty); - } - } - - protected: - ScriptPropertyMarshaler m_marshaler; - }; -} - -#endif diff --git a/Code/Framework/AzFramework/AzFramework/Script/ScriptNetBindings.cpp b/Code/Framework/AzFramework/AzFramework/Script/ScriptNetBindings.cpp deleted file mode 100644 index 45690eac01..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Script/ScriptNetBindings.cpp +++ /dev/null @@ -1,1427 +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 - -extern "C" { -# include -# include -} - -namespace AzFramework -{ - namespace Internal - { - static int NetBinding__IsAuthoritative(lua_State* lua) - { - ScriptNetBindingTable* netBindingTable = reinterpret_cast(lua_touserdata(lua,lua_upvalueindex(1))); - - //AZ_Assert(netBindingTable != nullptr && netBindingTable->GetScriptContext(),"Missing or misconfigured ScriptNetBindingTable as upvalue in lua_cclosure"); - if (netBindingTable && netBindingTable->GetScriptContext()) - { - lua_pushboolean(lua,netBindingTable->IsMaster()); - } - else - { - // If we don't have a net binding table, or a a script context, return true - // since we likely are the master. - lua_pushboolean(lua,true); - } - - return 1; - } - - static int NetBinding__IsMaster(lua_State* lua) - { - AZ_Warning("ScriptNetBindings", false, "IsMaster deprecated for the more lexical consistent IsAuthoritative"); - return NetBinding__IsAuthoritative(lua); - } - - static int NetBinding__CallRPC(lua_State* lua) - { - ScriptNetBindingTable* netBindingTable = reinterpret_cast(lua_touserdata(lua,lua_upvalueindex(1))); - - AZ_Error("ScriptComponent", netBindingTable != nullptr,"Missing ScriptNetBindingTable as upvalue in lua_cclosure"); - AZ_Error("ScriptComponent", netBindingTable == nullptr || netBindingTable->GetScriptContext(),"Missing ScriptNetBindingTable as upvalue in lua_cclosure"); - if (netBindingTable && netBindingTable->GetScriptContext()) - { - AZ::ScriptContext* context = netBindingTable->GetScriptContext(); - - AZ::ScriptDataContext stackContext; - bool validIndex = context->ReadStack(stackContext); - - if (validIndex) - { - netBindingTable->InvokeRPC(stackContext); - } - } - - return 0; - } - } - - ////////////////////////// - // ScriptPropertyDataSet - ////////////////////////// - - // Necessary since the field doesn't make a copy, but keeps the actual literal. - // But overall :( - - const char* ScriptPropertyDataSet::GetDataSetName() - { - static size_t s_chunkIndex = 0; - static const char* s_nameArray[] = { - "DataSet1","DataSet2","DataSet3","DataSet4","DataSet5", - "DataSet6","DataSet7","DataSet8","DataSet9","DataSet10", - "DataSet11","DataSet12","DataSet13","DataSet14","DataSet15", - "DataSet16","DataSet17","DataSet18","DataSet19","DataSet20", - "DataSet21","DataSet22","DataSet23","DataSet24","DataSet25", - "DataSet26","DataSet27","DataSet28","DataSet29","DataSet30", - "DataSet31","DataSet32" - }; - - if ((s_chunkIndex >= AZ_ARRAY_SIZE(s_nameArray)) && (AZ_ARRAY_SIZE(s_nameArray) >= 0)) - { - s_chunkIndex = s_chunkIndex % AZ_ARRAY_SIZE(s_nameArray); - } - - return s_nameArray[s_chunkIndex++]; - } - - ScriptPropertyDataSet::ScriptPropertyDataSet() - : ScriptPropertyDataSetType(GetDataSetName()) - , m_reserver(nullptr) - { - } - - ScriptPropertyDataSet::~ScriptPropertyDataSet() - { - AZ::FunctionalScriptProperty* functionalScriptProperty = azrtti_cast(Get()); - - if (functionalScriptProperty) - { - functionalScriptProperty->DisableInPlaceControls(); - functionalScriptProperty->RemoveWatcher(this); - } - } - - void ScriptPropertyDataSet::Reserve(ScriptNetBindingTable::NetworkedTableValue* reserver) - { - AZ_Error("ScriptComponent",m_reserver == nullptr || reserver == m_reserver, "Trying to reserve the same DataSet for two NetworkedTableVaules."); - - if (m_reserver == nullptr) - { - m_reserver = reserver; - AZ::ScriptPropertyWatcherBus::Handler::BusConnect(this); - - AZ::FunctionalScriptProperty* functionalScriptProperty = azrtti_cast(Get()); - - if (functionalScriptProperty) - { - functionalScriptProperty->EnableInPlaceControls(); - functionalScriptProperty->AddWatcher(this); - } - } - } - - void ScriptPropertyDataSet::Release(ScriptNetBindingTable::NetworkedTableValue* reserver) - { - AZ_Error("ScriptComponent",m_reserver == nullptr || m_reserver == reserver, "Incorrect NetworkedTableValue trying to release a reserver DataSet."); - if (m_reserver == reserver) - { - m_reserver = nullptr; - AZ::ScriptPropertyWatcherBus::Handler::BusDisconnect(this); - } - } - - bool ScriptPropertyDataSet::IsReserved() const - { - return m_reserver != nullptr; - } - - bool ScriptPropertyDataSet::UpdateScriptProperty(AZ::ScriptDataContext& scriptDataContext, const AZStd::string& propertyName) - { - bool wroteValue = false; - - Modify([&](AZ::ScriptProperty*& scriptProperty) - { - wroteValue = true; - if (scriptProperty == nullptr || !scriptProperty->TryRead(scriptDataContext,-1)) - { - AZ::ScriptProperty* newPropertyType = scriptDataContext.ConstructScriptProperty(-1,propertyName.c_str()); - - delete scriptProperty; - - if (newPropertyType == nullptr) - { - scriptProperty = aznew AZ::ScriptPropertyNil(); - } - else - { - scriptProperty = newPropertyType; - } - - AZ::FunctionalScriptProperty* functionalScriptProperty = azrtti_cast(newPropertyType); - - if (functionalScriptProperty) - { - functionalScriptProperty->EnableInPlaceControls(); - functionalScriptProperty->AddWatcher(this); - } - } - - m_throttler.SignalDirty(); - - return wroteValue; - }); - - return wroteValue; - } - - void ScriptPropertyDataSet::SetScriptProperty(AZ::ScriptProperty* scriptProperty) - { - Modify([&](AZ::ScriptProperty*& dataSetProperty) - { - AZ::ScriptProperty* tempProperty = dataSetProperty; - - if (scriptProperty == nullptr) - { - if (tempProperty) - { - dataSetProperty = aznew AZ::ScriptPropertyNil(tempProperty->m_name.c_str()); - } - else - { - dataSetProperty = aznew AZ::ScriptPropertyNil(); - } - } - else - { - dataSetProperty = scriptProperty; - } - - if (tempProperty) - { - delete tempProperty; - } - - AZ::FunctionalScriptProperty* functionalScriptProperty = azrtti_cast(dataSetProperty); - - if (functionalScriptProperty) - { - functionalScriptProperty->EnableInPlaceControls(); - functionalScriptProperty->AddWatcher(this); - } - - m_throttler.SignalDirty(); - - return true; - }); - } - - void ScriptPropertyDataSet::OnObjectModified() - { - m_throttler.SignalDirty(); - SetDirty(); - } - - //////////////////////// - // EntityScriptContext - //////////////////////// - - ScriptNetBindingTable::EntityScriptContext::EntityScriptContext() - : m_scriptContext(nullptr) - , m_entityTableRegistryIndex(LUA_REFNIL) - { - } - - void ScriptNetBindingTable::EntityScriptContext::Unload() - { - m_scriptContext = nullptr; - m_entityTableRegistryIndex = LUA_REFNIL; - } - - bool ScriptNetBindingTable::EntityScriptContext::HasEntityTableRegistryIndex() const - { - return m_entityTableRegistryIndex != LUA_REFNIL; - } - - int ScriptNetBindingTable::EntityScriptContext::GetEntityTableRegistryIndex() const - { - return m_entityTableRegistryIndex; - } - - bool ScriptNetBindingTable::EntityScriptContext::HasScriptContext() const - { - return m_scriptContext != nullptr; - } - - AZ::ScriptContext* ScriptNetBindingTable::EntityScriptContext::GetScriptContext() const - { - return m_scriptContext; - } - - void ScriptNetBindingTable::EntityScriptContext::ConfigureContext(AZ::ScriptContext* scriptContext, int entityTableRegistryIndex) - { - m_scriptContext = scriptContext; - m_entityTableRegistryIndex = entityTableRegistryIndex; - - AZ_Error("ScriptComponent",SanityCheckContext(),"Invalid configuration given to ScriptNetBindingTable"); - } - - bool ScriptNetBindingTable::EntityScriptContext::SanityCheckContext() const - { - bool isSane = HasScriptContext(); - - if (isSane) - { - // We want to check if our reference is actually pointing to a table - // which we will assume is our entity table - lua_State* nativeContext = m_scriptContext->NativeContext(); - - lua_rawgeti(nativeContext,LUA_REGISTRYINDEX,m_entityTableRegistryIndex); - isSane = lua_istable(nativeContext,-1); - lua_pop(nativeContext,1); - } - - return isSane; - } - - //////////////////////// - // NetworkedTableValue - //////////////////////// - - ScriptNetBindingTable::NetworkedTableValue::NetworkedTableValue(AZ::ScriptProperty* initialValue) - : m_shimmedScriptProperty(initialValue) - , m_dataSet(nullptr) - , m_forcedDataSetIndex(-1) - , m_functionReference(LUA_REFNIL) - { - AZ::FunctionalScriptProperty* functionalScriptProperty = azrtti_cast(initialValue); - - if (functionalScriptProperty) - { - functionalScriptProperty->EnableInPlaceControls(); - } - } - - ScriptNetBindingTable::NetworkedTableValue::~NetworkedTableValue() - { - // Always want to release our dataset if we have one when we are destroyed. - // - // We do not want to delete our proeprty thought, since we might have been copied over. - if (m_dataSet) - { - m_dataSet->Release(this); - } - } - - void ScriptNetBindingTable::NetworkedTableValue::Destroy() - { - if (m_shimmedScriptProperty) - { - delete m_shimmedScriptProperty; - m_shimmedScriptProperty = nullptr; - } - - if (m_dataSet) - { - m_dataSet->Release(this); - } - } - - bool ScriptNetBindingTable::NetworkedTableValue::HasDataSet() const - { - return m_dataSet != nullptr; - } - - void ScriptNetBindingTable::NetworkedTableValue::RegisterDataSet(ScriptPropertyDataSet* dataSet) - { - m_dataSet = dataSet; - - if (m_dataSet) - { - if (m_shimmedScriptProperty) - { - m_dataSet->SetScriptProperty(m_shimmedScriptProperty); - m_shimmedScriptProperty = nullptr; - } - - m_dataSet->Reserve(this); - } - } - - void ScriptNetBindingTable::NetworkedTableValue::UnbindFromDataSet() - { - if (m_dataSet) - { - // Take ownership of the DataSet script property into our shimmed value - // - // If we are the master, we can take ownership and set the data set value to null - if (m_dataSet->CanSet()) - { - m_shimmedScriptProperty = m_dataSet->Get(); - m_dataSet->Set(nullptr); - } - // Otherwise, we need to clone the data in the data set since we can't modify it and we need to avoid a double deletion. - else - { - AZ::ScriptProperty* scriptProperty = m_dataSet->Get(); - m_shimmedScriptProperty = scriptProperty->Clone(); - } - - m_dataSet->Release(this); - m_dataSet = nullptr; - } - } - - ScriptPropertyDataSet* ScriptNetBindingTable::NetworkedTableValue::GetDataSet() const - { - return m_dataSet; - } - - bool ScriptNetBindingTable::NetworkedTableValue::HasForcedDataSetIndex() const - { - return m_forcedDataSetIndex >= 1; - } - - void ScriptNetBindingTable::NetworkedTableValue::SetForcedDataSetIndex(int index) - { - m_forcedDataSetIndex = index; - } - - int ScriptNetBindingTable::NetworkedTableValue::GetForcedDataSetIndex() const - { - return m_forcedDataSetIndex; - } - - bool ScriptNetBindingTable::NetworkedTableValue::HasCallback() const - { - return m_functionReference != LUA_REFNIL; - } - - void ScriptNetBindingTable::NetworkedTableValue::RegisterCallback(int functionReference) - { - AZ_Warning("ScriptComponent",!HasCallback() || functionReference == LUA_REFNIL,"Overriding an already registered callback for a DataSet."); - - m_functionReference = functionReference; - } - - void ScriptNetBindingTable::NetworkedTableValue::ReleaseCallback(AZ::ScriptContext& scriptContext) - { - if (HasCallback()) - { - scriptContext.ReleaseCached(m_functionReference); - m_functionReference = LUA_REFNIL; - } - } - - void ScriptNetBindingTable::NetworkedTableValue::InvokeCallback(EntityScriptContext& entityContext, const GridMate::TimeContext& timeContext) - { - (void)timeContext; - - AZ::ScriptContext* scriptContext = entityContext.GetScriptContext(); - - AZ_Warning("ScriptComponent",scriptContext,"DataSetCallback given null ScriptContext."); - AZ_Warning("ScriptComponent",entityContext.HasEntityTableRegistryIndex(),"DataSetCallback given invalid entity table reference"); - if (scriptContext && entityContext.HasEntityTableRegistryIndex()) - { - AZ::ScriptDataContext callContext; - - if (scriptContext->CallCached(m_functionReference,callContext)) - { - callContext.PushArgFromRegistryIndex(entityContext.GetEntityTableRegistryIndex()); - callContext.CallExecute(); - } - } - } - - bool ScriptNetBindingTable::NetworkedTableValue::AssignValue(AZ::ScriptDataContext& scriptDataContext, const AZStd::string& propertyName) - { - bool assignedValue = false; - if (HasDataSet()) - { - assignedValue = GetDataSet()->UpdateScriptProperty(scriptDataContext, propertyName); - } - else - { - if (m_shimmedScriptProperty == nullptr || !m_shimmedScriptProperty->TryRead(scriptDataContext,-1)) - { - delete m_shimmedScriptProperty; - m_shimmedScriptProperty = nullptr; - m_shimmedScriptProperty = scriptDataContext.ConstructScriptProperty(-1,propertyName.c_str()); - - AZ::FunctionalScriptProperty* functionalScriptProperty = azrtti_cast(m_shimmedScriptProperty); - - if (functionalScriptProperty) - { - functionalScriptProperty->EnableInPlaceControls(); - } - } - - assignedValue = (m_shimmedScriptProperty != nullptr); - } - - return assignedValue; - } - - bool ScriptNetBindingTable::NetworkedTableValue::InspectValue(AZ::ScriptContext* scriptContext) const - { - AZ::ScriptProperty* inspectedProperty = m_shimmedScriptProperty; - - if (HasDataSet()) - { - inspectedProperty = GetDataSet()->Get(); - } - - bool inspectedValue = false; - - if (inspectedProperty) - { - inspectedValue = inspectedProperty->Write((*scriptContext)); - } - - if (!inspectedValue) - { - inspectedValue = true; - - AZ::ScriptPropertyNil nilProperty; - nilProperty.Write((*scriptContext)); - } - - return inspectedValue; - } - - ////////////// - // RPCHelper - ////////////// - - // Maybe make this guy create the table himself? - // Encapsulate the whole binding process in here. - ScriptNetBindingTable::RPCBindingHelper::RPCBindingHelper() - : m_masterReference(LUA_REFNIL) - , m_proxyReference(LUA_REFNIL) - { - } - - ScriptNetBindingTable::RPCBindingHelper::~RPCBindingHelper() - { - } - - void ScriptNetBindingTable::RPCBindingHelper::ReleaseTableIndex(AZ::ScriptContext& scriptContext) - { - if (m_masterReference != LUA_REFNIL) - { - scriptContext.ReleaseCached(m_masterReference); - m_masterReference = LUA_REFNIL; - } - - if (m_proxyReference != LUA_REFNIL) - { - scriptContext.ReleaseCached(m_proxyReference); - m_proxyReference = LUA_REFNIL; - } - } - - bool ScriptNetBindingTable::RPCBindingHelper::IsValid() const - { - // Proxy is optional, so we only care about having the master index. - return m_masterReference != LUA_REFNIL; - } - - void ScriptNetBindingTable::RPCBindingHelper::SetMasterFunction(int masterReference) - { - AZ_Error("ScriptComponent",m_masterReference == LUA_REFNIL || masterReference == LUA_REFNIL, "Trying to rebind RPC master callback"); - - if (m_masterReference == LUA_REFNIL || masterReference == LUA_REFNIL) - { - m_masterReference = masterReference; - } - } - - bool ScriptNetBindingTable::RPCBindingHelper::InvokeMaster(EntityScriptContext& entityScriptContext, const ScriptRPCMarshaler::Container& params) - { - if (!entityScriptContext.HasScriptContext()) - { - AZ_Error("ScriptComponent",false,"Invoking RPC with invalid ScriptContext"); - return false; - } - - bool allowRPC = false; - - if (m_masterReference != LUA_REFNIL) - { - AZ::ScriptDataContext callContext; - AZ::ScriptContext* scriptContext = entityScriptContext.GetScriptContext(); - - if (scriptContext->CallCached(m_masterReference,callContext)) - { - callContext.PushArgFromRegistryIndex(entityScriptContext.GetEntityTableRegistryIndex()); - - for (AZ::ScriptProperty* property : params) - { - callContext.PushArgScriptProperty(property); - } - - if (callContext.CallExecute()) - { - bool hasResult = false; - if (callContext.GetNumResults() == 1) - { - hasResult = callContext.ReadResult(0,allowRPC); - } - - AZ_Assert(hasResult,"Master RPC function needs to return a boolean value"); - (void)hasResult; - } - } - - } - - return allowRPC; - } - - void ScriptNetBindingTable::RPCBindingHelper::SetProxyFunction(int proxyReference) - { - AZ_Error("ScriptComponent",m_proxyReference == LUA_REFNIL || proxyReference == LUA_REFNIL,"Trying to rebind an RPC Proxy call."); - - if (m_proxyReference == LUA_REFNIL || proxyReference == LUA_REFNIL) - { - m_proxyReference = proxyReference; - } - } - - void ScriptNetBindingTable::RPCBindingHelper::InvokeProxy(EntityScriptContext& entityScriptContext, const ScriptRPCMarshaler::Container& params) - { - if (!entityScriptContext.HasScriptContext()) - { - AZ_Error("ScriptComponent",false,"Trying to call a callback without a script context."); - return; - } - - AZ_Warning("ScriptComponent",m_proxyReference != LUA_REFNIL,"Trying to invoke an RPC on the proxy without a callback being set."); - if (m_proxyReference != LUA_REFNIL) - { - AZ::ScriptDataContext callContext; - AZ::ScriptContext* scriptContext = entityScriptContext.GetScriptContext(); - - if (scriptContext->CallCached(m_proxyReference,callContext)) - { - callContext.PushArgFromRegistryIndex(entityScriptContext.GetEntityTableRegistryIndex()); - - for (AZ::ScriptProperty* property : params) - { - callContext.PushArgScriptProperty(property); - } - - callContext.CallExecute(); - } - } - } - - ////////////////////////// - // ScriptNetBindingTable - ////////////////////////// - void ScriptNetBindingTable::Reflect(AZ::ReflectContext* reflection) - { - NetworkContext* netContext = azrtti_cast(reflection); - - if (netContext) - { - // Using old method until we update the network context to allow for array offests. - // Or find a better way to handle the script replica chunk - if (!GridMate::ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(GridMate::ReplicaChunkClassId(ScriptComponentReplicaChunk::GetChunkName()))) - { - GridMate::ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - } - } - } - - // Template specialization for the ConvertPropertyArrayToTable GenericClass support to deal with extra memory copies. - template<> - AZ::ScriptPropertyTable* ScriptNetBindingTable::ConvertPropertyArrayToTable(AZ::ScriptPropertyGenericClassArray* arrayProperty) - { - AZ::ScriptPropertyTable* scriptPropertyTable = aznew AZ::ScriptPropertyTable(arrayProperty->m_name.c_str()); - - AZ::ScriptPropertyGenericClass emptyGenericClass; - - for (unsigned int i=0; i < arrayProperty->m_values.size(); ++i) - { - // Offset by 1 to deal with lua 1 indexing. - // Table will make a clone of our object. - // - // To avoid pointlessly double copying the data. Insert the empty class. - scriptPropertyTable->SetTableValue(i+1, &emptyGenericClass); - - // Then do a find for the class back, to load up the data into the final object directly. - AZ::ScriptPropertyGenericClass* ownedClass = static_cast(scriptPropertyTable->FindTableValue(i+1)); - - const AZ::DynamicSerializableField& serializableField = arrayProperty->m_values[i]; - - ownedClass->Set(serializableField); - } - - return scriptPropertyTable; - } - - ScriptNetBindingTable::ScriptNetBindingTable() - { - } - - ScriptNetBindingTable::~ScriptNetBindingTable() - { - - } - - void ScriptNetBindingTable::Unload() - { - // Unbind our elements from our script context. - if (m_entityScriptContext.HasScriptContext()) - { - AZ::ScriptContext& scriptContext = (*m_entityScriptContext.GetScriptContext()); - for (NetworkedTableMap::value_type& tablePair : m_networkedTable) - { - NetworkedTableValue& tableValue = tablePair.second; - tableValue.ReleaseCallback(scriptContext); - } - - for (RPCHelperMap::value_type& rpcPair : m_rpcHelperMap) - { - RPCBindingHelper& bindingHelper = rpcPair.second; - bindingHelper.ReleaseTableIndex(scriptContext); - } - } - - // Destroy the table values, since they might contain some memory - for (NetworkedTableMap::value_type& tablePair : m_networkedTable) - { - tablePair.second.Destroy(); - } - - m_networkedTable.clear(); - m_rpcHelperMap.clear(); - - m_entityScriptContext.Unload(); - } - - void ScriptNetBindingTable::CreateNetworkBindingTable(AZ::ScriptContext* scriptContext, int baseTableIndex, int entityTableIndex) - { - (void)baseTableIndex; - - lua_State* nativeContext = scriptContext->NativeContext(); - - lua_pushliteral(nativeContext,"IsMaster"); - lua_pushlightuserdata(nativeContext,this); - lua_pushcclosure(nativeContext, &Internal::NetBinding__IsMaster,1); - lua_rawset(nativeContext,entityTableIndex); - - lua_pushliteral(nativeContext,"IsAuthoritative"); - lua_pushlightuserdata(nativeContext,this); - lua_pushcclosure(nativeContext, &Internal::NetBinding__IsAuthoritative,1); - lua_rawset(nativeContext,entityTableIndex); - - lua_pushstring(nativeContext,ScriptComponent::NetRPCFieldName); - lua_createtable(nativeContext,0,0); - - int rpcTableIndex = lua_gettop(nativeContext); - - // Read the stack - AZ::ScriptDataContext stackContext; - if (scriptContext->ReadStack(stackContext)) - { - // Inspect the element we know to be our table context - AZ::ScriptDataContext entityDataContext; - if (stackContext.IsTable(baseTableIndex) && stackContext.InspectTable(baseTableIndex,entityDataContext)) - { - // Find our RPC table inside of baseTableIndex - int tableIndex = 0; - if (entityDataContext.PushTableElement(ScriptComponent::NetRPCFieldName,&tableIndex)) - { - // If it's a table, we want to inspect it. - AZ::ScriptDataContext rpcTable; - if (entityDataContext.IsTable(tableIndex) && entityDataContext.InspectTable(tableIndex,rpcTable)) - { - // Iterate over the fields here, and register and RPC for each element inside of that table. - int fieldIndex; - int elementIndex; - const char* fieldName; - - while (rpcTable.InspectNextElement(elementIndex, fieldName, fieldIndex)) - { - if (fieldName != nullptr) - { - RegisterRPC(rpcTable,fieldName,elementIndex,rpcTableIndex); - } - } - } - } - } - } - - lua_rawset(nativeContext,entityTableIndex); - } - - void ScriptNetBindingTable::FinalizeNetworkTable(AZ::ScriptContext* scriptContext, int entityTableRegistryIndex) - { - m_entityScriptContext.ConfigureContext(scriptContext, entityTableRegistryIndex); - - if (m_replicaChunk) - { - AssignDataSets(); - } - } - - AZ::ScriptContext* ScriptNetBindingTable::GetScriptContext() const - { - return m_entityScriptContext.GetScriptContext(); - } - - bool ScriptNetBindingTable::IsMaster() const - { - return (m_replicaChunk != nullptr) ? m_replicaChunk->IsMaster() : true; - } - - bool ScriptNetBindingTable::AssignTableValue(AZ::ScriptDataContext& stackDataContext) - { - bool wroteValue = false; - AZ_Error("ScriptComponent",stackDataContext.GetScriptContext() == m_entityScriptContext.GetScriptContext(),"Trying to use a ScriptNetBindings in the wrong context."); - - // We do not want to allow assignments on proxy replicas - // since that information will be discarded anyway. - if ((m_replicaChunk && !m_replicaChunk->IsMaster()) || (stackDataContext.GetScriptContext() != m_entityScriptContext.GetScriptContext())) - { - return false; - } - - AZStd::string key; - - if (stackDataContext.ReadValue(-2,key)) - { - NetworkedTableValue* networkedTableValue = FindTableValue(key); - - // If we don't have the value, it means we aren't trying to network it. - if (networkedTableValue) - { - if (m_replicaChunk && !networkedTableValue->HasDataSet()) - { - ScriptComponentReplicaChunk* scriptChunk = static_cast(m_replicaChunk.get()); - - scriptChunk->AssignDataSet((*networkedTableValue)); - } - - wroteValue = networkedTableValue->AssignValue(stackDataContext,key); - } - } - - return wroteValue; - } - - bool ScriptNetBindingTable::InspectTableValue(AZ::ScriptDataContext& stackContext) const - { - bool readValue = false; - AZStd::string key; - - if (stackContext.ReadValue(-1,key)) - { - AZ::ScriptContext* scriptContext = stackContext.GetScriptContext(); - - if (scriptContext) - { - const NetworkedTableValue* networkTableValue = FindTableValue(key); - - if (networkTableValue) - { - readValue = networkTableValue->InspectValue((stackContext.GetScriptContext())); - - // Default to nil if we have a network table value registered, but couldn't - // inspect it for some reason. - if (!readValue) - { - readValue = true; - static AZ::ScriptPropertyNil s_nilValue; - s_nilValue.Write((*scriptContext)); - } - } - } - else - { - AZ_Error("ScriptComponent",false,"Trying to read value into invalid ScriptContext"); - } - } - - return readValue; - } - - bool ScriptNetBindingTable::RegisterDataSet(AZ::ScriptDataContext& networkTableContext, AZ::ScriptProperty* scriptProperty) - { - if (scriptProperty == nullptr) - { - AZ_Error("ScriptComponent",false,"Trying to Create a dataset for a null script property."); - return false; - } - - AZ::Uuid typeId = azrtti_typeid(scriptProperty); - - if ( typeId == azrtti_typeid() - || typeId == azrtti_typeid()) - { - AZ_Error("ScriptComponent",false,"Using unsupported type for ScriptProperty(%s) net binding. Value will not be networked.", scriptProperty->m_name.c_str()); - return false; - } - - // If we've already got an item inside of our network table. - // We need to surpress that problem, since it may happen when we reload the script - if (m_networkedTable.find(scriptProperty->m_name) != m_networkedTable.end()) - { - return true; - } - - int elementIndex; - bool enabled = false; - bool handledProperty = false; - - if (networkTableContext.PushTableElement("Enabled",&elementIndex)) - { - // If we have the enabled field and it's not a boolean. - // Assume false. - if (networkTableContext.IsBoolean(elementIndex)) - { - // If we didn't read in the enabled value, assume it's false. - if (!networkTableContext.ReadValue(elementIndex,enabled)) - { - enabled = false; - } - } - } - else - { - // If we don't have an enabled field, assume that we want to be bound. - enabled = true; - } - - if (enabled) - { - NetworkedTableValue networkedTableValue; - - // Convert the property arrays over to a table to simplify the logic flow of detecting - // the various changes, and to more readily support what the general LUA syntax. - if (typeId == azrtti_typeid()) - { - AZ::ScriptPropertyBooleanArray* sourceArray = static_cast(scriptProperty); - - networkedTableValue = NetworkedTableValue(ConvertPropertyArrayToTable(sourceArray)); - } - else if (typeId == azrtti_typeid()) - { - AZ::ScriptPropertyNumberArray* sourceArray = static_cast(scriptProperty); - - networkedTableValue = NetworkedTableValue(ConvertPropertyArrayToTable(sourceArray)); - } - else if (typeId == azrtti_typeid()) - { - AZ::ScriptPropertyStringArray* sourceArray = static_cast(scriptProperty); - - networkedTableValue = NetworkedTableValue(ConvertPropertyArrayToTable(sourceArray)); - } - else if (typeId == azrtti_typeid()) - { - AZ::ScriptPropertyGenericClassArray* sourceArray = static_cast(scriptProperty); - - networkedTableValue = NetworkedTableValue(ConvertPropertyArrayToTable(sourceArray)); - } - else - { - networkedTableValue = NetworkedTableValue(scriptProperty->Clone()); - } - - if (networkTableContext.PushTableElement("OnNewValue", &elementIndex)) - { - if (networkTableContext.IsFunction(elementIndex)) - { - networkedTableValue.RegisterCallback( networkTableContext.CacheValue(elementIndex) ); - } - } - - if (networkTableContext.PushTableElement("ForceIndex",&elementIndex)) - { - if (networkTableContext.IsNumber(elementIndex)) - { - int forcedDataSetIndex = 0; - if (networkTableContext.ReadValue(elementIndex,forcedDataSetIndex)) - { - AZ_Error("ScriptComponent",forcedDataSetIndex >= 1 && forcedDataSetIndex <= ScriptComponentReplicaChunk::k_maxScriptableDataSets,"Trying to force Property (%s) to an invalid DataSetIndex(%i).",scriptProperty->m_name.c_str(),forcedDataSetIndex); - if(forcedDataSetIndex >= 1 && forcedDataSetIndex <= ScriptComponentReplicaChunk::k_maxScriptableDataSets) - { - networkedTableValue.SetForcedDataSetIndex(forcedDataSetIndex); - } - } - else - { - AZ_Error("ScriptComponent",false,"Trying to force Property (%s) to unknown DataSetIndex. Ignoring field.", scriptProperty->m_name.c_str()); - } - } - } - - AZStd::pair insertResult = m_networkedTable.insert(NetworkedTableMap::value_type(scriptProperty->m_name,networkedTableValue)); - - // If we failed to insert the object, we need to destroy the networked table value. - // To avoid leaking memory - if (!insertResult.second) - { - networkedTableValue.Destroy(); - } - - handledProperty = true; - } - - return handledProperty; - } - - bool ScriptNetBindingTable::InvokeRPC(AZ::ScriptDataContext& stackContext) - { - lua_State* nativeContext = stackContext.GetScriptContext()->NativeContext(); - - bool invokedRPC = false; - AZStd::string rpcName; - - // Assuming this is coming from an __call metamethod - // the lua stack will look as follows - // 1 - Table - // n - Params - if (stackContext.IsTable(1)) - { - // Get the RPC name - lua_pushliteral(nativeContext,"_rpcName"); - lua_gettable(nativeContext,1); - - if (stackContext.IsString(-1)) - { - if (stackContext.ReadValue(-1,rpcName)) - { - // Pop off the key value we just read in; It's no longer necessary - lua_pop(nativeContext,1); - - RPCHelperMap::iterator rpcIter = m_rpcHelperMap.find(rpcName); - - if (rpcIter != m_rpcHelperMap.end()) - { - bool foundParams = true; - - ScriptRPCMarshaler::Container paramContainer; - - // Need to start at 2, since 1 is our table. - for (int i=2; i <= lua_gettop(nativeContext); ++i) - { - AZ::ScriptProperty* property = stackContext.ConstructScriptProperty(i,"param"); - - if (property) - { - paramContainer.push_back(property); - } - else - { - foundParams = false; - break; - } - } - - // The script marshaler will clean up the keys after it has marshalled them out. - if (foundParams) - { - invokedRPC = true; - - if (m_replicaChunk) - { - ScriptComponentReplicaChunk* scriptReplicaChunk = static_cast(m_replicaChunk.get()); - scriptReplicaChunk->m_scriptRPC(rpcName,paramContainer); - } - else - { - rpcIter->second.InvokeMaster(m_entityScriptContext,paramContainer); - } - } - else - { - for (AZ::ScriptProperty* property : paramContainer) - { - delete property; - } - - paramContainer.clear(); - } - } - } - else - { - // We failed to read, so we need to pop the value we pushed off the stack. - lua_pop(nativeContext,1); - } - } - else - { - // Pop off the value we added to the top of the stack - lua_pop(nativeContext,1); - } - } - - return invokedRPC; - } - - void ScriptNetBindingTable::RegisterRPC(AZ::ScriptDataContext& rpcTableContext, const AZStd::string& rpc, int elementIndex, int tableStackIndex) - { - if (rpcTableContext.IsTable(elementIndex)) - { - RPCBindingHelper helper; - - AZ::ScriptDataContext rpcContext; - if (rpcTableContext.InspectTable(elementIndex,rpcContext)) - { - int functionIndex = 0; - if (rpcContext.PushTableElement("OnMaster",&functionIndex)) - { - helper.SetMasterFunction(rpcContext.CacheValue(functionIndex)); - } - else - { - AZ_Error("ScriptNetBinding", false, "Could not find OnMaster function for RPC (%s).", rpc.c_str()); - } - - if (rpcContext.PushTableElement("OnProxy",&functionIndex)) - { - helper.SetProxyFunction(rpcContext.CacheValue(functionIndex)); - } - } - else - { - AZ_Error("ScriptNetBinding", false, "Could inspect table for RPC (%s).", rpc.c_str()); - } - - if (helper.IsValid()) - { - lua_State* nativeContext = rpcTableContext.GetScriptContext()->NativeContext(); - - // Create the RPC Table inside of our entity table to allow for functions to be called on it. - // - lua_pushlstring(nativeContext,rpc.c_str(),rpc.size()); - lua_createtable(nativeContext,0,1); - - // Set up a name field inside of the table - lua_pushliteral(nativeContext,"_rpcName"); - lua_pushlstring(nativeContext,rpc.c_str(),rpc.size()); - lua_rawset(nativeContext,-3); - - // - lua_createtable(nativeContext,0,1); - lua_pushliteral(nativeContext,"__call"); - lua_pushlightuserdata(nativeContext, this); - lua_pushcclosure(nativeContext, &Internal::NetBinding__CallRPC,1); - lua_rawset(nativeContext,-3); - - lua_setmetatable(nativeContext,-2); - // - - lua_rawset(nativeContext,tableStackIndex); - // - - m_rpcHelperMap.insert(RPCHelperMap::value_type(rpc,helper)); - } - } - } - - GridMate::ReplicaChunkPtr ScriptNetBindingTable::GetNetworkBinding() - { - m_replicaChunk = GridMate::CreateReplicaChunk(); - m_replicaChunk->SetHandler(this); - - if (m_entityScriptContext.HasScriptContext()) - { - AssignDataSets(); - } - - return m_replicaChunk; - } - - void ScriptNetBindingTable::SetNetworkBinding(GridMate::ReplicaChunkPtr chunk) - { - m_replicaChunk = chunk; - m_replicaChunk->SetHandler(this); - - if (m_entityScriptContext.HasScriptContext()) - { - AssignDataSets(); - } - } - - void ScriptNetBindingTable::UnbindFromNetwork() - { - if (m_replicaChunk) - { - m_replicaChunk->SetHandler(nullptr); - - for (NetworkedTableMap::value_type& tablePair : m_networkedTable) - { - tablePair.second.UnbindFromDataSet(); - } - - m_replicaChunk = nullptr; - } - } - - void ScriptNetBindingTable::OnPropertyUpdate(AZ::ScriptProperty*const& scriptProperty, const GridMate::TimeContext& tc) - { - AZ_Error("ScriptComponent",m_replicaChunk != nullptr,"DataSet callback method called without ReplicaChunk present."); - - if (scriptProperty && m_replicaChunk) - { - ScriptComponentReplicaChunk* scriptReplicaChunk = static_cast(m_replicaChunk.get()); - - NetworkedTableValue* tableValue = FindTableValue(scriptProperty->m_name); - - if (tableValue) - { - if (!tableValue->HasDataSet()) - { - scriptReplicaChunk->AssignDataSetForProperty((*tableValue),scriptProperty); - AZ_Error("ScriptComponent",tableValue->HasDataSet(),"Unable to bind received ScriptProperty to DataSet."); - } - else - { - AZ_Error("ScriptComponent",scriptReplicaChunk->SanityCheckDataSet(scriptProperty,tableValue->GetDataSet()),"Mismatch between DataSet being chagned and mapping to dataset index."); - } - - if (tableValue->HasCallback()) - { - tableValue->InvokeCallback(m_entityScriptContext,tc); - } - } - else - { - AZ_Error("ScriptComponent",false,"Receiving update for unknown ScriptProperty."); - } - } - } - - bool ScriptNetBindingTable::OnInvokeRPC(AZStd::string functionName, AZStd::vector< AZ::ScriptProperty*> params, const GridMate::RpcContext& rpcContext) - { - (void)rpcContext; - - bool canProxyExecute = false; - AZ_Error("ScriptComponent",m_replicaChunk,"Receiving RPC callback with null ReplicaChunk."); - - RPCHelperMap::iterator rpcIter = m_rpcHelperMap.find(functionName); - - if (rpcIter != m_rpcHelperMap.end()) - { - RPCBindingHelper& rpcHelper = rpcIter->second; - - if (m_replicaChunk == nullptr || m_replicaChunk->IsMaster()) - { - canProxyExecute = rpcHelper.InvokeMaster(m_entityScriptContext,params); - } - else - { - // The canProxyExecute return value is meaningless on proxies. - rpcHelper.InvokeProxy(m_entityScriptContext,params); - } - } - - return canProxyExecute; - } - - const AZ::ScriptProperty* ScriptNetBindingTable::FindScriptProperty(const AZStd::string& name) const - { - const NetworkedTableValue* networkedTableValue = FindTableValue(name); - return networkedTableValue ? networkedTableValue->GetShimmedScriptProperty() : nullptr; - } - - void ScriptNetBindingTable::AssignDataSets() - { - if (m_replicaChunk) - { - ScriptComponentReplicaChunk* scriptComponentChunk = static_cast(m_replicaChunk.get()); - - // Going to do this in two passes, first to do all of the forced ones, then all of the arbitrary ones. - for (NetworkedTableMap::value_type& tablePair : m_networkedTable) - { - if (tablePair.second.HasForcedDataSetIndex() && !tablePair.second.HasDataSet()) - { - if (!scriptComponentChunk->AssignDataSet(tablePair.second)) - { - // Remove the forced DataSet index since it was invalid. - // Second pass will assign this an arbitrary one. - tablePair.second.SetForcedDataSetIndex(-1); - } - } - } - - for (NetworkedTableMap::value_type& tablePair : m_networkedTable) - { - // Try to assign everything that doesn't already have a dataset. - if (!tablePair.second.HasDataSet()) - { - scriptComponentChunk->AssignDataSet(tablePair.second); - } - } - } - } - - ScriptNetBindingTable::NetworkedTableValue* ScriptNetBindingTable::FindTableValue(const AZStd::string& name) - { - NetworkedTableValue* retVal = nullptr; - NetworkedTableMap::iterator tableIter = m_networkedTable.find(name); - - if (tableIter != m_networkedTable.end()) - { - retVal = &(tableIter->second); - } - - return retVal; - } - - const ScriptNetBindingTable::NetworkedTableValue* ScriptNetBindingTable::FindTableValue(const AZStd::string& name) const - { - const NetworkedTableValue* retVal = nullptr; - NetworkedTableMap::const_iterator tableIter = m_networkedTable.find(name); - - if (tableIter != m_networkedTable.end()) - { - retVal = &(tableIter->second); - } - - return retVal; - } - - //////////////////////////////// - // ScriptComponentReplicaChunk - //////////////////////////////// - - ScriptComponentReplicaChunk::ScriptComponentReplicaChunk() - : m_scriptRPC("ScriptRPC") - , m_enabledDataSetMask(0) - { - } - - ScriptComponentReplicaChunk::~ScriptComponentReplicaChunk() - { - for (int i=0; i < k_maxScriptableDataSets; ++i) - { - ScriptPropertyDataSet& dataSet = m_propertyDataSets[i]; - - dataSet.Modify([](AZ::ScriptProperty*& scriptProperty) - { - delete scriptProperty; - scriptProperty = nullptr; - return false; - }); - } - } - - bool ScriptComponentReplicaChunk::IsReplicaMigratable() - { - return true; - } - - AZ::u32 ScriptComponentReplicaChunk::CalculateDirtyDataSetMask(GridMate::MarshalContext& marshalContext) - { - if ((marshalContext.m_marshalFlags & GridMate::ReplicaMarshalFlags::ForceDirty)) - { - return m_enabledDataSetMask; - } - - return GridMate::ReplicaChunkBase::CalculateDirtyDataSetMask(marshalContext); - } - - bool ScriptComponentReplicaChunk::AssignDataSet(ScriptNetBindingTable::NetworkedTableValue& helper) - { - bool assigned = false; - - if (helper.HasForcedDataSetIndex()) - { - int testIndex = helper.GetForcedDataSetIndex() - 1; - - if (testIndex >= 0 && testIndex < k_maxScriptableDataSets) - { - ScriptPropertyDataSet* testDataSet = &m_propertyDataSets[testIndex]; - - if (!testDataSet->IsReserved()) - { - assigned = true; - helper.RegisterDataSet(testDataSet); - m_enabledDataSetMask |= (1 << testIndex); - } - else - { - AZ_Error("ScriptComponent",false,"Trying to register a networked value to a previously used DataSet."); - } - } - else - { - AZ_Error("ScriptComponent",false,"Trying to register a table value to an invalid DataSet index."); - } - } - else - { - for (int i=0; i < k_maxScriptableDataSets; ++i) - { - if (!m_propertyDataSets[i].IsReserved()) - { - assigned = true; - helper.RegisterDataSet(&m_propertyDataSets[i]); - m_enabledDataSetMask |= (1 << i); - break; - } - } - - AZ_Error("ScriptComponent",assigned, "Trying to create more then %i datasets for a script",k_maxScriptableDataSets); - } - - return assigned; - } - - void ScriptComponentReplicaChunk::AssignDataSetForProperty(ScriptNetBindingTable::NetworkedTableValue& helper, AZ::ScriptProperty* targetProperty) - { - AZ_Error("ScriptComponent",!IsMaster(),"Binding table value to specified DataSet on Master(Master should be making that choice, not responding to a choice)."); - - if (!IsMaster()) - { - for (int i=0; i < k_maxScriptableDataSets; ++i) - { - if (m_propertyDataSets[i].Get() == targetProperty) - { - helper.RegisterDataSet(&m_propertyDataSets[i]); - m_enabledDataSetMask |= (1 << i); - break; - } - } - } - } - - bool ScriptComponentReplicaChunk::SanityCheckDataSet(AZ::ScriptProperty* targetProperty, ScriptPropertyDataSet* assumedDataSet) - { - bool isSane = false; - - for (int i=0; i < k_maxScriptableDataSets; ++i) - { - if (m_propertyDataSets[i].Get() == targetProperty) - { - isSane = &(m_propertyDataSets[i]) == assumedDataSet; - break; - } - } - - return isSane; - } -} diff --git a/Code/Framework/AzFramework/AzFramework/Script/ScriptNetBindings.h b/Code/Framework/AzFramework/AzFramework/Script/ScriptNetBindings.h deleted file mode 100644 index eec28b71b0..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Script/ScriptNetBindings.h +++ /dev/null @@ -1,320 +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 AZFRAMEWORK_SCRIPT_NET_BINDINGS_H -#define AZFRAMEWORK_SCRIPT_NET_BINDINGS_H - -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace AzFramework -{ - class ScriptPropertyDataSet; - class ScriptComponentReplicaChunk; - - // ScriptNetBindingTable will act as the go between for the ScriptComponent and the Replica's. - // It will also allow for holding of values in the case where you haven't been bound to a replica chunk yet and the - // script tries to interact with something that is networked. - // - // Allows for scripts to be re-used seamlessly in a offline vs online scenario(and support for going from offline to online), - // including RPCs(will alawys call the master version if offline) - class ScriptNetBindingTable - : public GridMate::ReplicaChunkInterface - { - private: - friend class ScriptComponentReplicaChunk; - friend class ScriptPropertyDataSet; - - // Helper struct to keep track of a a ScriptContext - // and the entityTableReference. Mainly used for - // calling in to functions in LUA where we want - // to push in the table reference as the first parameter - struct EntityScriptContext - { - public: - EntityScriptContext(); - - void Unload(); - - bool HasEntityTableRegistryIndex() const; - int GetEntityTableRegistryIndex() const; - - bool HasScriptContext() const; - AZ::ScriptContext* GetScriptContext() const; - - void ConfigureContext(AZ::ScriptContext* scriptContext, int entityTableRegistryIndex); - - private: - - bool SanityCheckContext() const; - - AZ::ScriptContext* m_scriptContext; - int m_entityTableRegistryIndex; - }; - - class NetworkedTableValue; - friend NetworkedTableValue; - - typedef AZStd::unordered_map NetworkedTableMap; - - class RPCBindingHelper; - friend RPCBindingHelper; - - typedef AZStd::unordered_map RPCHelperMap; - - // Helper class that will wrap up our interactions with the actual stored value - // to hide the general use case of if we are connected to a replica or not. - // - // Additionally this will serve as a holding ground for a 'networked' - // value that doesn't have a dataset. - // - // Lastly holds onto the Callback references. - class NetworkedTableValue - { - public: - AZ_CLASS_ALLOCATOR(NetworkedTableValue, AZ::SystemAllocator, 0); - - NetworkedTableValue(AZ::ScriptProperty* initialValue = nullptr); - ~NetworkedTableValue(); - - void Destroy(); - - // Methods to register this value to a chunk - bool HasDataSet() const; - void RegisterDataSet(ScriptPropertyDataSet* dataSet); - void UnbindFromDataSet(); - ScriptPropertyDataSet* GetDataSet() const; - - // Information kept in order to force these values to use a particular dataset for debugging. - bool HasForcedDataSetIndex() const; - void SetForcedDataSetIndex(int index); - int GetForcedDataSetIndex() const; - - // Callback functions - bool HasCallback() const; - void RegisterCallback(int functionReference); - void ReleaseCallback(AZ::ScriptContext& scriptContext); - void InvokeCallback(EntityScriptContext& scriptContext, const GridMate::TimeContext& timeContext); - - bool AssignValue(AZ::ScriptDataContext& scriptDataContext, const AZStd::string& propertyName); - bool InspectValue(AZ::ScriptContext* scriptContext) const; - - // Methods used for unit tests - const AZ::ScriptProperty* GetShimmedScriptProperty() const { return m_shimmedScriptProperty; } - private: - - // This value will be used if we have a networked property, but don't have a valid chunk yet. - // Works as a temporary store, which will be resolved once we get assigned to a DataSet - AZ::ScriptProperty* m_shimmedScriptProperty; - - // The data set we are bound to - ScriptPropertyDataSet* m_dataSet; - int m_forcedDataSetIndex; - - int m_functionReference; - }; - - // Future thoughts - // - Move the actual RPC meta table creation - // into this guy - class RPCBindingHelper - { - public: - AZ_CLASS_ALLOCATOR(RPCBindingHelper, AZ::SystemAllocator, 0); - - RPCBindingHelper(); - ~RPCBindingHelper(); - - void ReleaseTableIndex(AZ::ScriptContext& scriptContext); - - bool IsValid() const; - - void SetMasterFunction(int masterReference); - bool InvokeMaster(EntityScriptContext& entityScriptContext, const ScriptRPCMarshaler::Container& params); - - void SetProxyFunction(int masterReference); - void InvokeProxy(EntityScriptContext& entityScriptContext, const ScriptRPCMarshaler::Container& params); - - private: - int m_masterReference; - int m_proxyReference; - }; - - public: - AZ_CLASS_ALLOCATOR(ScriptNetBindingTable, AZ::SystemAllocator, 0); - static void Reflect(AZ::ReflectContext* reflect); - - ScriptNetBindingTable(); - ~ScriptNetBindingTable(); - - void Unload(); - - void CreateNetworkBindingTable(AZ::ScriptContext* scriptContext, int baseTableIndex, int entityTableIndex); - void FinalizeNetworkTable(AZ::ScriptContext* scriptContext, int entityTableRegistryIndex); - - AZ::ScriptContext* GetScriptContext() const; - - bool IsMaster() const; - - ////////////////////////////////////////////////////////////////////////////////////////////////////// - // DataSet Functionality - // - // Called when the script wants to bind a function callback to when - // a value changes - // - // Might change this to just be register DataSet - bool RegisterDataSet(AZ::ScriptDataContext& stackContext, AZ::ScriptProperty* scriptProperty); - - // Called when the script wants to assign a value to the script value - bool AssignTableValue(AZ::ScriptDataContext& stackContext); - - // Called when the script wants to know the value of a script value. - bool InspectTableValue(AZ::ScriptDataContext& stackContext) const; - ////////////////////////////////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////////////////////////////////// - /// RPC Functionality - void RegisterRPC(AZ::ScriptDataContext& rpcTableContext, const AZStd::string& rpcName, int elementIndex, int tableStackIndex); - bool InvokeRPC(AZ::ScriptDataContext& stackContext); - ////////////////////////////////////////////////////////////////////////////////////////////////////// - - // Netbinding Interface duplication here to be called from the ScriptComponent - GridMate::ReplicaChunkPtr GetNetworkBinding(); - void SetNetworkBinding(GridMate::ReplicaChunkPtr chunk); - void UnbindFromNetwork(); - - void OnPropertyUpdate(AZ::ScriptProperty*const& scriptProperty, const GridMate::TimeContext& tc); - bool OnInvokeRPC(AZStd::string functionName, AZStd::vector< AZ::ScriptProperty*> properties, const GridMate::RpcContext& rpcContext); - - // Methods used for unit tests - const AZ::ScriptProperty* FindScriptProperty(const AZStd::string& name) const; - - - private: - - void RegisterMetaTableCache(); - - template - AZ::ScriptPropertyTable* ConvertPropertyArrayToTable(PropertyArrayType* arrayProperty) - { - AZ::ScriptPropertyTable* scriptPropertyTable = aznew AZ::ScriptPropertyTable(arrayProperty->m_name.c_str()); - - PropertyType propertyType; - - for (unsigned int i=0; i < arrayProperty->m_values.size(); ++i) - { - propertyType.m_value = arrayProperty->m_values[i]; - - // Offset by 1 to deal with lua 1 indexing. - // Table will make a clone of our object. - scriptPropertyTable->SetTableValue(i+1, &propertyType); - } - - return scriptPropertyTable; - } - - void AssignDataSets(); - - NetworkedTableValue* FindTableValue(const AZStd::string& name); - const NetworkedTableValue* FindTableValue(const AZStd::string& name) const; - - EntityScriptContext m_entityScriptContext; - - GridMate::ReplicaChunkPtr m_replicaChunk; - - NetworkedTableMap m_networkedTable; - RPCHelperMap m_rpcHelperMap; - }; - - // Typedeffing out the RPC and DataSet definitions. - typedef GridMate::Rpc< GridMate::RpcArg< AZStd::string >, GridMate::RpcArg< ScriptRPCMarshaler::Container, ScriptRPCMarshaler > >::BindInterface ScriptPropertyRPC; - typedef GridMate::DataSet::BindInterface ScriptPropertyDataSetType; - - class ScriptComponentReplicaChunk; - - // Specialized DataSet used by the ScriptProperties, just to add some wrapped around functionality - // and to allow me to manipulate the DataSet throttler in order to properly manage a dirty flag - class ScriptPropertyDataSet - : public ScriptPropertyDataSetType - , public AZ::ScriptPropertyWatcherBus::Handler - , public AZ::ScriptPropertyWatcher - { - private: - friend class ScriptComponentReplicaChunk; - friend class ScriptNetBindingTable::NetworkedTableValue; - - const char* GetDataSetName(); - - public: - ScriptPropertyDataSet(); - ~ScriptPropertyDataSet(); - bool IsReserved() const; - - bool UpdateScriptProperty(AZ::ScriptDataContext& scriptDataContext, const AZStd::string& propertyName); - void SetScriptProperty(AZ::ScriptProperty* scriptProperty); - - void OnObjectModified() override; - - private: - void Reserve(ScriptNetBindingTable::NetworkedTableValue* reserver); - void Release(ScriptNetBindingTable::NetworkedTableValue* reserver); - - ScriptNetBindingTable::NetworkedTableValue* m_reserver; - }; - - // The actual ReplicaChunk that the script will use - class ScriptComponentReplicaChunk - : public GridMate::ReplicaChunkBase - { - public: - AZ_CLASS_ALLOCATOR(ScriptComponentReplicaChunk, AZ::SystemAllocator,0); - static const int k_maxScriptableDataSets = GM_MAX_DATASETS_IN_CHUNK; - - static const char* GetChunkName() { return "ScriptComponentReplicaChunk"; } - - // Might want to add some type of comment field into the various fields so this can be properly parsed - // and determined what we are actually sending. - ScriptComponentReplicaChunk(); - ~ScriptComponentReplicaChunk(); - - bool IsReplicaMigratable() override; - - AZ::u32 CalculateDirtyDataSetMask(GridMate::MarshalContext& marshalContext) override; - - // Called from the Master, will assign the table value to the DataSet specified by the helper. - bool AssignDataSet(ScriptNetBindingTable::NetworkedTableValue& helper); - - // Called from teh Proxy. Will Assign the TableValue to the DataSet that contains the target property - void AssignDataSetForProperty(ScriptNetBindingTable::NetworkedTableValue& helper, AZ::ScriptProperty* targetProperty); - - // Only called inside of an assert, checks that the DataSet that the targetProperty is in is the same as the assumedDataSet - // Used to confirm that we don't get a confusion between master/proxy about which ScriptProperty is assigned to which DataSet. - bool SanityCheckDataSet(AZ::ScriptProperty* targetProperty, ScriptPropertyDataSet* assumedDataSet); - - ScriptPropertyRPC m_scriptRPC; - - private: - AZ::u32 m_enabledDataSetMask; - ScriptPropertyDataSet m_propertyDataSets[k_maxScriptableDataSets]; - }; -} - -#endif diff --git a/Code/Framework/AzFramework/AzFramework/TargetManagement/TargetManagementComponent.cpp b/Code/Framework/AzFramework/AzFramework/TargetManagement/TargetManagementComponent.cpp index e44185bd33..d3ba48d587 100644 --- a/Code/Framework/AzFramework/AzFramework/TargetManagement/TargetManagementComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/TargetManagement/TargetManagementComponent.cpp @@ -177,7 +177,7 @@ namespace AzFramework Neighborhood::NeighborReplicaPtr replicaChunk = GridMate::CreateReplicaChunk(session->GetMyMember()->GetId().Compact(), m_component->m_settings->m_persistentName.c_str(), Neighborhood::NEIGHBOR_CAP_LUA_VM | Neighborhood::NEIGHBOR_CAP_LUA_DEBUGGER); replicaChunk->SetDisplayName(m_component->m_settings->m_persistentName.c_str()); replica->AttachReplicaChunk(replicaChunk); - session->GetReplicaMgr()->AddMaster(replica); + session->GetReplicaMgr()->AddPrimary(replica); } } diff --git a/Code/Framework/AzFramework/AzFramework/azframework_files.cmake b/Code/Framework/AzFramework/AzFramework/azframework_files.cmake index 1b1cd49aa7..135d9d36bd 100644 --- a/Code/Framework/AzFramework/AzFramework/azframework_files.cmake +++ b/Code/Framework/AzFramework/AzFramework/azframework_files.cmake @@ -161,26 +161,6 @@ set(FILES Metrics/MetricsPlainTextNameRegistration.h Network/AssetProcessorConnection.cpp Network/AssetProcessorConnection.h - Network/DynamicSerializableFieldMarshaler.h - Network/EntityIdMarshaler.h - Network/InterestManagerComponent.h - Network/InterestManagerComponent.cpp - Network/NetBindable.h - Network/NetBindable.cpp - Network/NetBindingEventsBus.h - Network/NetBindingHandlerBus.h - Network/NetBindingSystemBus.h - Network/NetBindingComponent.h - Network/NetBindingComponent.cpp - Network/NetBindingComponentChunk.h - Network/NetBindingComponentChunk.cpp - Network/NetBindingSystemImpl.h - Network/NetBindingSystemImpl.cpp - Network/NetBindingSystemComponent.h - Network/NetBindingSystemComponent.cpp - Network/NetworkContext.h - Network/NetworkContext.cpp - Network/NetSystemBus.h Network/SocketConnection.cpp Network/SocketConnection.h Logging/LogFile.cpp @@ -203,10 +183,6 @@ set(FILES Script/ScriptDebugAgentBus.h Script/ScriptDebugMsgReflection.cpp Script/ScriptDebugMsgReflection.h - Script/ScriptMarshal.h - Script/ScriptMarshal.cpp - Script/ScriptNetBindings.h - Script/ScriptNetBindings.cpp Script/ScriptRemoteDebugging.cpp Script/ScriptRemoteDebugging.h StreamingInstall/StreamingInstall.h diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp index ac5f1136f5..70cad69268 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp @@ -1287,7 +1287,6 @@ namespace AzToolsFramework Field("Cached World Transform Parent", &TransformComponent::m_cachedWorldTransformParent)-> Field("Parent Activation Transform Mode", &TransformComponent::m_parentActivationTransformMode)-> Field("IsStatic", &TransformComponent::m_isStatic)-> - Field("Sync Enabled", &TransformComponent::m_netSyncEnabled)-> Field("InterpolatePosition", &TransformComponent::m_interpolatePosition)-> Field("InterpolateRotation", &TransformComponent::m_interpolateRotation)-> Version(9, &Internal::TransformComponentDataConverter); @@ -1322,21 +1321,7 @@ namespace AzToolsFramework Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Hide)-> DataElement(AZ::Edit::UIHandlers::Default, &TransformComponent::m_cachedWorldTransform, "Cached World Transform", "")-> Attribute(AZ::Edit::Attributes::SliceFlags, AZ::Edit::SliceFlags::NotPushable)-> - Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Hide)-> - - ClassElement(AZ::Edit::ClassElements::Group, "Network Sync")-> - Attribute(AZ::Edit::Attributes::AutoExpand, true)-> - - DataElement(AZ::Edit::UIHandlers::Default, &TransformComponent::m_netSyncEnabled, "Sync to replicas", "Sync to network replicas.")-> - DataElement(AZ::Edit::UIHandlers::ComboBox, &TransformComponent::m_interpolatePosition, - "Position Interpolation", "Enable local interpolation of position.")-> - EnumAttribute(AZ::InterpolationMode::NoInterpolation, "None")-> - EnumAttribute(AZ::InterpolationMode::LinearInterpolation, "Linear")-> - - DataElement(AZ::Edit::UIHandlers::ComboBox, &TransformComponent::m_interpolateRotation, - "Rotation Interpolation", "Enable local interpolation of rotation.")-> - EnumAttribute(AZ::InterpolationMode::NoInterpolation, "None")-> - EnumAttribute(AZ::InterpolationMode::LinearInterpolation, "Linear"); + Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Hide); ptrEdit->Class("Values", "XYZ PYR")-> DataElement(AZ::Edit::UIHandlers::Default, &EditorTransform::m_translate, "Translate", "Local Position (Relative to parent) in meters.")-> diff --git a/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.cpp b/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.cpp index e3b474ba5d..380739bab1 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.cpp +++ b/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.cpp @@ -1486,7 +1486,7 @@ namespace GridMate // Only support a single cipher suite in OpenSSL that supports: // - // ECDHE Master key exchange using ephemeral elliptic curve diffie-hellman. + // ECDHE Key exchange using ephemeral elliptic curve diffie-hellman. // RSA Authentication (public and private key) used to sign ECDHE parameters and can be checked against a CA. // AES256 AES cipher for symmetric key encryption using a 256-bit key. // GCM Mode of operation for symmetric key encryption. diff --git a/Code/Framework/GridMate/GridMate/Carrier/StreamSecureSocketDriver.cpp b/Code/Framework/GridMate/GridMate/Carrier/StreamSecureSocketDriver.cpp index 9e59496ed1..30c2c63ed9 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/StreamSecureSocketDriver.cpp +++ b/Code/Framework/GridMate/GridMate/Carrier/StreamSecureSocketDriver.cpp @@ -97,7 +97,7 @@ namespace GridMate // Only support a single cipher suite in OpenSSL that supports: // - // ECDHE Master key exchange using ephemeral elliptic curve diffie-hellman. + // ECDHE Key exchange using ephemeral elliptic curve diffie-hellman. // RSA Authentication (public and private key) used to sign ECDHE parameters and can be checked against a CA. // AES256 AES cipher for symmetric key encryption using a 256-bit key. // GCM Mode of operation for symmetric key encryption. diff --git a/Code/Framework/GridMate/GridMate/Replica/DataSet.cpp b/Code/Framework/GridMate/GridMate/Replica/DataSet.cpp index 614c50a7e0..fb6a6fe5cd 100644 --- a/Code/Framework/GridMate/GridMate/Replica/DataSet.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/DataSet.cpp @@ -52,6 +52,6 @@ namespace GridMate bool DataSetBase::CanSet() const { - return m_replicaChunk ? m_replicaChunk->IsMaster() : true; + return m_replicaChunk ? m_replicaChunk->IsPrimary() : true; } } diff --git a/Code/Framework/GridMate/GridMate/Replica/DataSet.h b/Code/Framework/GridMate/GridMate/Replica/DataSet.h index f91a86dcec..61ff75516b 100644 --- a/Code/Framework/GridMate/GridMate/Replica/DataSet.h +++ b/Code/Framework/GridMate/GridMate/Replica/DataSet.h @@ -43,7 +43,7 @@ namespace GridMate struct DataSetDefaultTraits { /** - * \brief Should a change in DataSet value invoke a callback on a master replica chunk? + * \brief Should a change in DataSet value invoke a callback on a primary replica chunk? * * By default, DataSet::BindInterface only invokes on client/non-authoritative replica chunks. * This switch enables the callback on server/authoritative replica chunks. @@ -55,7 +55,7 @@ namespace GridMate }; /** - * \brief Turns on DataSet callbacks to be invoked on the master replica as well as client replicas. + * \brief Turns on DataSet callbacks to be invoked on the primary replica as well as client replicas. */ struct DataSetInvokeEverywhereTraits : DataSetDefaultTraits { @@ -200,7 +200,7 @@ namespace GridMate } /** - Modify the DataSet. Call this on the Master node to change the data, + Modify the DataSet. Call this on the Primary node to change the data, which will be propagated to all proxies. **/ void Set(const DataType& v) @@ -214,7 +214,7 @@ namespace GridMate } /** - Modify the DataSet. Call this on the Master node to change the data, + Modify the DataSet. Call this on the Primary node to change the data, which will be propagated to all proxies. **/ void Set(DataType&& v) @@ -228,7 +228,7 @@ namespace GridMate } /** - Modify the DataSet. Call this on the Master node to change the data, + Modify the DataSet. Call this on the Primary node to change the data, which will be propagated to all proxies. **/ template @@ -243,7 +243,7 @@ namespace GridMate } /** - Modify the DataSet directly without copying it. Call this on the Master node, + Modify the DataSet directly without copying it. Call this on the Primary node, passing in a function object that takes the value by reference, optionally modifies the data, and returns true if the data was changed. **/ diff --git a/Code/Framework/GridMate/GridMate/Replica/DeltaCompressedDataSet.h b/Code/Framework/GridMate/GridMate/Replica/DeltaCompressedDataSet.h index cc19c2336b..8d88635c07 100644 --- a/Code/Framework/GridMate/GridMate/Replica/DeltaCompressedDataSet.h +++ b/Code/Framework/GridMate/GridMate/Replica/DeltaCompressedDataSet.h @@ -159,7 +159,7 @@ namespace GridMate } /** - Modify the DataSet. Call this on the Master node to change the data, + Modify the DataSet. Call this on the Primary node to change the data, which will be propagated to all proxies. **/ void Set(const FieldType& v) @@ -201,7 +201,7 @@ namespace GridMate private: DataSet m_absolutePortion; DataSet m_relativePortion; - FieldType m_combinedValue; // the latest value on either master or proxy + FieldType m_combinedValue; // the latest value on either primary or proxy }; //----------------------------------------------------------------------------- diff --git a/Code/Framework/GridMate/GridMate/Replica/Interest/BitmaskInterestHandler.cpp b/Code/Framework/GridMate/GridMate/Replica/Interest/BitmaskInterestHandler.cpp index 1a35fd1893..75f4c8bdd2 100644 --- a/Code/Framework/GridMate/GridMate/Replica/Interest/BitmaskInterestHandler.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/Interest/BitmaskInterestHandler.cpp @@ -366,7 +366,7 @@ namespace GridMate auto replica = Replica::CreateReplica("BitmaskInterestHandlerRules"); m_rulesReplica = CreateAndAttachReplicaChunk(replica); - m_rm->AddMaster(replica); + m_rm->AddPrimary(replica); } void BitmaskInterestHandler::OnRulesHandlerUnregistered(InterestManager* manager) diff --git a/Code/Framework/GridMate/GridMate/Replica/Interest/InterestManager.cpp b/Code/Framework/GridMate/GridMate/Replica/Interest/InterestManager.cpp index 770dcd4f1f..ff1a29a917 100644 --- a/Code/Framework/GridMate/GridMate/Replica/Interest/InterestManager.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/Interest/InterestManager.cpp @@ -206,7 +206,7 @@ namespace GridMate return false; } - if (replica->IsMaster()) // own the replica? + if (replica->IsPrimary()) // own the replica? { return true; } diff --git a/Code/Framework/GridMate/GridMate/Replica/Interest/ProximityInterestHandler.cpp b/Code/Framework/GridMate/GridMate/Replica/Interest/ProximityInterestHandler.cpp index 4e3c2c77a4..13a0151bc7 100644 --- a/Code/Framework/GridMate/GridMate/Replica/Interest/ProximityInterestHandler.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/Interest/ProximityInterestHandler.cpp @@ -508,7 +508,7 @@ namespace GridMate auto replica = Replica::CreateReplica("ProximityInterestHandlerRules"); m_rulesReplica = CreateAndAttachReplicaChunk(replica); - m_rm->AddMaster(replica); + m_rm->AddPrimary(replica); } void ProximityInterestHandler::OnRulesHandlerUnregistered(InterestManager* manager) diff --git a/Code/Framework/GridMate/GridMate/Replica/MigrationSequence.cpp b/Code/Framework/GridMate/GridMate/Replica/MigrationSequence.cpp index 48fbfe5289..a1150a198a 100644 --- a/Code/Framework/GridMate/GridMate/Replica/MigrationSequence.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/MigrationSequence.cpp @@ -26,7 +26,7 @@ namespace GridMate m_replicaMgr = replica->GetReplicaManager(); - if (replica->IsMaster() && newOwnerId != m_replicaMgr->GetLocalPeerId()) + if (replica->IsPrimary() && newOwnerId != m_replicaMgr->GetLocalPeerId()) { m_sm.SetStateHandler(AZ_HSM_STATE_NAME(MST_TOP), AZ::HSM::StateHandler(this, &MigrationSequence::DefaultHandler), AZ::HSM::InvalidStateId, MST_MIGRATING); } @@ -312,7 +312,7 @@ namespace GridMate return true; case ME_MODIFY_NEW_OWNER: m_newOwnerId = *static_cast(event.userData); - if (m_replica->IsMaster() && m_newOwnerId != m_replicaMgr->m_self.GetId()) + if (m_replica->IsPrimary() && m_newOwnerId != m_replicaMgr->m_self.GetId()) { sm.Transition(MST_MIGRATING); } diff --git a/Code/Framework/GridMate/GridMate/Replica/RemoteProcedureCall.h b/Code/Framework/GridMate/GridMate/Replica/RemoteProcedureCall.h index 98494267ad..4256dd978b 100644 --- a/Code/Framework/GridMate/GridMate/Replica/RemoteProcedureCall.h +++ b/Code/Framework/GridMate/GridMate/Replica/RemoteProcedureCall.h @@ -370,8 +370,8 @@ namespace GridMate PeerId sourcePeerId = GetSourcePeerId(); bool shouldQueue = true; bool processed = false; - bool isMaster = m_replicaChunk->IsMaster(); - if (isMaster) + bool isPrimary = m_replicaChunk->IsPrimary(); + if (isPrimary) { // We are authoritative so execute the RPC immediately, forwarding the args along RpcRequest localRequest(this, rc.m_realTime, rc.m_realTime, rc.m_localTime); @@ -385,7 +385,7 @@ namespace GridMate if (shouldQueue) { TypeTuple* storage = aznew TypeTuple(this, RpcContext(rc.m_realTime, rc.m_realTime, rc.m_localTime, sourcePeerId), AZStd::forward(args) ...); - storage->m_authoritative = isMaster; + storage->m_authoritative = isPrimary; storage->m_processed = processed; storage->m_reliable = Traits::s_isReliable; OnRpcRequest(storage); diff --git a/Code/Framework/GridMate/GridMate/Replica/Replica.cpp b/Code/Framework/GridMate/GridMate/Replica/Replica.cpp index 483e523e05..c0a92de0d8 100644 --- a/Code/Framework/GridMate/GridMate/Replica/Replica.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/Replica.cpp @@ -106,7 +106,7 @@ namespace GridMate //----------------------------------------------------------------------------- void Replica::Destroy() { - AZ_Assert(IsMaster(), "We don't own replica 0x%x!", GetRepId()); + AZ_Assert(IsPrimary(), "We don't own replica 0x%x!", GetRepId()); if (m_manager) { m_manager->Destroy(this); @@ -327,7 +327,7 @@ namespace GridMate if (IsActive()) { - if (IsMaster()) + if (IsPrimary()) { EBUS_EVENT(Debug::ReplicaDrillerBus, OnRequestReplicaChangeOwnership, this, requestor); diff --git a/Code/Framework/GridMate/GridMate/Replica/Replica.h b/Code/Framework/GridMate/GridMate/Replica/Replica.h index fb630ac1a4..5291a7f143 100644 --- a/Code/Framework/GridMate/GridMate/Replica/Replica.h +++ b/Code/Framework/GridMate/GridMate/Replica/Replica.h @@ -68,7 +68,7 @@ namespace GridMate Rep_ManagedAlloc = 1 << 1, Rep_CanMigrate = 1 << 2, Rep_New = 1 << 3, - Rep_Master = 1 << 4, + Rep_Primary = 1 << 4, Rep_Active = 1 << 6, Rep_ChangedOwner = 1 << 7, Rep_SuspendDownstream = 1 << 8, @@ -85,7 +85,7 @@ namespace GridMate void Destroy(); - void UpdateReplica(const ReplicaContext& rc); // Called when updating replica master from source + void UpdateReplica(const ReplicaContext& rc); // Called when updating replica primary from source void UpdateFromReplica(const ReplicaContext& rc); // Called when updating game with replica info bool AcceptChangeOwnership(PeerId requestor, const ReplicaContext& rc); // Return true to accept the transfer void OnActivate(const ReplicaContext& rc); @@ -112,8 +112,8 @@ namespace GridMate void RequestChangeOwnership(PeerId newOwner = InvalidReplicaPeerId); // If newOwner is not specified we assume it should be the local peer - bool IsMaster() const { return !IsActive() || !!(m_flags & Rep_Master); } - bool IsProxy() const { return !IsMaster(); } + bool IsPrimary() const { return !IsActive() || !!(m_flags & Rep_Primary); } + bool IsProxy() const { return !IsPrimary(); } bool IsNew() const { return !!(m_flags & Rep_New); } bool IsNewOwner() const { return !!(m_flags & Rep_ChangedOwner); } bool IsActive() const { return !!(m_flags & Rep_Active); } @@ -170,7 +170,7 @@ namespace GridMate void MarkRPCsAsRelayed(); - void SetMaster(bool isMaster) { m_flags = isMaster ? m_flags | Rep_Master : m_flags & ~Rep_Master; } + void SetPrimary(bool isPrimary) { m_flags = isPrimary ? m_flags | Rep_Primary : m_flags & ~Rep_Primary; } void SetNew() { m_flags |= Rep_New; } void SetRepId(ReplicaId id); void SetMigratable(bool migratable); diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.cpp b/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.cpp index 087f5f3273..adcff38190 100644 --- a/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.cpp @@ -125,18 +125,18 @@ namespace GridMate return false; } //----------------------------------------------------------------------------- - bool ReplicaChunkBase::IsMaster() const + bool ReplicaChunkBase::IsPrimary() const { if (m_replica) { - return m_replica->IsMaster(); + return m_replica->IsPrimary(); } return true; } //----------------------------------------------------------------------------- bool ReplicaChunkBase::IsProxy() const { - return !IsMaster(); + return !IsPrimary(); } //----------------------------------------------------------------------------- bool ReplicaChunkBase::IsDirty(AZ::u32 marshalFlags) const @@ -398,8 +398,8 @@ namespace GridMate { if (mc.m_peer != m_replica->m_upstreamHop) { - AZ_TracePrintf("GridMate", "Received dataset updates for replica id %08x(%s) from unexpected peer.", GetReplicaId(), IsActive() && IsMaster() ? "master" : "proxy"); - if (IsMaster()) + AZ_TracePrintf("GridMate", "Received dataset updates for replica id %08x(%s) from unexpected peer.", GetReplicaId(), IsActive() && IsPrimary() ? "primary" : "proxy"); + if (IsPrimary()) { mc.m_iBuf->Skip(mc.m_iBuf->Left()); return; @@ -547,7 +547,7 @@ namespace GridMate AZ_Assert(false, "Discarding non-authoritative RPC <%s> because s_allowNonAuthoritativeRequests trait is disabled!", GetDescriptor()->GetRpcName(this, rpc)); isRpcValid = false; } - if (!rpc->IsAllowNonAuthoritativeRequestsRelay() && !IsMaster()) + if (!rpc->IsAllowNonAuthoritativeRequestsRelay() && !IsPrimary()) { AZ_Assert(false, "Discarding non-authoritative RPC <%s> because s_allowNonAuthoritativeRequestRelay trait is disabled!", GetDescriptor()->GetRpcName(this, rpc)); isRpcValid = false; @@ -639,19 +639,19 @@ namespace GridMate for (RPCQueue::iterator iRPC = m_rpcQueue.begin(); iRPC != m_rpcQueue.end(); ) { Internal::RpcRequest* request = *iRPC; - bool isMaster = IsMaster(); // need to do this check after each RPC because ownership may change + bool isPrimary = IsPrimary(); // need to do this check after each RPC because ownership may change if (!m_replica->IsActive()) // this can happen if replica was deactivated within a previous RPC call { request->m_relayed = true; } - else if (!request->m_processed && (isMaster || request->m_authoritative)) + else if (!request->m_processed && (isPrimary || request->m_authoritative)) { request->m_realTime = rc.m_realTime; request->m_localTime = rc.m_localTime; bool ret = request->m_rpc->Invoke(request); request->m_processed = true; - if (isMaster) + if (isPrimary) { if (ret) { diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.h b/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.h index 7cfff0fe26..50b6bb8584 100644 --- a/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.h +++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.h @@ -45,17 +45,17 @@ namespace GridMate /** A single unit of network functionality A ReplicaChunk is a user extendable network object. One or more ReplicaChunks can be owned by a Replica, which is both a container and manager for them. A replica is owned - by a Master, and is propagated to other network nodes, who interact with is as a Proxy. + by a Primary, and is propagated to other network nodes, who interact with is as a Proxy. The data a ReplicaChunk contains should generally be related to the other data stored within it. Since multiple chunks can be attached to a Replica, unrelated data can simply be stored in other chunks on the same Replica. A ReplicaChunk has two primary ways to interact with it: DataSets and Remote Procedure Calls (RPCs). - DataSets store arbitrary data, which only the Master is able to modify. Any changes are + DataSets store arbitrary data, which only the Primary is able to modify. Any changes are propagated to the Proxy ReplicaChunks on the other nodes. RPCs are methods that can be executed on a remote node. They are first invoked on the - Master, who then decides if the invocation should be propagated to the Proxies. + Primary, who then decides if the invocation should be propagated to the Proxies. ReplicaChunks can be created by inheriting from the class and registered by calling ReplicaChunkDescriptorTable::RegisterChunkType() to create the factory required by @@ -107,7 +107,7 @@ namespace GridMate PeerId GetPeerId() const; virtual ReplicaManager* GetReplicaManager(); bool IsActive() const; - bool IsMaster() const; + bool IsPrimary() const; bool IsProxy() const; virtual void OnAttachedToReplica(Replica* replica) { (void) replica; } @@ -191,7 +191,7 @@ namespace GridMate void AddDataSetEvent(DataSetBase* dataset); // Called to enqueue a user event handler for a modified DataSet on a proxy node - void SignalDataSetChanged(const DataSetBase& dataset); // Called when the DataSet changes on the master node + void SignalDataSetChanged(const DataSetBase& dataset); // Called when the DataSet changes on the primary node void EnqueueMarshalTask(); diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaDrillerEvents.h b/Code/Framework/GridMate/GridMate/Replica/ReplicaDrillerEvents.h index 09b454a03e..14e70a3213 100644 --- a/Code/Framework/GridMate/GridMate/Replica/ReplicaDrillerEvents.h +++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaDrillerEvents.h @@ -62,7 +62,7 @@ namespace GridMate //! Called when an ownership transfer request is received. virtual void OnRequestReplicaChangeOwnership(Replica* replica, PeerId requestor) { (void)replica; (void)requestor; } //! Called when a replica changes ownership, not necessarily to or from the local node. - virtual void OnReplicaChangeOwnership(Replica* replica, bool wasMaster) { (void)replica; (void)wasMaster; } + virtual void OnReplicaChangeOwnership(Replica* replica, bool wasPrimary) { (void)replica; (void)wasPrimary; } //! Called when a chunk has been created. It doesn't mean it will be added to the system. //! Object will be partially constructed at this point if you inherit from ReplicaChunk @@ -91,9 +91,9 @@ namespace GridMate //! Called when data is received for a dataset. virtual void OnReceiveDataSet(ReplicaChunkBase* chunk, AZ::u32 chunkIndex, DataSetBase* dataSet, PeerId from, PeerId to, const void* data, size_t len) { (void)chunk; (void)chunkIndex; (void)dataSet; (void)from; (void)to; (void)data; (void)len; } - //! Called when an rpc request is received. RpcRequest pointer will be null if rpc is called on master replica. + //! Called when an rpc request is received. RpcRequest pointer will be null if rpc is called on primary replica. virtual void OnRequestRpc(ReplicaChunkBase* chunk, Internal::RpcRequest* rpc) { (void)chunk; (void)rpc; } - //! Called when an rpc is invoked. RpcRequest pointer will be null if rpc is called on master replica. + //! Called when an rpc is invoked. RpcRequest pointer will be null if rpc is called on primary replica. virtual void OnInvokeRpc(ReplicaChunkBase* chunk, Internal::RpcRequest* rpc) { (void)chunk; (void)rpc; } //! Called every time an rpc is sent to a peer. virtual void OnSendRpc(ReplicaChunkBase* chunk, AZ::u32 chunkIndex, Internal::RpcRequest* rpc, PeerId from, PeerId to, const void* data, size_t len) { (void)chunk; (void)chunkIndex; (void)rpc; (void)from; (void)to; (void)data; (void)len; } diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.cpp b/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.cpp index 32a941ef4a..78d6f260db 100644 --- a/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.cpp @@ -386,7 +386,7 @@ namespace GridMate replica->SetMigratable(true); // register global session info - // this one is kind of special so don't go through AddMaster() + // this one is kind of special so don't go through AddPrimary() ReplicaContext rc(this, GetTime(), &m_self); replica->m_createTime = rc.m_realTime; replica->SetRepId(RepId_SessionInfo); @@ -405,7 +405,7 @@ namespace GridMate else { // take over ownership of the session info - AZ_Assert(!m_sessionInfo->IsMaster(), "We just became host but we were already the owner of sessionInfo!"); + AZ_Assert(!m_sessionInfo->IsPrimary(), "We just became host but we were already the owner of sessionInfo!"); AZ_Assert(m_sessionInfo->m_pHostPeer->IsOrphan(), "We can't be promoted if we are still connected to the host!"); m_sessionInfo->m_pHostPeer->Remove(m_sessionInfo->GetReplica()); m_self.Add(m_sessionInfo->GetReplica()); @@ -903,7 +903,7 @@ namespace GridMate ReplicaContext rc(this, GetTime()); for (auto& replicaObject : m_self.m_objectsTimeSort) { - if (replicaObject.m_replica->IsMaster()) + if (replicaObject.m_replica->IsPrimary()) { replicaObject.m_replica->UpdateReplica(rc); } @@ -1357,11 +1357,11 @@ namespace GridMate m_flags &= ~Rm_Processing; } //----------------------------------------------------------------------------- - void ReplicaManager::RegisterReplica(const ReplicaPtr& pReplica, bool isMaster, ReplicaContext& rc) + void ReplicaManager::RegisterReplica(const ReplicaPtr& pReplica, bool isPrimary, ReplicaContext& rc) { AZ_Assert((pReplica->m_flags & ~Replica::Rep_Traits) == 0, "This replica is not clean, flags=0x%x, rpcs=%d!", pReplica->m_flags); AZ_Assert(pReplica->GetRepId() != InvalidReplicaId, "You should set the replica ID before you register it!"); - pReplica->SetMaster(isMaster); + pReplica->SetPrimary(isPrimary); pReplica->SetNew(); auto it = m_replicas.insert(AZStd::make_pair(pReplica->GetRepId(), pReplica)); // register with lookup table (void)it; @@ -1371,21 +1371,21 @@ namespace GridMate OnReplicaChanged(pReplica); } //----------------------------------------------------------------------------- - ReplicaId ReplicaManager::AddMaster(const ReplicaPtr& pMaster) + ReplicaId ReplicaManager::AddPrimary(const ReplicaPtr& pPrimary) { AZ_Assert(IsReady(), "ReplicaManager is not ready!"); - AZ_Assert(pMaster, "Attempting to register NULL replica!"); + AZ_Assert(pPrimary, "Attempting to register NULL replica!"); ReplicaId newId = m_localIdBlocks.Alloc(); ReplicaContext rc(this, GetTime(), &m_self); - pMaster->m_createTime = rc.m_realTime; - pMaster->SetRepId(newId); - m_self.Add(pMaster.get()); - AZStd::static_pointer_cast(pMaster->m_replicaStatus)->m_ownerSeq.Set(1); - pMaster->InitReplica(this); - RegisterReplica(pMaster, true, rc); + pPrimary->m_createTime = rc.m_realTime; + pPrimary->SetRepId(newId); + m_self.Add(pPrimary.get()); + AZStd::static_pointer_cast(pPrimary->m_replicaStatus)->m_ownerSeq.Set(1); + pPrimary->InitReplica(this); + RegisterReplica(pPrimary, true, rc); - //AZ_TracePrintf("GridMate", "Peer 0x%x: Added replica master 0x%x.\n", - // GetLocalPeerId(), pMaster->GetRepId()); + //AZ_TracePrintf("GridMate", "Peer 0x%x: Added replica primary 0x%x.\n", + // GetLocalPeerId(), pPrimary->GetRepId()); return newId; } @@ -1458,9 +1458,9 @@ namespace GridMate continue; } - ReplicaPeer* source = replica->IsMaster() ? &m_self : replica->m_upstreamHop; + ReplicaPeer* source = replica->IsPrimary() ? &m_self : replica->m_upstreamHop; - if (replica->IsMaster() + if (replica->IsPrimary() || (IsSyncHost() && source->GetId() != target->GetId() && !(source->GetMode() == Mode_Peer && target->GetMode() == Mode_Peer))) { ReplicaTarget::AddReplicaTarget(target, replica.get()); @@ -1471,7 +1471,7 @@ namespace GridMate else { // Replica might've changed owner -> we need to update its targets accordingly - ReplicaPeer* source = replica->IsMaster() ? &m_self : replica->m_upstreamHop; + ReplicaPeer* source = replica->IsPrimary() ? &m_self : replica->m_upstreamHop; for (auto it = replica->m_targets.begin(); it != replica->m_targets.end(); ) { @@ -1652,14 +1652,14 @@ namespace GridMate } } //----------------------------------------------------------------------------- - void ReplicaManager::ChangeReplicaOwnership(ReplicaPtr replica, const ReplicaContext& rc, bool isMaster) + void ReplicaManager::ChangeReplicaOwnership(ReplicaPtr replica, const ReplicaContext& rc, bool isPrimary) { - bool wasMaster = replica->IsMaster(); - if (wasMaster != isMaster) // wasMaster == isMaster can happen when host's replica is moved to client, and client confirms with Cmd_NewOwner + bool wasPrimary = replica->IsPrimary(); + if (wasPrimary != isPrimary) // wasPrimary == isPrimary can happen when host's replica is moved to client, and client confirms with Cmd_NewOwner { - replica->SetMaster(isMaster); + replica->SetPrimary(isPrimary); replica->OnChangeOwnership(rc); - EBUS_EVENT(Debug::ReplicaDrillerBus, OnReplicaChangeOwnership, replica.get(), wasMaster); + EBUS_EVENT(Debug::ReplicaDrillerBus, OnReplicaChangeOwnership, replica.get(), wasPrimary); } } //----------------------------------------------------------------------------- diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.h b/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.h index 55b8551441..00de7e9e11 100644 --- a/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.h +++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.h @@ -190,7 +190,7 @@ namespace GridMate //----------------------------------------------------------------------------- struct ReplicaMgrDesc { - // Single-master roles that replica managers can have + // Single-primary roles that replica managers can have enum Roles { Role_SyncHost = 1 << 0, @@ -421,13 +421,13 @@ namespace GridMate size_t ReleaseIdBlock(PeerId requestor); void _Unmarshal(ReadBuffer& rb, ReplicaPeer* from); - void RegisterReplica(const ReplicaPtr& pReplica, bool isMaster, ReplicaContext& rc); + void RegisterReplica(const ReplicaPtr& pReplica, bool isPrimary, ReplicaContext& rc); void UnregisterReplica(const ReplicaPtr& replica, const ReplicaContext& rc); void RemoveReplicaFromDownstream(const ReplicaPtr& replica, const ReplicaContext& rc); void MigrateReplica(ReplicaPtr replica, PeerId newOwnerId); void AnnounceReplicaMigrated(ReplicaId replicaId, PeerId newOwnerId); void OnReplicaMigrated(ReplicaPtr replica, bool isOwner, const ReplicaContext& rc); - void ChangeReplicaOwnership(ReplicaPtr replica, const ReplicaContext& rc, bool isMaster); + void ChangeReplicaOwnership(ReplicaPtr replica, const ReplicaContext& rc, bool isPrimary); void AckUpstreamSuspended(ReplicaId replicaId, PeerId sendTo, AZ::u32 requestTime); void OnAckUpstreamSuspended(ReplicaId replicaId, PeerId from, AZ::u32 requestTime); void AckDownstream(ReplicaId replicaId, PeerId sendTo, AZ::u32 requestTime); @@ -595,7 +595,7 @@ namespace GridMate * Replicas */ virtual ReplicaPtr FindReplica(ReplicaId replicaId); - ReplicaId AddMaster(const ReplicaPtr& pMaster); + ReplicaId AddPrimary(const ReplicaPtr& pPrimary); /* * Tasks diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaStatus.h b/Code/Framework/GridMate/GridMate/Replica/ReplicaStatus.h index 7e72dbab63..f3afb7747d 100644 --- a/Code/Framework/GridMate/GridMate/Replica/ReplicaStatus.h +++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaStatus.h @@ -50,10 +50,10 @@ namespace GridMate //! Called on the originator node to request replica migration. Rpc >::BindInterface RequestOwnership; - //! Called by the master to suspend upstream requests during replica migration. + //! Called by the primary to suspend upstream requests during replica migration. Rpc, RpcArg >::BindInterface MigrationSuspendUpstream; - //! Called by the master to signal downstream flush during replica migration. + //! Called by the primary to signal downstream flush during replica migration. Rpc, RpcArg >::BindInterface MigrationRequestDownstreamAck; struct ReplicaOptions diff --git a/Code/Framework/GridMate/GridMate/Replica/SystemReplicas.cpp b/Code/Framework/GridMate/GridMate/Replica/SystemReplicas.cpp index cbaf97ad1d..944524ed2f 100644 --- a/Code/Framework/GridMate/GridMate/Replica/SystemReplicas.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/SystemReplicas.cpp @@ -84,7 +84,7 @@ namespace GridMate // on activation of this replica, create our PeerInfo replica Replica* peerReplica = Replica::CreateReplica("PeerInfo"); CreateAndAttachReplicaChunk(peerReplica); - rc.m_rm->AddMaster(peerReplica); + rc.m_rm->AddPrimary(peerReplica); } //----------------------------------------------------------------------------- void SessionInfo::OnReplicaDeactivate(const ReplicaContext& rc) @@ -132,7 +132,7 @@ namespace GridMate (void)rc; if (m_pMgr->IsSyncHost()) { - AZ_Assert(IsMaster(), "The host should always own sessionInfo!!!"); + AZ_Assert(IsPrimary(), "The host should always own sessionInfo!!!"); AZ_Assert(m_pendingPeerReports.find(peerId) == m_pendingPeerReports.end(), "We are already waiting for reports for peer 0x%8x!", peerId); vector peers; @@ -205,7 +205,7 @@ namespace GridMate //----------------------------------------------------------------------------- void PeerReplica::OnReplicaActivate(const ReplicaContext& rc) { - if (IsMaster()) + if (IsPrimary()) { m_peerId.Set(rc.m_rm->GetLocalPeerId()); } diff --git a/Code/Framework/GridMate/GridMate/Replica/Tasks/ReplicaMarshalTasks.cpp b/Code/Framework/GridMate/GridMate/Replica/Tasks/ReplicaMarshalTasks.cpp index e295e74556..37c0c1d8c4 100644 --- a/Code/Framework/GridMate/GridMate/Replica/Tasks/ReplicaMarshalTasks.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/Tasks/ReplicaMarshalTasks.cpp @@ -294,7 +294,7 @@ namespace GridMate //----------------------------------------------------------------------------- ReplicaTask::TaskStatus ReplicaMarshalZombieTask::Run(const RunContext& context) { - if (m_replica->IsMaster() || context.m_replicaManager->IsSyncHost()) + if (m_replica->IsPrimary() || context.m_replicaManager->IsSyncHost()) { m_replica->PrepareData(context.m_replicaManager->GetGridMate()->GetDefaultEndianType(), // A zombie task occurs right before replica gets removed, by design it needs to set all properties one last time. diff --git a/Code/Framework/GridMate/GridMate/Replica/Tasks/ReplicaUpdateTasks.h b/Code/Framework/GridMate/GridMate/Replica/Tasks/ReplicaUpdateTasks.h index 7d9d7e90fe..61e11ed56d 100644 --- a/Code/Framework/GridMate/GridMate/Replica/Tasks/ReplicaUpdateTasks.h +++ b/Code/Framework/GridMate/GridMate/Replica/Tasks/ReplicaUpdateTasks.h @@ -35,7 +35,7 @@ namespace GridMate }; /** - * Task to update master & proxy replicas. + * Task to update primary & proxy replicas. * Processes RPCs and calls replicas UpdateFromReplica. Will complete immediately if no RPCs * left queued after processing, otherweise will be repeated next update tick. * Initiates replica migration if proxy owner has died. diff --git a/Code/Framework/GridMate/GridMate/Session/Session.cpp b/Code/Framework/GridMate/GridMate/Session/Session.cpp index cf9edff496..9e8aab50ec 100644 --- a/Code/Framework/GridMate/GridMate/Session/Session.cpp +++ b/Code/Framework/GridMate/GridMate/Session/Session.cpp @@ -960,7 +960,7 @@ GridSession::AddMember(GridMember* member) replica->AttachReplicaChunk(member); } - m_replicaMgr->AddMaster(replica); + m_replicaMgr->AddPrimary(replica); member->m_isHost.Set(member->IsLocal()); } @@ -1583,7 +1583,7 @@ GridSession::OnStateCreate(HSM& sm, const HSM::Event& e) // Bind session replica Replica* stateReplica = Replica::CreateReplica("SessionStateInfo"); stateReplica->AttachReplicaChunk(m_state); - m_replicaMgr->AddMaster(stateReplica); + m_replicaMgr->AddPrimary(stateReplica); // Bind member replica bool isAdded = AddMember(m_myMember); @@ -2005,7 +2005,7 @@ GridMember::OnReplicaActivate(const ReplicaContext& rc) { // if this member is me... add my state to the system. AZ_Assert(m_session->GetMyMember() == this, "The only local member should be myMember too!"); - rc.m_rm->AddMaster(m_clientState->GetReplica()); + rc.m_rm->AddPrimary(m_clientState->GetReplica()); // Both member and client state are valid! send member joined message EBUS_DBG_EVENT(Debug::SessionDrillerBus, OnMemberJoined, m_session, this); @@ -2052,7 +2052,7 @@ GridMember::OnReplicaChangeOwnership(const ReplicaContext& rc) { (void)rc; AZ_Assert(m_session->IsMigratingHost(), "This function can be called only during host migration!"); - if (IsMaster()) + if (IsPrimary()) { // Host owns the members, if I became the owner means I am the HOST! if (m_session->m_myMember == this) @@ -2084,7 +2084,7 @@ GridMember::OnKick(AZ::u8 reason, const RpcContext& rc) m_session->Leave(false); } - return true; // this is called only on the master + return true; // this is called only on the primary } return false; } @@ -2320,8 +2320,8 @@ void GridMemberStateReplica::OnReplicaDeactivate(const ReplicaContext& rc) { (void)rc; - // for master (this is our state) we always keep it. So don't do anything. - if (IsMaster()) + // for primary (this is our state) we always keep it. So don't do anything. + if (IsPrimary()) { return; } diff --git a/Code/Framework/GridMate/Tests/Interest.cpp b/Code/Framework/GridMate/Tests/Interest.cpp index b4fb9b7654..c449c92083 100644 --- a/Code/Framework/GridMate/Tests/Interest.cpp +++ b/Code/Framework/GridMate/Tests/Interest.cpp @@ -534,7 +534,7 @@ namespace GridMate auto replica = Replica::CreateReplica("ProximityInterestHandlerRules"); m_rulesReplica = CreateAndAttachReplicaChunk(replica); - m_rm->AddMaster(replica); + m_rm->AddPrimary(replica); } void ProximityInterestHandler::OnRulesHandlerUnregistered(InterestManager* manager) @@ -658,7 +658,7 @@ class Integ_InterestTest { AZ_Printf("GridMate", "InterestTestChunk::OnReplicaActivate repId=%08X(%s) fromPeerId=%08X localPeerId=%08X\n", GetReplicaId(), - IsMaster() ? "master" : "proxy", + IsPrimary() ? "primary" : "proxy", rc.m_peer ? rc.m_peer->GetId() : 0, rc.m_rm->GetLocalPeerId()); @@ -674,7 +674,7 @@ class Integ_InterestTest { AZ_Printf("GridMate", "InterestTestChunk::OnReplicaDeactivate repId=%08X(%s) fromPeerId=%08X localPeerId=%08X\n", GetReplicaId(), - IsMaster() ? "master" : "proxy", + IsPrimary() ? "primary" : "proxy", rc.m_peer ? rc.m_peer->GetId() : 0, rc.m_rm->GetLocalPeerId()); @@ -734,7 +734,7 @@ class Integ_InterestTest m_replica->m_data.Set(m_num); m_replica->m_bitmaskAttributeData.Set(1 << i); - m_session->GetReplicaMgr()->AddMaster(r); + m_session->GetReplicaMgr()->AddPrimary(r); } void UpdateAttribute() @@ -952,7 +952,7 @@ public: if (numUpdates == 250) { - // Checking everybody lost all replicas (except master) + // Checking everybody lost all replicas (except primary) for (int i = 0; i < k_numMachines; ++i) { for (int j = 0; j < k_numMachines; ++j) @@ -1079,11 +1079,11 @@ class LargeWorldTest void OnReplicaActivate(const ReplicaContext& rc) override { - /*if (!IsMaster())*/ + /*if (!IsPrimary())*/ /*{ AZ_Printf("GridMate", "LargeWorldTestChunk::OnReplicaActivate repId=%08X(%s) fromPeerId=%08X localPeerId=%08X\n", GetReplicaId(), - IsMaster() ? "master" : "proxy", + IsPrimary() ? "primary" : "proxy", rc.m_peer ? rc.m_peer->GetId() : 0, rc.m_rm->GetLocalPeerId()); }*/ @@ -1214,7 +1214,7 @@ class LargeWorldTest m_replicas.push_back(replica); - m_session->GetReplicaMgr()->AddMaster(r); + m_session->GetReplicaMgr()->AddPrimary(r); } void PopulateWorld() @@ -1453,7 +1453,7 @@ public: if (numUpdates == 250) { - // Checking everybody lost all replicas (except master) + // Checking everybody lost all replicas (except primary) for (int i = 0; i < k_numMachines; ++i) { /*for (int j = 0; j < k_numMachines; ++j) diff --git a/Code/Framework/GridMate/Tests/Replica.cpp b/Code/Framework/GridMate/Tests/Replica.cpp index 4d2f8d1e3a..624ee8c7e0 100644 --- a/Code/Framework/GridMate/Tests/Replica.cpp +++ b/Code/Framework/GridMate/Tests/Replica.cpp @@ -1615,7 +1615,7 @@ public: { (void)f; (void)rc; - AZ_TracePrintf("GridMate", "Executed MyHandler123 requested at %u with %g on %s at %u.\n", rc.m_timestamp, f, GetReplica()->IsMaster() ? "Master" : "Proxy", rc.m_realTime); + AZ_TracePrintf("GridMate", "Executed MyHandler123 requested at %u with %g on %s at %u.\n", rc.m_timestamp, f, GetReplica()->IsPrimary() ? "Primary" : "Proxy", rc.m_realTime); return true; } @@ -1653,14 +1653,14 @@ public: (void)rc; if (rc.m_rm->GetUserContext(12345)) { - AZ_TracePrintf("GridMate", "Activate %s with UserData:%p\n", GetReplica()->IsMaster() ? "master" : "proxy", rc.m_rm->GetUserContext(12345)); + AZ_TracePrintf("GridMate", "Activate %s with UserData:%p\n", GetReplica()->IsPrimary() ? "primary" : "proxy", rc.m_rm->GetUserContext(12345)); } if (IsProxy()) { Bind(aznew MyObj()); } - if (IsMaster()) + if (IsPrimary()) { EBUS_EVENT(MigratableReplicaDebugMsgs::EBus, OnNewOwner, GetReplicaId(), rc.m_rm); } @@ -1679,9 +1679,9 @@ public: void OnReplicaChangeOwnership(const ReplicaContext& rc) override { (void)rc; - AZ_TracePrintf("GridMate", "Migratable replica 0x%x became %s on Peer %d\n", (int) GetReplicaId(), IsMaster() ? "master" : "proxy", (int) rc.m_rm->GetLocalPeerId()); + AZ_TracePrintf("GridMate", "Migratable replica 0x%x became %s on Peer %d\n", (int) GetReplicaId(), IsPrimary() ? "primary" : "proxy", (int) rc.m_rm->GetLocalPeerId()); - if (IsMaster()) + if (IsPrimary()) { EBUS_EVENT(MigratableReplicaDebugMsgs::EBus, OnNewOwner, GetReplicaId(), rc.m_rm); } @@ -1725,7 +1725,7 @@ protected: { (void)f; (void)rc; - AZ_TracePrintf("GridMate", "Executed MyHandler123 requested at %u with %g on %s at %u.\n", rc.m_timestamp, f, IsMaster() ? "Master" : "Proxy", rc.m_realTime); + AZ_TracePrintf("GridMate", "Executed MyHandler123 requested at %u with %g on %s at %u.\n", rc.m_timestamp, f, IsPrimary() ? "Primary" : "Proxy", rc.m_realTime); return true; } bool MyHandler2(const float& f, int p2, const RpcContext& rc) @@ -1733,7 +1733,7 @@ protected: (void)f; (void)p2; (void)rc; - AZ_TracePrintf("GridMate", "Executed MyHandler2 requested at %u with %g,%d on %s at %u.\n", rc.m_timestamp, f, p2, IsMaster() ? "Master" : "Proxy", rc.m_realTime); + AZ_TracePrintf("GridMate", "Executed MyHandler2 requested at %u with %g,%d on %s at %u.\n", rc.m_timestamp, f, p2, IsPrimary() ? "Primary" : "Proxy", rc.m_realTime); return true; } bool MyHandler3(const float& f, int p2, EBla p3, const RpcContext& rc) @@ -1742,7 +1742,7 @@ protected: (void)p2; (void)p3; (void)rc; - AZ_TracePrintf("GridMate", "Executed MyHandler3 requested at %u with %g,%d,%d on %s at %u.\n", rc.m_timestamp, f, p2, p3, IsMaster() ? "Master" : "Proxy", rc.m_realTime); + AZ_TracePrintf("GridMate", "Executed MyHandler3 requested at %u with %g,%d,%d on %s at %u.\n", rc.m_timestamp, f, p2, p3, IsPrimary() ? "Primary" : "Proxy", rc.m_realTime); return true; } bool MyHandler4(const float& f, int p2, EBla p3, const IntVectorType& p4, const RpcContext& rc) @@ -1752,13 +1752,13 @@ protected: (void)p3; (void)p4; (void)rc; - AZ_TracePrintf("GridMate", "Executed MyHandler4 requested at %u with %g,%d,%d,%d,%d on %s at %u.\n", rc.m_timestamp, f, p2, p3, p4[0], p4[1], IsMaster() ? "Master" : "Proxy", rc.m_realTime); + AZ_TracePrintf("GridMate", "Executed MyHandler4 requested at %u with %g,%d,%d,%d,%d on %s at %u.\n", rc.m_timestamp, f, p2, p3, p4[0], p4[1], IsPrimary() ? "Primary" : "Proxy", rc.m_realTime); return true; } bool MyHandlerUnreliable(const int& i, const RpcContext& rc) { (void)rc; - AZ_TracePrintf("GridMate", "Executed MyHandlerUnreliable requested at %u with %d on %s at %u.\n", rc.m_timestamp, i, IsMaster() ? "Master" : "Proxy", rc.m_realTime); + AZ_TracePrintf("GridMate", "Executed MyHandlerUnreliable requested at %u with %d on %s at %u.\n", rc.m_timestamp, i, IsPrimary() ? "Primary" : "Proxy", rc.m_realTime); AZ_TEST_ASSERT(i > m_prevUnreliableValue); if ((i - m_prevUnreliableValue) > 1) { @@ -1824,7 +1824,7 @@ public: (void)rc; if (rc.m_rm->GetUserContext(12345)) { - AZ_TracePrintf("GridMate", "Activate %s with UserData:%p\n", IsMaster() ? "master" : "proxy", rc.m_rm->GetUserContext(12345)); + AZ_TracePrintf("GridMate", "Activate %s with UserData:%p\n", IsPrimary() ? "primary" : "proxy", rc.m_rm->GetUserContext(12345)); } if (IsProxy()) { @@ -1845,7 +1845,7 @@ public: void OnReplicaChangeOwnership(const ReplicaContext& rc) override { (void)rc; - AZ_TracePrintf("GridMate", "NonMigratable replica 0x%x became %s on Peer %d\n", (int) GetReplicaId(), IsMaster() ? "master" : "proxy", (int) rc.m_rm->GetLocalPeerId()); + AZ_TracePrintf("GridMate", "NonMigratable replica 0x%x became %s on Peer %d\n", (int) GetReplicaId(), IsPrimary() ? "primary" : "proxy", (int) rc.m_rm->GetLocalPeerId()); } void Bind(MyObj* pObj) @@ -1950,7 +1950,7 @@ TEST_F(Integ_ReplicaGMTest, ReplicaTest) // put something on s1 to get it going auto rep = Replica::CreateReplica(nullptr); s1rep1 = CreateAndAttachReplicaChunk(rep); - s1rep1id = sessions[s1].GetReplicaMgr().AddMaster(rep); + s1rep1id = sessions[s1].GetReplicaMgr().AddPrimary(rep); s1rep1->Bind(s1obj1 = aznew MyObj()); // connect s2 to s1 @@ -1993,7 +1993,7 @@ TEST_F(Integ_ReplicaGMTest, ReplicaTest) { auto newReplica = Replica::CreateReplica(nullptr); s2rep1 = CreateAndAttachReplicaChunk(newReplica); - s2rep1id = sessions[s2].GetReplicaMgr().AddMaster(newReplica); + s2rep1id = sessions[s2].GetReplicaMgr().AddPrimary(newReplica); s2rep1->Bind(s2obj1 = aznew MyObj()); } else @@ -2020,7 +2020,7 @@ TEST_F(Integ_ReplicaGMTest, ReplicaTest) { auto newReplica = Replica::CreateReplica(nullptr); s1rep2 = CreateAndAttachReplicaChunk(newReplica); - s1rep2id = sessions[s1].GetReplicaMgr().AddMaster(newReplica); + s1rep2id = sessions[s1].GetReplicaMgr().AddPrimary(newReplica); s1rep2->Bind(s1obj2 = aznew MyObj); } else @@ -2041,7 +2041,7 @@ TEST_F(Integ_ReplicaGMTest, ReplicaTest) { auto newReplica = Replica::CreateReplica(nullptr); s3rep1 = CreateAndAttachReplicaChunk(newReplica); - s3rep1id = sessions[s3].GetReplicaMgr().AddMaster(newReplica); + s3rep1id = sessions[s3].GetReplicaMgr().AddPrimary(newReplica); s3rep1->Bind(s3obj1 = aznew MyObj()); } else @@ -2289,13 +2289,13 @@ TEST_F(Integ_ForcedReplicaMigrationTest, ForcedReplicaMigrationTest) { auto rep = Replica::CreateReplica(nullptr); migrRep[i] = CreateAndAttachReplicaChunk(rep, aznew MyObj()); - peers[i].GetReplicaMgr().AddMaster(rep); + peers[i].GetReplicaMgr().AddPrimary(rep); AZ_TEST_ASSERT(m_replicaOwnership[migrRep[i]->GetReplicaId()] == &peers[i].GetReplicaMgr()); } { auto rep = Replica::CreateReplica(nullptr); nonMigrRep[i] = CreateAndAttachReplicaChunk(rep, aznew MyObj()); - peers[i].GetReplicaMgr().AddMaster(rep); + peers[i].GetReplicaMgr().AddPrimary(rep); } } addReplicas = false; @@ -2418,7 +2418,7 @@ public: void OnReplicaActivate(const ReplicaContext& rc) override { - if (IsMaster()) + if (IsPrimary()) { m_owner.Set(rc.m_rm->GetLocalPeerId() - 1); m_control.Set(rc.m_rm->GetLocalPeerId() - 1); @@ -2427,9 +2427,9 @@ public: void OnReplicaChangeOwnership(const ReplicaContext& rc) override { - if (IsMaster()) + if (IsPrimary()) { - AZ_TracePrintf("GridMate", "OnChangeOwnership: 0x%04x Became master on node %d\n", GetReplicaId(), rc.m_rm->GetLocalPeerId() - 1); + AZ_TracePrintf("GridMate", "OnChangeOwnership: 0x%04x Became primary on node %d\n", GetReplicaId(), rc.m_rm->GetLocalPeerId() - 1); m_owner.Set(rc.m_rm->GetLocalPeerId() - 1); } else @@ -2591,18 +2591,18 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) { auto rep = Replica::CreateReplica(nullptr); nodes[iNode].m_always = CreateAndAttachReplicaChunk(rep); - nodes[iNode].m_session.GetReplicaMgr().AddMaster(rep); + nodes[iNode].m_session.GetReplicaMgr().AddPrimary(rep); } { auto rep = Replica::CreateReplica(nullptr); nodes[iNode].m_never = CreateAndAttachReplicaChunk(rep); - nodes[iNode].m_session.GetReplicaMgr().AddMaster(rep); + nodes[iNode].m_session.GetReplicaMgr().AddPrimary(rep); } { auto rep = Replica::CreateReplica(nullptr); nodes[iNode].m_sometimes = CreateAndAttachReplicaChunk(rep); nodes[iNode].m_sometimes->m_acceptMigrationRequests = iNode == Peer1 || iNode == Client1; - nodes[iNode].m_session.GetReplicaMgr().AddMaster(rep); + nodes[iNode].m_session.GetReplicaMgr().AddPrimary(rep); } } } @@ -2675,7 +2675,7 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) AZ_TEST_ASSERT(nodes[Client1].m_always->m_accepted == 1); AZ_TEST_ASSERT(nodes[Client1].m_always->GetReplica()->IsProxy()); AZ_TEST_ASSERT(nodes[Client1].m_always->m_owner.Get() == Client2); - AZ_TEST_ASSERT(nodes[Client2].m_session.GetReplicaMgr().FindReplica(nodes[Client1].m_always->GetReplicaId())->IsMaster()); + AZ_TEST_ASSERT(nodes[Client2].m_session.GetReplicaMgr().FindReplica(nodes[Client1].m_always->GetReplicaId())->IsPrimary()); // C1 -> C2 -> Host (2nd migration) ReplicaPtr aHonC1 = nodes[Host].m_session.GetReplicaMgr().FindReplica(nodes[Client1].m_always->GetReplicaId()); @@ -2737,7 +2737,7 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) AZ_TEST_ASSERT(nodes[Peer1].m_always->m_accepted == 1); AZ_TEST_ASSERT(nodes[Peer1].m_always->GetReplica()->IsProxy()); AZ_TEST_ASSERT(nodes[Peer1].m_always->m_owner.Get() == Peer2); - AZ_TEST_ASSERT(nodes[Peer2].m_session.GetReplicaMgr().FindReplica(nodes[Peer1].m_always->GetReplicaId())->IsMaster()); + AZ_TEST_ASSERT(nodes[Peer2].m_session.GetReplicaMgr().FindReplica(nodes[Peer1].m_always->GetReplicaId())->IsPrimary()); AZ_TEST_ASSERT(nodes[Peer1].m_always->m_control.Get() == Peer2); // P2 -> Host -> C2 (both at same time, with C2 arriving second) @@ -2750,7 +2750,7 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) AZ_TEST_ASSERT(aP2onH->m_accepted == 1); AZ_TEST_ASSERT(aP2onH->GetReplica()->IsProxy()); AZ_TEST_ASSERT(aP2onH->m_owner.Get() == Client2); - AZ_TEST_ASSERT(nodes[Client2].m_session.GetReplicaMgr().FindReplica(nodes[Peer2].m_always->GetReplicaId())->IsMaster()); + AZ_TEST_ASSERT(nodes[Client2].m_session.GetReplicaMgr().FindReplica(nodes[Peer2].m_always->GetReplicaId())->IsPrimary()); AZ_TEST_ASSERT(nodes[Peer2].m_always->m_control.Get() == Client2); // Host -> C1 @@ -2758,7 +2758,7 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) AZ_TEST_ASSERT(nodes[Host].m_always->m_accepted == 1); AZ_TEST_ASSERT(nodes[Host].m_always->GetReplica()->IsProxy()); AZ_TEST_ASSERT(nodes[Host].m_always->m_owner.Get() == Client1); - AZ_TEST_ASSERT(nodes[Client1].m_session.GetReplicaMgr().FindReplica(nodes[Host].m_always->GetReplicaId())->IsMaster()); + AZ_TEST_ASSERT(nodes[Client1].m_session.GetReplicaMgr().FindReplica(nodes[Host].m_always->GetReplicaId())->IsPrimary()); AZ_TEST_ASSERT(nodes[Host].m_always->m_control.Get() == Client1); // C1 -> C2 -> Host (2nd migration) @@ -2771,7 +2771,7 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) AZ_TEST_ASSERT(aC1onC2->m_accepted == 1); AZ_TEST_ASSERT(aC1onC2->GetReplica()->IsProxy()); AZ_TEST_ASSERT(aC1onC2->m_owner.Get() == Host); - AZ_TEST_ASSERT(nodes[Host].m_session.GetReplicaMgr().FindReplica(nodes[Client1].m_always->GetReplicaId())->IsMaster()); + AZ_TEST_ASSERT(nodes[Host].m_session.GetReplicaMgr().FindReplica(nodes[Client1].m_always->GetReplicaId())->IsPrimary()); AZ_TEST_ASSERT(nodes[Client1].m_always->m_control.Get() == Host); // C2 -> P1 @@ -2779,13 +2779,13 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) AZ_TEST_ASSERT(nodes[Client2].m_always->m_accepted == 1); AZ_TEST_ASSERT(nodes[Client2].m_always->GetReplica()->IsProxy()); AZ_TEST_ASSERT(nodes[Client2].m_always->m_owner.Get() == Peer1); - AZ_TEST_ASSERT(nodes[Peer1].m_session.GetReplicaMgr().FindReplica(nodes[Client2].m_always->GetReplicaId())->IsMaster()); + AZ_TEST_ASSERT(nodes[Peer1].m_session.GetReplicaMgr().FindReplica(nodes[Client2].m_always->GetReplicaId())->IsPrimary()); AZ_TEST_ASSERT(nodes[Client2].m_always->m_control.Get() == Peer1); // P1 -> C1 (Forbidden) AZ_TEST_ASSERT(nodes[Peer1].m_never->m_requests == 0); AZ_TEST_ASSERT(nodes[Peer1].m_never->m_accepted == 0); - AZ_TEST_ASSERT(nodes[Peer1].m_never->GetReplica()->IsMaster()); + AZ_TEST_ASSERT(nodes[Peer1].m_never->GetReplica()->IsPrimary()); AZ_TEST_ASSERT(nodes[Peer1].m_never->m_owner.Get() == Peer1); AZ_TEST_ASSERT(nodes[Client1].m_session.GetReplicaMgr().FindReplica(nodes[Peer1].m_never->GetReplicaId())->IsProxy()); AZ_TEST_ASSERT(nodes[Peer1].m_never->m_control.Get() == Peer1); @@ -2793,7 +2793,7 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) // C2 -> P2 (Forbidden) AZ_TEST_ASSERT(nodes[Client2].m_never->m_requests == 0); AZ_TEST_ASSERT(nodes[Client2].m_never->m_accepted == 0); - AZ_TEST_ASSERT(nodes[Client2].m_never->GetReplica()->IsMaster()); + AZ_TEST_ASSERT(nodes[Client2].m_never->GetReplica()->IsPrimary()); AZ_TEST_ASSERT(nodes[Client2].m_never->m_owner.Get() == Client2); AZ_TEST_ASSERT(nodes[Peer2].m_session.GetReplicaMgr().FindReplica(nodes[Client2].m_never->GetReplicaId())->IsProxy()); AZ_TEST_ASSERT(nodes[Client2].m_never->m_control.Get() == Client2); @@ -2803,7 +2803,7 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) AZ_TEST_ASSERT(nodes[Peer1].m_sometimes->m_accepted == 1); AZ_TEST_ASSERT(nodes[Peer1].m_sometimes->GetReplica()->IsProxy()); AZ_TEST_ASSERT(nodes[Peer1].m_sometimes->m_owner.Get() == Host); - AZ_TEST_ASSERT(nodes[Host].m_session.GetReplicaMgr().FindReplica(nodes[Peer1].m_sometimes->GetReplicaId())->IsMaster()); + AZ_TEST_ASSERT(nodes[Host].m_session.GetReplicaMgr().FindReplica(nodes[Peer1].m_sometimes->GetReplicaId())->IsPrimary()); AZ_TEST_ASSERT(nodes[Peer1].m_sometimes->m_control.Get() == Host); // C1 -> P1 @@ -2811,13 +2811,13 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) AZ_TEST_ASSERT(nodes[Client1].m_sometimes->m_accepted == 1); AZ_TEST_ASSERT(nodes[Client1].m_sometimes->GetReplica()->IsProxy()); AZ_TEST_ASSERT(nodes[Client1].m_sometimes->m_owner.Get() == Peer1); - AZ_TEST_ASSERT(nodes[Peer1].m_session.GetReplicaMgr().FindReplica(nodes[Client1].m_sometimes->GetReplicaId())->IsMaster()); + AZ_TEST_ASSERT(nodes[Peer1].m_session.GetReplicaMgr().FindReplica(nodes[Client1].m_sometimes->GetReplicaId())->IsPrimary()); AZ_TEST_ASSERT(nodes[Client1].m_sometimes->m_control.Get() == Peer1); // P2 -> C2 (Forbidden) AZ_TEST_ASSERT(nodes[Peer2].m_sometimes->m_requests == 1); AZ_TEST_ASSERT(nodes[Peer2].m_sometimes->m_accepted == 0); - AZ_TEST_ASSERT(nodes[Peer2].m_sometimes->GetReplica()->IsMaster()); + AZ_TEST_ASSERT(nodes[Peer2].m_sometimes->GetReplica()->IsPrimary()); AZ_TEST_ASSERT(nodes[Peer2].m_sometimes->m_owner.Get() == Peer2); AZ_TEST_ASSERT(nodes[Client2].m_session.GetReplicaMgr().FindReplica(nodes[Peer2].m_never->GetReplicaId())->IsProxy()); AZ_TEST_ASSERT(nodes[Peer2].m_sometimes->m_control.Get() == Peer2); @@ -2825,7 +2825,7 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) // C2 -> Host (Forbidden) AZ_TEST_ASSERT(nodes[Client2].m_sometimes->m_requests == 1); AZ_TEST_ASSERT(nodes[Client2].m_sometimes->m_accepted == 0); - AZ_TEST_ASSERT(nodes[Client2].m_sometimes->GetReplica()->IsMaster()); + AZ_TEST_ASSERT(nodes[Client2].m_sometimes->GetReplica()->IsPrimary()); AZ_TEST_ASSERT(nodes[Client2].m_sometimes->m_owner.Get() == Client2); AZ_TEST_ASSERT(nodes[Host].m_session.GetReplicaMgr().FindReplica(nodes[Client2].m_never->GetReplicaId())->IsProxy()); AZ_TEST_ASSERT(nodes[Client2].m_sometimes->m_control.Get() == Client2); @@ -2946,12 +2946,12 @@ TEST_F(Integ_PeerRejoinTest, PeerRejoinTest) { auto rep = Replica::CreateReplica(nullptr); migrRep[i] = CreateAndAttachReplicaChunk(rep, aznew MyObj()); - peers[i].GetReplicaMgr().AddMaster(rep); + peers[i].GetReplicaMgr().AddPrimary(rep); } { auto rep = Replica::CreateReplica(nullptr); nonMigrRep[i] = CreateAndAttachReplicaChunk(rep, aznew MyObj()); - peers[i].GetReplicaMgr().AddMaster(rep); + peers[i].GetReplicaMgr().AddPrimary(rep); } } addReplicas = false; @@ -3099,7 +3099,7 @@ public: { // make sure the requestor is set to s1 AZ_TEST_ASSERT(rpcContext.m_sourcePeer == s1 + 1); - if (IsMaster()) + if (IsPrimary()) { m_nAuthoritativeOnlyRpcCallsFromS1.Modify([](int& value) { ++value; return true; }); } @@ -3114,7 +3114,7 @@ public: { // make sure the requestor is set to s2 AZ_TEST_ASSERT(rpcContext.m_sourcePeer == s2 + 1); - if (IsMaster()) + if (IsPrimary()) { m_nAuthoritativeOnlyRpcCallsFromS2.Modify([](int& value) { ++value; return true; }); } @@ -3129,7 +3129,7 @@ public: { // make sure the requestor is set to s3 AZ_TEST_ASSERT(rpcContext.m_sourcePeer == s3 + 1); - if (IsMaster()) + if (IsPrimary()) { m_nAuthoritativeOnlyRpcCallsFromS3.Modify([](int& value) { ++value; return true; }); } @@ -3168,7 +3168,7 @@ TEST_F(Integ_ReplicationSecurityOptionsTest, ReplicationSecurityOptionsTest) ReplicaChunkDescriptorTable::Get().RegisterChunkType(); MPSession sessions[nSessions]; - ReplicaPtr masters[nSessions]; + ReplicaPtr primarys[nSessions]; // initialize transport int basePort = 4427; @@ -3202,10 +3202,10 @@ TEST_F(Integ_ReplicationSecurityOptionsTest, ReplicationSecurityOptionsTest) for (int i = 0; i < nSessions; ++i) { AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().IsReady()); - masters[i] = Replica::CreateReplica("ReplicationSecurityOptionsTest::TestReplica"); + primarys[i] = Replica::CreateReplica("ReplicationSecurityOptionsTest::TestReplica"); TestChunkPtr chunk = CreateReplicaChunk(); - masters[i]->AttachReplicaChunk(chunk); - sessions[i].GetReplicaMgr().AddMaster(masters[i]); + primarys[i]->AttachReplicaChunk(chunk); + sessions[i].GetReplicaMgr().AddPrimary(primarys[i]); } } @@ -3214,9 +3214,9 @@ TEST_F(Integ_ReplicationSecurityOptionsTest, ReplicationSecurityOptionsTest) AZ_TEST_START_TRACE_SUPPRESSION; for (int i = 0; i < nSessions; ++i) { - sessions[s1].GetReplicaMgr().FindReplica(masters[i]->GetRepId())->FindReplicaChunk()->ForwardSourcePeerRpcFromS1(); - sessions[s2].GetReplicaMgr().FindReplica(masters[i]->GetRepId())->FindReplicaChunk()->ForwardSourcePeerRpcFromS2(); - sessions[s3].GetReplicaMgr().FindReplica(masters[i]->GetRepId())->FindReplicaChunk()->ForwardSourcePeerRpcFromS3(); + sessions[s1].GetReplicaMgr().FindReplica(primarys[i]->GetRepId())->FindReplicaChunk()->ForwardSourcePeerRpcFromS1(); + sessions[s2].GetReplicaMgr().FindReplica(primarys[i]->GetRepId())->FindReplicaChunk()->ForwardSourcePeerRpcFromS2(); + sessions[s3].GetReplicaMgr().FindReplica(primarys[i]->GetRepId())->FindReplicaChunk()->ForwardSourcePeerRpcFromS3(); } } @@ -3227,36 +3227,36 @@ TEST_F(Integ_ReplicationSecurityOptionsTest, ReplicationSecurityOptionsTest) AZ_TEST_STOP_TRACE_SUPPRESSION(2); // All chunks should have received the call from the host - AZ_TEST_ASSERT(masters[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1 == 1); - AZ_TEST_ASSERT(masters[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1 == 1); - AZ_TEST_ASSERT(masters[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1 == 1); + AZ_TEST_ASSERT(primarys[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1 == 1); + AZ_TEST_ASSERT(primarys[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1 == 1); + AZ_TEST_ASSERT(primarys[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1 == 1); // the host chunk should have received calls from both clients - AZ_TEST_ASSERT(masters[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2 == 1); - AZ_TEST_ASSERT(masters[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3 == 1); + AZ_TEST_ASSERT(primarys[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2 == 1); + AZ_TEST_ASSERT(primarys[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3 == 1); // the chunk on s2 should receive its own call but not from s3 - AZ_TEST_ASSERT(masters[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2 == 1); - AZ_TEST_ASSERT(masters[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3 == 0); + AZ_TEST_ASSERT(primarys[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2 == 1); + AZ_TEST_ASSERT(primarys[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3 == 0); // the chunk on s3 should receive its own call but not from s2 - AZ_TEST_ASSERT(masters[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2 == 0); - AZ_TEST_ASSERT(masters[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3 == 1); + AZ_TEST_ASSERT(primarys[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2 == 0); + AZ_TEST_ASSERT(primarys[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3 == 1); // all datasets should have propagated properly for (int i = 0; i < nSessions; ++i) { - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s1]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get() == masters[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s1]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get() == masters[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s1]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get() == masters[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s1]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get() == primarys[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s1]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get() == primarys[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s1]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get() == primarys[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s2]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get() == masters[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s2]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get() == masters[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s2]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get() == masters[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s2]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get() == primarys[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s2]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get() == primarys[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s2]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get() == primarys[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s3]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get() == masters[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s3]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get() == masters[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s3]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get() == masters[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s3]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get() == primarys[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s3]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get() == primarys[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s3]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get() == primarys[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get()); } } @@ -3265,9 +3265,9 @@ TEST_F(Integ_ReplicationSecurityOptionsTest, ReplicationSecurityOptionsTest) AZ_TEST_START_TRACE_SUPPRESSION; for (int i = 0; i < nSessions; ++i) { - sessions[s1].GetReplicaMgr().FindReplica(masters[i]->GetRepId())->FindReplicaChunk()->AuthoritativeOnlyRpcFromS1(); - sessions[s2].GetReplicaMgr().FindReplica(masters[i]->GetRepId())->FindReplicaChunk()->AuthoritativeOnlyRpcFromS2(); - sessions[s3].GetReplicaMgr().FindReplica(masters[i]->GetRepId())->FindReplicaChunk()->AuthoritativeOnlyRpcFromS3(); + sessions[s1].GetReplicaMgr().FindReplica(primarys[i]->GetRepId())->FindReplicaChunk()->AuthoritativeOnlyRpcFromS1(); + sessions[s2].GetReplicaMgr().FindReplica(primarys[i]->GetRepId())->FindReplicaChunk()->AuthoritativeOnlyRpcFromS2(); + sessions[s3].GetReplicaMgr().FindReplica(primarys[i]->GetRepId())->FindReplicaChunk()->AuthoritativeOnlyRpcFromS3(); } } @@ -3278,40 +3278,40 @@ TEST_F(Integ_ReplicationSecurityOptionsTest, ReplicationSecurityOptionsTest) AZ_TEST_STOP_TRACE_SUPPRESSION(6); // Each chunk should have received their own AuthoritativeOnlyRpc once. - AZ_TEST_ASSERT(masters[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1 == 1); - AZ_TEST_ASSERT(masters[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2 == 1); - AZ_TEST_ASSERT(masters[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3 == 1); + AZ_TEST_ASSERT(primarys[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1 == 1); + AZ_TEST_ASSERT(primarys[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2 == 1); + AZ_TEST_ASSERT(primarys[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3 == 1); // Calls from other nodes should have been discarded. - AZ_TEST_ASSERT(masters[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2 == 0); - AZ_TEST_ASSERT(masters[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3 == 0); - AZ_TEST_ASSERT(masters[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1 == 0); - AZ_TEST_ASSERT(masters[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3 == 0); - AZ_TEST_ASSERT(masters[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1 == 0); - AZ_TEST_ASSERT(masters[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2 == 0); + AZ_TEST_ASSERT(primarys[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2 == 0); + AZ_TEST_ASSERT(primarys[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3 == 0); + AZ_TEST_ASSERT(primarys[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1 == 0); + AZ_TEST_ASSERT(primarys[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3 == 0); + AZ_TEST_ASSERT(primarys[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1 == 0); + AZ_TEST_ASSERT(primarys[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2 == 0); // Calls should have successfully propagated to the other 2 proxies - AZ_TEST_ASSERT(sessions[s1].GetReplicaMgr().FindReplica(masters[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS2 == 1); - AZ_TEST_ASSERT(sessions[s1].GetReplicaMgr().FindReplica(masters[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS3 == 1); - AZ_TEST_ASSERT(sessions[s2].GetReplicaMgr().FindReplica(masters[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS1 == 1); - AZ_TEST_ASSERT(sessions[s2].GetReplicaMgr().FindReplica(masters[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS3 == 1); - AZ_TEST_ASSERT(sessions[s3].GetReplicaMgr().FindReplica(masters[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS1 == 1); - AZ_TEST_ASSERT(sessions[s3].GetReplicaMgr().FindReplica(masters[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS2 == 1); + AZ_TEST_ASSERT(sessions[s1].GetReplicaMgr().FindReplica(primarys[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS2 == 1); + AZ_TEST_ASSERT(sessions[s1].GetReplicaMgr().FindReplica(primarys[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS3 == 1); + AZ_TEST_ASSERT(sessions[s2].GetReplicaMgr().FindReplica(primarys[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS1 == 1); + AZ_TEST_ASSERT(sessions[s2].GetReplicaMgr().FindReplica(primarys[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS3 == 1); + AZ_TEST_ASSERT(sessions[s3].GetReplicaMgr().FindReplica(primarys[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS1 == 1); + AZ_TEST_ASSERT(sessions[s3].GetReplicaMgr().FindReplica(primarys[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS2 == 1); // all datasets should have propagated properly for (int i = 0; i < nSessions; ++i) { - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get() == masters[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get() == masters[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get() == masters[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get() == primarys[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get() == primarys[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get() == primarys[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get() == masters[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get() == masters[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get() == masters[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get() == primarys[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get() == primarys[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get() == primarys[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get() == masters[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get() == masters[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get() == masters[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get() == primarys[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get() == primarys[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get() == primarys[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get()); } } @@ -3594,7 +3594,7 @@ public: auto rep = Replica::CreateReplica(nullptr); auto chunk = CreateAndAttachReplicaChunk(rep); replicas.push_back(AZStd::make_pair(rep, chunk)); - session.GetReplicaMgr().AddMaster(rep); + session.GetReplicaMgr().AddPrimary(rep); } } @@ -3730,7 +3730,7 @@ public: { auto rep = Replica::CreateReplica(nullptr); chunks[i] = CreateAndAttachReplicaChunk(rep); - sessions[sHost].GetReplicaMgr().AddMaster(rep); + sessions[sHost].GetReplicaMgr().AddPrimary(rep); } // connect to host diff --git a/Code/Framework/GridMate/Tests/ReplicaBehavior.cpp b/Code/Framework/GridMate/Tests/ReplicaBehavior.cpp index 3f9db2ba0e..c3dac305db 100644 --- a/Code/Framework/GridMate/Tests/ReplicaBehavior.cpp +++ b/Code/Framework/GridMate/Tests/ReplicaBehavior.cpp @@ -687,7 +687,7 @@ namespace ReplicaBehavior { AZ_TEST_ASSERT(chunk->Data1.IsDefaultValue()); AZ_TEST_ASSERT(chunk->Data2.IsDefaultValue()); - m_replicaIdDefault = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaIdDefault = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } } @@ -725,7 +725,7 @@ namespace ReplicaBehavior { AZ_TEST_ASSERT(!chunk->Data1.IsDefaultValue()); AZ_TEST_ASSERT(!chunk->Data2.IsDefaultValue()); - m_replicaIdModified = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaIdModified = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } break; } @@ -816,7 +816,7 @@ namespace ReplicaBehavior { LargeChunkWithDefaults* chunk = CreateAndAttachReplicaChunk(replica); AZ_TEST_ASSERT(chunk); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } ~Integ_ReplicaDefaultDataSetDriller() @@ -923,13 +923,13 @@ namespace ReplicaBehavior { ChunkWithBools* chunk1 = CreateAndAttachReplicaChunk(replica1); AZ_TEST_ASSERT(chunk1); - m_replicaBoolsId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica1); + m_replicaBoolsId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica1); ReplicaPtr replica2 = Replica::CreateReplica(nullptr); ChunkWithShortInts* chunk2 = CreateAndAttachReplicaChunk(replica2); AZ_TEST_ASSERT(chunk2); - m_replicaU8Id = m_sessions[sHost].GetReplicaMgr().AddMaster(replica2); + m_replicaU8Id = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica2); } ~Integ_Replica_ComparePackingBoolsVsU8() @@ -1058,7 +1058,7 @@ namespace ReplicaBehavior { auto chunk = CreateAndAttachReplicaChunk(replica); AZ_TEST_ASSERT(chunk); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } ~Integ_CheckDataSetStreamIsntWrittenMoreThanNecessary() @@ -1155,7 +1155,7 @@ namespace ReplicaBehavior { auto chunk = CreateAndAttachReplicaChunk(replica); AZ_TEST_ASSERT(chunk); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } ~Integ_CheckDataSetStreamIsntWrittenMoreThanNecessaryOnceDirty() @@ -1249,7 +1249,7 @@ namespace ReplicaBehavior { ForcingDirtyTestChunk* chunk = CreateAndAttachReplicaChunk(replica); AZ_TEST_ASSERT(chunk); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } ~Integ_CheckReplicaIsntSentWithNoChanges() @@ -1360,7 +1360,7 @@ namespace ReplicaBehavior { auto chunk = CreateAndAttachReplicaChunk(replica); AZ_TEST_ASSERT(chunk); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } ~Integ_CheckEntityScriptReplicaIsntSentWithNoChanges() diff --git a/Code/Framework/GridMate/Tests/ReplicaMedium.cpp b/Code/Framework/GridMate/Tests/ReplicaMedium.cpp index 7c04c26487..fbdf4ee493 100644 --- a/Code/Framework/GridMate/Tests/ReplicaMedium.cpp +++ b/Code/Framework/GridMate/Tests/ReplicaMedium.cpp @@ -73,12 +73,12 @@ public: static const char* GetChunkName() { return "RPCChunk"; } RPCChunk() - : m_fromMasterBroadcast(0) - , m_fromMasterNotBroadcast(0) + : m_fromPrimaryBroadcast(0) + , m_fromPrimaryNotBroadcast(0) , m_fromProxyBroadcast(0) , m_fromProxyNotBroadcast(0) - , FromMasterBroadcast("FromMasterBroadcast") - , FromMasterNotBroadcast("FromMasterNotBroadcast") + , FromPrimaryBroadcast("FromPrimaryBroadcast") + , FromPrimaryNotBroadcast("FromPrimaryNotBroadcast") , FromProxyBroadcast("FromProxyBroadcast") , FromProxyNotBroadcast("FromProxyNotBroadcast") , BroadcastInt("BroadcastInt") @@ -86,30 +86,30 @@ public: bool IsReplicaMigratable() override { return false; } - bool FromMasterBroadcastFn(const RpcContext&) + bool FromPrimaryBroadcastFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed FromMasterBroadcast %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); - m_fromMasterBroadcast++; + AZ_TracePrintf("GridMate", "Executed FromPrimaryBroadcast %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); + m_fromPrimaryBroadcast++; return true; } - bool FromMasterNotBroadcastFn(const RpcContext&) + bool FromPrimaryNotBroadcastFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed FromMasterNotBroadcast %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); - m_fromMasterNotBroadcast++; + AZ_TracePrintf("GridMate", "Executed FromPrimaryNotBroadcast %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); + m_fromPrimaryNotBroadcast++; return false; } bool FromProxyBroadcastFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed FromProxyBroadcast %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); + AZ_TracePrintf("GridMate", "Executed FromProxyBroadcast %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); m_fromProxyBroadcast++; return true; } bool FromProxyNotBroadcastFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed FromProxyNotBroadcast %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); + AZ_TracePrintf("GridMate", "Executed FromProxyNotBroadcast %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); m_fromProxyNotBroadcast++; return false; } @@ -120,14 +120,14 @@ public: return true; } - int m_fromMasterBroadcast; - int m_fromMasterNotBroadcast; + int m_fromPrimaryBroadcast; + int m_fromPrimaryNotBroadcast; int m_fromProxyBroadcast; int m_fromProxyNotBroadcast; AZStd::vector m_sentData; - Rpc<>::BindInterface FromMasterBroadcast; - Rpc<>::BindInterface FromMasterNotBroadcast; + Rpc<>::BindInterface FromPrimaryBroadcast; + Rpc<>::BindInterface FromPrimaryNotBroadcast; Rpc<>::BindInterface FromProxyBroadcast; Rpc<>::BindInterface FromProxyNotBroadcast; Rpc >::BindInterface BroadcastInt; @@ -158,21 +158,21 @@ public: bool Zero(const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[0]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[0]; (void) list; return true; } bool One(AZ::u32 t1, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[1]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[1]; list.push_back(t1); return true; } bool Two(AZ::u32 t1, AZ::u32 t2, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[2]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[2]; list.push_back(t1); list.push_back(t2); return true; @@ -180,7 +180,7 @@ public: bool Three(AZ::u32 t1, AZ::u32 t2, AZ::u32 t3, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[3]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[3]; list.push_back(t1); list.push_back(t2); list.push_back(t3); @@ -189,7 +189,7 @@ public: bool Four(AZ::u32 t1, AZ::u32 t2, AZ::u32 t3, AZ::u32 t4, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[4]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[4]; list.push_back(t1); list.push_back(t2); list.push_back(t3); @@ -199,7 +199,7 @@ public: bool Five(AZ::u32 t1, AZ::u32 t2, AZ::u32 t3, AZ::u32 t4, AZ::u32 t5, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[5]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[5]; list.push_back(t1); list.push_back(t2); list.push_back(t3); @@ -210,7 +210,7 @@ public: bool Six(AZ::u32 t1, AZ::u32 t2, AZ::u32 t3, AZ::u32 t4, AZ::u32 t5, AZ::u32 t6, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[6]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[6]; list.push_back(t1); list.push_back(t2); list.push_back(t3); @@ -222,7 +222,7 @@ public: bool Seven(AZ::u32 t1, AZ::u32 t2, AZ::u32 t3, AZ::u32 t4, AZ::u32 t5, AZ::u32 t6, AZ::u32 t7, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[7]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[7]; list.push_back(t1); list.push_back(t2); list.push_back(t3); @@ -235,7 +235,7 @@ public: bool Eight(AZ::u32 t1, AZ::u32 t2, AZ::u32 t3, AZ::u32 t4, AZ::u32 t5, AZ::u32 t6, AZ::u32 t7, AZ::u32 t8, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[8]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[8]; list.push_back(t1); list.push_back(t2); list.push_back(t3); @@ -249,7 +249,7 @@ public: bool Nine(AZ::u32 t1, AZ::u32 t2, AZ::u32 t3, AZ::u32 t4, AZ::u32 t5, AZ::u32 t6, AZ::u32 t7, AZ::u32 t8, AZ::u32 t9, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[9]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[9]; list.push_back(t1); list.push_back(t2); list.push_back(t3); @@ -890,7 +890,7 @@ public: // put something on s1 to get it going auto replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } RPCChunk::Ptr m_chunk; @@ -905,11 +905,11 @@ TEST_F(Integ_ReplicaChunkRPCExec, ReplicaChunkRPCExec) switch (tick) { case 10: - m_chunk->FromMasterBroadcast(); + m_chunk->FromPrimaryBroadcast(); break; case 20: - m_chunk->FromMasterNotBroadcast(); + m_chunk->FromPrimaryNotBroadcast(); break; case 30: @@ -932,13 +932,13 @@ TEST_F(Integ_ReplicaChunkRPCExec, ReplicaChunkRPCExec) auto s2proxy = m_sessions[s2].GetReplicaMgr().FindReplica(m_replicaId)->FindReplicaChunk(); auto s3proxy = m_sessions[s3].GetReplicaMgr().FindReplica(m_replicaId)->FindReplicaChunk(); - AZ_TEST_ASSERT(s1host->m_fromMasterBroadcast == 1); - AZ_TEST_ASSERT(s2proxy->m_fromMasterBroadcast == 1); - AZ_TEST_ASSERT(s3proxy->m_fromMasterBroadcast == 1); + AZ_TEST_ASSERT(s1host->m_fromPrimaryBroadcast == 1); + AZ_TEST_ASSERT(s2proxy->m_fromPrimaryBroadcast == 1); + AZ_TEST_ASSERT(s3proxy->m_fromPrimaryBroadcast == 1); - AZ_TEST_ASSERT(s1host->m_fromMasterNotBroadcast == 1); - AZ_TEST_ASSERT(s2proxy->m_fromMasterNotBroadcast == 0); - AZ_TEST_ASSERT(s3proxy->m_fromMasterNotBroadcast == 0); + AZ_TEST_ASSERT(s1host->m_fromPrimaryNotBroadcast == 1); + AZ_TEST_ASSERT(s2proxy->m_fromPrimaryNotBroadcast == 0); + AZ_TEST_ASSERT(s3proxy->m_fromPrimaryNotBroadcast == 0); AZ_TEST_ASSERT(s1host->m_fromProxyBroadcast == 1); AZ_TEST_ASSERT(s2proxy->m_fromProxyBroadcast == 1); @@ -965,12 +965,12 @@ public: GM_CLASS_ALLOCATOR(DestroyRPCChunk); DestroyRPCChunk() - : DestroyFromMaster("DestroyFromMaster") + : DestroyFromPrimary("DestroyFromPrimary") , DestroyFromProxy("DestroyFromProxy") , BeforeDestroyFromProxy("BeforeDestroyFromProxy") , AfterDestroyFromProxy("AfterDestroyFromProxy") - , BeforeDestroyFromMaster("BeforeDestroyFromMaster") - , AfterDestroyFromMaster("AfterDestroyFromMaster") + , BeforeDestroyFromPrimary("BeforeDestroyFromPrimary") + , AfterDestroyFromPrimary("AfterDestroyFromPrimary") { } @@ -979,11 +979,11 @@ public: bool IsReplicaMigratable() override { return false; } - bool DestroyFromMasterFn(const RpcContext&) + bool DestroyFromPrimaryFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed DestroyFromMaster %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); - ++s_destroyFromMasterCalls; - if (GetReplica()->IsMaster()) + AZ_TracePrintf("GridMate", "Executed DestroyFromPrimary %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); + ++s_destroyFromPrimaryCalls; + if (GetReplica()->IsPrimary()) { GetReplica()->Destroy(); } @@ -992,9 +992,9 @@ public: bool DestroyFromProxyFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed DestroyFromProxy %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); + AZ_TracePrintf("GridMate", "Executed DestroyFromProxy %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); ++s_destroyFromProxyCalls; - if (GetReplica()->IsMaster()) + if (GetReplica()->IsPrimary()) { GetReplica()->Destroy(); } @@ -1003,53 +1003,53 @@ public: bool BeforeDestroyFromProxyFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed BeforeDestroyFromProxy %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); + AZ_TracePrintf("GridMate", "Executed BeforeDestroyFromProxy %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); ++s_beforeDestroyFromProxyCalls; return true; } bool AfterDestroyFromProxyFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed AfterDestroyFromProxy %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); + AZ_TracePrintf("GridMate", "Executed AfterDestroyFromProxy %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); ++s_afterDestroyFromProxyCalls; return true; } - bool BeforeDestroyFromMasterFn(const RpcContext&) + bool BeforeDestroyFromPrimaryFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed BeforeDestroyFromMaster %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); - ++s_beforeDestroyFromMasterCalls; + AZ_TracePrintf("GridMate", "Executed BeforeDestroyFromPrimary %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); + ++s_beforeDestroyFromPrimaryCalls; return true; } - bool AfterDestroyFromMasterFn(const RpcContext&) + bool AfterDestroyFromPrimaryFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed AfterDestroyFromMaster %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); - ++s_afterDestroyFromMasterCalls; + AZ_TracePrintf("GridMate", "Executed AfterDestroyFromPrimary %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); + ++s_afterDestroyFromPrimaryCalls; return true; } - Rpc<>::BindInterface DestroyFromMaster; + Rpc<>::BindInterface DestroyFromPrimary; Rpc<>::BindInterface DestroyFromProxy; Rpc<>::BindInterface BeforeDestroyFromProxy; Rpc<>::BindInterface AfterDestroyFromProxy; - Rpc<>::BindInterface BeforeDestroyFromMaster; - Rpc<>::BindInterface AfterDestroyFromMaster; + Rpc<>::BindInterface BeforeDestroyFromPrimary; + Rpc<>::BindInterface AfterDestroyFromPrimary; - static int s_destroyFromMasterCalls; - static int s_beforeDestroyFromMasterCalls; - static int s_afterDestroyFromMasterCalls; + static int s_destroyFromPrimaryCalls; + static int s_beforeDestroyFromPrimaryCalls; + static int s_afterDestroyFromPrimaryCalls; static int s_destroyFromProxyCalls; static int s_beforeDestroyFromProxyCalls; static int s_afterDestroyFromProxyCalls; }; int DestroyRPCChunk::s_destroyFromProxyCalls = 0; -int DestroyRPCChunk::s_destroyFromMasterCalls = 0; +int DestroyRPCChunk::s_destroyFromPrimaryCalls = 0; int DestroyRPCChunk::s_beforeDestroyFromProxyCalls = 0; int DestroyRPCChunk::s_afterDestroyFromProxyCalls = 0; -int DestroyRPCChunk::s_beforeDestroyFromMasterCalls = 0; -int DestroyRPCChunk::s_afterDestroyFromMasterCalls = 0; +int DestroyRPCChunk::s_beforeDestroyFromPrimaryCalls = 0; +int DestroyRPCChunk::s_afterDestroyFromPrimaryCalls = 0; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- @@ -1077,7 +1077,7 @@ public: { auto replica = Replica::CreateReplica(nullptr); CreateAndAttachReplicaChunk(replica); - m_repId[i] = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_repId[i] = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } } @@ -1092,12 +1092,12 @@ TEST_F(Integ_ReplicaDestroyedInRPC, ReplicaDestroyedInRPC) { case 10: { - // calling destroy on master - auto master = m_sessions[sHost].GetReplicaMgr().FindReplica(m_repId[0]); - auto masterChunk = master->FindReplicaChunk(); - masterChunk->BeforeDestroyFromMaster(); - masterChunk->DestroyFromMaster(); - masterChunk->AfterDestroyFromMaster(); + // calling destroy on primary + auto primary = m_sessions[sHost].GetReplicaMgr().FindReplica(m_repId[0]); + auto primaryChunk = primary->FindReplicaChunk(); + primaryChunk->BeforeDestroyFromPrimary(); + primaryChunk->DestroyFromPrimary(); + primaryChunk->AfterDestroyFromPrimary(); // calling destroy on proxy auto proxy = m_sessions[s2].GetReplicaMgr().FindReplica(m_repId[1]); @@ -1113,15 +1113,15 @@ TEST_F(Integ_ReplicaDestroyedInRPC, ReplicaDestroyedInRPC) { // checking if before destroy RPC was called on every peer AZ_TEST_ASSERT(DestroyRPCChunk::s_beforeDestroyFromProxyCalls == nSessions); - AZ_TEST_ASSERT(DestroyRPCChunk::s_beforeDestroyFromMasterCalls == nSessions); + AZ_TEST_ASSERT(DestroyRPCChunk::s_beforeDestroyFromPrimaryCalls == nSessions); // checking if destroy itself was called on every peer AZ_TEST_ASSERT(DestroyRPCChunk::s_destroyFromProxyCalls == nSessions); - AZ_TEST_ASSERT(DestroyRPCChunk::s_destroyFromMasterCalls == nSessions); + AZ_TEST_ASSERT(DestroyRPCChunk::s_destroyFromPrimaryCalls == nSessions); // checking if after destroy RPC was never called AZ_TEST_ASSERT(DestroyRPCChunk::s_afterDestroyFromProxyCalls == 0); // RPCs that arrive via the network after deactivation should be dropped. - AZ_TEST_ASSERT(DestroyRPCChunk::s_afterDestroyFromMasterCalls == 1); // RPCs explicitly called on an inactive replica should still be executed. + AZ_TEST_ASSERT(DestroyRPCChunk::s_afterDestroyFromPrimaryCalls == 1); // RPCs explicitly called on an inactive replica should still be executed. return TestStatus::Completed; } @@ -1157,7 +1157,7 @@ public: { // put something on s1 to get it going m_replica = Replica::CreateReplica(nullptr); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); } ReplicaPtr m_replica; @@ -1232,7 +1232,7 @@ public: // put something on s1 to get it going m_replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(m_replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); } ReplicaPtr m_replica; @@ -1286,7 +1286,7 @@ public: // put something on s1 to get it going m_replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(m_replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); } ReplicaPtr m_replica; @@ -1391,7 +1391,7 @@ public: { // put something on s1 to get it going m_replica = Replica::CreateReplica(nullptr); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); } @@ -1453,7 +1453,7 @@ public: { ReplicaPtr replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); AZ_TEST_ASSERT(m_chunk->m_attaches == 1); AZ_TEST_ASSERT(m_chunk->m_activates == 1); @@ -1531,7 +1531,7 @@ public: auto chunk = CreateAndAttachReplicaChunk(replica); AZ_TEST_ASSERT(chunk); } - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); auto numChunks = replica->GetNumChunks(); AZ_TEST_ASSERT(numChunks == GM_MAX_CHUNKS_PER_REPLICA); @@ -1594,7 +1594,7 @@ public: { m_replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(m_replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); AZ_TEST_ASSERT(m_chunk->m_attaches == 1); AZ_TEST_ASSERT(m_chunk->m_activates == 1); @@ -1820,16 +1820,16 @@ public: ++m_numRequestChangeOwnership; } - void OnReplicaChangeOwnership(Replica* replica, bool wasMaster) override + void OnReplicaChangeOwnership(Replica* replica, bool wasPrimary) override { AZ_TEST_ASSERT(replica); switch (m_numChangedOwnership) { case 0: // host loses ownership - AZ_TEST_ASSERT(replica->IsProxy() && wasMaster == true); + AZ_TEST_ASSERT(replica->IsProxy() && wasPrimary == true); break; case 1: // peer acquires ownership - AZ_TEST_ASSERT(replica->IsMaster() && wasMaster == false); + AZ_TEST_ASSERT(replica->IsPrimary() && wasPrimary == false); break; default: AZ_TEST_ASSERT(0); @@ -2008,7 +2008,7 @@ public: ReplicaPtr replica = Replica::CreateReplica(nullptr); CreateAndAttachReplicaChunk(replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } ~Integ_ReplicaDriller() @@ -2038,7 +2038,7 @@ TEST_F(Integ_ReplicaDriller, ReplicaDriller) { auto rep = m_sessions[s2].GetReplicaMgr().FindReplica(m_replicaId); AZ_TEST_ASSERT(rep); - AZ_TEST_ASSERT(rep->IsMaster()); + AZ_TEST_ASSERT(rep->IsPrimary()); rep->Destroy(); break; } @@ -2110,7 +2110,7 @@ public: { m_replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(m_replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); } @@ -2172,16 +2172,16 @@ public: { m_replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(m_replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); - m_masterHandler.reset(aznew CustomHandler()); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); + m_primaryHandler.reset(aznew CustomHandler()); m_proxyHandler.reset(aznew CustomHandler()); - m_chunk->SetHandler(m_masterHandler.get()); + m_chunk->SetHandler(m_primaryHandler.get()); } ReplicaPtr m_replica; ReplicaId m_replicaId; CustomHandlerChunk::Ptr m_chunk; - AZStd::scoped_ptr m_masterHandler; + AZStd::scoped_ptr m_primaryHandler; AZStd::scoped_ptr m_proxyHandler; }; @@ -2262,7 +2262,7 @@ public: { m_replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(m_replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); } ReplicaPtr m_replica; @@ -2338,7 +2338,7 @@ public: { m_replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(m_replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); } ReplicaPtr m_replica; @@ -2488,7 +2488,7 @@ public: m_chunks[i] = CreateAndAttachReplicaChunk(replica); m_chunks[i]->m_value.Set(i + 1); // setting dataset values to 1..kNumReplicas m_chunks[i]->SetPriority(k_replicaPriorityNormal + static_cast(i)); // the later created - the higher priorities, so should be sent in reverse order - m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } } @@ -2594,7 +2594,7 @@ public: ReplicaPtr replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(replica); - m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } SuspendUpdatesChunk::Ptr m_chunk = nullptr; @@ -2684,9 +2684,9 @@ public: void OnReplicaActivate(const GridMate::ReplicaContext&) override { - if (IsMaster()) + if (IsPrimary()) { - nMasterActivations++; + nPrimaryActivations++; } else { @@ -2694,11 +2694,11 @@ public: } } - static int nMasterActivations; + static int nPrimaryActivations; static int nProxyActivations; }; }; -int Integ_BasicHostChunkDescriptorTest::HostChunk::nMasterActivations = 0; +int Integ_BasicHostChunkDescriptorTest::HostChunk::nPrimaryActivations = 0; int Integ_BasicHostChunkDescriptorTest::HostChunk::nProxyActivations = 0; TEST_F(Integ_BasicHostChunkDescriptorTest, BasicHostChunkDescriptorTest) @@ -2744,25 +2744,25 @@ TEST_F(Integ_BasicHostChunkDescriptorTest, BasicHostChunkDescriptorTest) { hostReplica = Replica::CreateReplica("HostReplica"); hostReplica->AttachReplicaChunk(CreateReplicaChunk()); - nodes[Host].GetReplicaMgr().AddMaster(hostReplica); + nodes[Host].GetReplicaMgr().AddPrimary(hostReplica); } if (tick == 300) { - AZ_TEST_ASSERT(HostChunk::nMasterActivations == 1); + AZ_TEST_ASSERT(HostChunk::nPrimaryActivations == 1); AZ_TEST_ASSERT(HostChunk::nProxyActivations == 1); AZ_TEST_ASSERT(nodes[Client].GetReplicaMgr().FindReplica(hostReplica->GetRepId())->FindReplicaChunk()); AZ_TEST_START_TRACE_SUPPRESSION; clientReplica = Replica::CreateReplica("ClientReplica"); clientReplica->AttachReplicaChunk(CreateReplicaChunk()); - nodes[Client].GetReplicaMgr().AddMaster(clientReplica); + nodes[Client].GetReplicaMgr().AddPrimary(clientReplica); } if (tick == 400) { AZ_TEST_STOP_TRACE_SUPPRESSION(1); - AZ_TEST_ASSERT(HostChunk::nMasterActivations == 2); + AZ_TEST_ASSERT(HostChunk::nPrimaryActivations == 2); AZ_TEST_ASSERT(HostChunk::nProxyActivations == 1); AZ_TEST_ASSERT(!nodes[Host].GetReplicaMgr().FindReplica(clientReplica->GetRepId())->FindReplicaChunk()); } @@ -2792,10 +2792,10 @@ TEST_F(Integ_BasicHostChunkDescriptorTest, BasicHostChunkDescriptorTest) } /* - * Create and immedietly destroy master replica + * Create and immedietly destroy primary replica * Test that it does not result in any network sync */ -class Integ_CreateDestroyMaster +class Integ_CreateDestroyPrimary : public Integ_SimpleTest , public Debug::ReplicaDrillerBus::Handler { @@ -2831,7 +2831,7 @@ public: } }; -TEST_F(Integ_CreateDestroyMaster, CreateDestroyMaster) +TEST_F(Integ_CreateDestroyPrimary, CreateDestroyPrimary) { RunTickLoop([this](int tick)-> TestStatus { @@ -2843,7 +2843,7 @@ TEST_F(Integ_CreateDestroyMaster, CreateDestroyMaster) ConnectDriller(); auto replica = Replica::CreateReplica(nullptr); CreateAndAttachReplicaChunk(replica); - m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); // Destroying replica right away replica->Destroy(); @@ -2894,7 +2894,7 @@ public: LargeChunkWithDefaultsMedium* chunk = CreateAndAttachReplicaChunk(replica); AZ_TEST_ASSERT(chunk); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } ~ReplicaACKfeedbackTestFixture() diff --git a/Code/Framework/GridMate/Tests/ReplicaSmall.cpp b/Code/Framework/GridMate/Tests/ReplicaSmall.cpp index c2cd8845da..f1d78d5a18 100644 --- a/Code/Framework/GridMate/Tests/ReplicaSmall.cpp +++ b/Code/Framework/GridMate/Tests/ReplicaSmall.cpp @@ -234,7 +234,7 @@ public: /** * OfflineModeTest verifies that replica chunks are usable without -* an active session, and basically behave as masters. +* an active session, and basically behave as primarys. */ class OfflineModeTest : public UnitTest::GridMateMPTestFixture @@ -297,7 +297,7 @@ public: AZ_TEST_ASSERT(OfflineChunk::s_nInstances == 1); ReplicaChunkPtr chunkPtr = offlineChunk; chunkPtr->Init(ReplicaChunkClassId(OfflineChunk::GetChunkName())); - AZ_TEST_ASSERT(chunkPtr->IsMaster()); + AZ_TEST_ASSERT(chunkPtr->IsPrimary()); AZ_TEST_ASSERT(!chunkPtr->IsProxy()); offlineChunk->m_data1.Set(5); AZ_TEST_ASSERT(offlineChunk->m_data1.Get() == 5); @@ -315,7 +315,7 @@ public: return true; }); AZ_TEST_ASSERT(offlineChunk->m_data2.Get() == 10); - AZ_TEST_ASSERT(offlineChunk->m_nCallsDataSetChangeCB == 0); // DataSet change CB doesn't get called on master. + AZ_TEST_ASSERT(offlineChunk->m_nCallsDataSetChangeCB == 0); // DataSet change CB doesn't get called on primary. offlineChunk->CallRpc(); AZ_TEST_ASSERT(offlineChunk->m_nCallsRpcHandlerCB == 1); @@ -325,11 +325,11 @@ public: AZ_TEST_ASSERT(strcmp(offlineReplica->GetDebugName(), replicaName) == 0); offlineReplica->AttachReplicaChunk(chunkPtr); - AZ_TEST_ASSERT(chunkPtr->IsMaster()); + AZ_TEST_ASSERT(chunkPtr->IsPrimary()); AZ_TEST_ASSERT(!chunkPtr->IsProxy()); offlineReplica->DetachReplicaChunk(chunkPtr); - AZ_TEST_ASSERT(chunkPtr->IsMaster()); + AZ_TEST_ASSERT(chunkPtr->IsPrimary()); AZ_TEST_ASSERT(!chunkPtr->IsProxy()); AZ_TEST_ASSERT(OfflineChunk::s_nInstances == 1); @@ -462,7 +462,7 @@ public: ReplicaPeer peer(&rm); AZ_TracePrintf("GridMate", "\n"); - Replica* replica = Replica::CreateReplica("TestMasterReplica"); + Replica* replica = Replica::CreateReplica("TestPrimaryReplica"); ReplicaChunkDescriptorTable::Get().RegisterChunkType(); AZStd::unique_ptr chunk(CreateReplicaChunk()); diff --git a/Code/Framework/Tests/GridMocks.h b/Code/Framework/Tests/GridMocks.h deleted file mode 100644 index 08426bf5a6..0000000000 --- a/Code/Framework/Tests/GridMocks.h +++ /dev/null @@ -1,58 +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 - -namespace UnitTest -{ - class MockSession - : public GridMate::GridSession - { - public: - MockSession(GridMate::SessionService* service) - : GridSession(service) - { - } - - void SetReplicaManager(GridMate::ReplicaManager* replicaManager) - { - m_replicaMgr = replicaManager; - } - - MOCK_METHOD4(CreateRemoteMember, GridMate::GridMember*(const GridMate::string&, GridMate::ReadBuffer&, GridMate::RemotePeerMode, GridMate::ConnectionID)); - MOCK_METHOD1(OnSessionParamChanged, void(const GridMate::GridSessionParam&)); - MOCK_METHOD1(OnSessionParamRemoved, void(const GridMate::string&)); - }; - - class MockSessionService - : public GridMate::SessionService - { - public: - MockSessionService() - : SessionService(GridMate::SessionServiceDesc()) - { - } - - ~MockSessionService() - { - m_activeSearches.clear(); - m_gridMate = nullptr; - } - - MOCK_CONST_METHOD0(IsReady, bool()); - }; -} diff --git a/Code/Framework/Tests/InterestManagerComponentTests.cpp b/Code/Framework/Tests/InterestManagerComponentTests.cpp deleted file mode 100644 index f321609785..0000000000 --- a/Code/Framework/Tests/InterestManagerComponentTests.cpp +++ /dev/null @@ -1,151 +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 "GridMocks.h" - -#include -#include -#include - -#include -#include -#include - -namespace UnitTest -{ - using testing::_; - - class MockInterestManagerEvents - : public AzFramework::InterestManagerEventsBus::Handler - { - public: - MockInterestManagerEvents() - { - BusConnect(); - } - - virtual ~MockInterestManagerEvents() - { - BusDisconnect(); - } - - MOCK_METHOD1(OnInterestManagerActivate, void(GridMate::InterestManager* im)); - MOCK_METHOD1(OnInterestManagerDeactivate, void(GridMate::InterestManager* im)); - }; - - class InterestManagerComponentFixture - : public AllocatorsFixture - { - public: - InterestManagerComponentFixture() - : AllocatorsFixture() - { - - } - - ~InterestManagerComponentFixture() - { - - } - - void SetUp() override - { - AZ::AzSock::Startup(); - - AllocatorsFixture::SetUp(); - AZ::AllocatorInstance::Create(); - m_gridMate = GridMate::GridMateCreate(GridMate::GridMateDesc()); - m_carrier = GridMate::DefaultCarrier::Create(GridMate::CarrierDesc(), m_gridMate); - - m_sessionService = AZStd::make_unique(); - m_gridSession = AZStd::make_unique(m_sessionService.get()); - - m_replicaManagerDesc.m_carrier = m_carrier; - m_replicaManagerDesc.m_myPeerId = AZ::Crc32(testing::UnitTest::GetInstance()->current_test_info()->test_case_name()); - m_replicaManagerDesc.m_roles = GridMate::ReplicaMgrDesc::Role_SyncHost; - m_replicaManager = AZStd::make_unique(); - m_replicaManager->Init(m_replicaManagerDesc); - - m_gridSession->SetReplicaManager(m_replicaManager.get()); - } - - void TearDown() override - { - m_gridSession = nullptr; - m_sessionService = nullptr; - - m_replicaManager->Shutdown(); - m_replicaManager = nullptr; - - m_carrier->Shutdown(); - delete m_carrier; - GridMate::GridMateDestroy(m_gridMate); - AZ::AllocatorInstance::Destroy(); - AllocatorsFixture::TearDown(); - - AZ::AzSock::Cleanup(); - } - - AZStd::unique_ptr m_sessionService; - AZStd::unique_ptr m_gridSession; - - GridMate::IGridMate* m_gridMate; - GridMate::Carrier* m_carrier; - - GridMate::ReplicaMgrDesc m_replicaManagerDesc; - AZStd::unique_ptr m_replicaManager; - }; - - TEST_F(InterestManagerComponentFixture, TestNetworkSessionDeactivate) - { - // Using StrictMock here will ensure that the test fails if any of the events fire (as no EXPECT_CALL has been set). - testing::StrictMock interestManagerEvents; - AzFramework::InterestManagerComponent interestManagerComponent; - - // This will connect the component to the NetBindingSystemEventsBus - interestManagerComponent.Activate(); - - // Ensure that the interest manager component handles receiving OnNetworkSessionDeactivated for a session that was never activated. - // This can happen in the event of a client failing to connect to a host. - AzFramework::NetBindingSystemEventsBus::Broadcast( - &AzFramework::NetBindingSystemEvents::OnNetworkSessionDeactivated, m_gridSession.get()); - - interestManagerComponent.Deactivate(); - } - - TEST_F(InterestManagerComponentFixture, TestNetworkSessionActivateAndDeactivate) - { - // Using StrictMock here will ensure that the test fails if any of the events fire (as no EXPECT_CALL has been set). - testing::StrictMock interestManagerEvents; - AzFramework::InterestManagerComponent interestManagerComponent; - GridMate::ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - GridMate::ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - - // This will connect the component to the NetBindingSystemEventsBus - interestManagerComponent.Activate(); - - // Golden path test that the interest manager component behaves as expected under normal conditions - // (receiving OnNetworkSessionActivated followed by OnNetworkSessionDeactivated). - testing::Expectation activationEvent = EXPECT_CALL(interestManagerEvents, OnInterestManagerActivate(_)) - .Times(1); - AzFramework::NetBindingSystemEventsBus::Broadcast( - &AzFramework::NetBindingSystemEvents::OnNetworkSessionActivated, m_gridSession.get()); - - EXPECT_CALL(interestManagerEvents, OnInterestManagerDeactivate(_)) - .Times(1) - .After(activationEvent); - AzFramework::NetBindingSystemEventsBus::Broadcast( - &AzFramework::NetBindingSystemEvents::OnNetworkSessionDeactivated, m_gridSession.get()); - - interestManagerComponent.Deactivate(); - } -} diff --git a/Code/Framework/Tests/NetBinding.cpp b/Code/Framework/Tests/NetBinding.cpp deleted file mode 100644 index cf2455be0f..0000000000 --- a/Code/Framework/Tests/NetBinding.cpp +++ /dev/null @@ -1,600 +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 -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace UnitTest -{ -#if 0 - using namespace AZ; - - /** - */ - class NetBindingTestComponent - : public AZ::Component - , public AzFramework::NetBindable - { - friend class NetBindingComponentChunk; - - public: - AZ_COMPONENT(NetBindingTestComponent, "{DE5CF1C0-B4B6-4BB0-86FE-936B400871E0}", AzFramework::NetBindable); - - protected: - class NetChunk - : public GridMate::ReplicaChunk - { - public: - AZ_CLASS_ALLOCATOR(NetChunk, AZ::SystemAllocator, 0); - - static const char* GetChunkName() { return "NetBindingTestComponent::NetChunk"; } - - bool IsReplicaMigratable() override { return false; } - }; - - /////////////////////////////////////////////////////////////////////// - // NetBindable - GridMate::ReplicaChunkPtr GetNetworkBinding() override - { - AZ_TracePrintf("NetBinding", "NetBindingTestComponent::GetNetworkBinding()\n"); - m_chunk = GridMate::CreateReplicaChunk(); - AZ_Assert(m_chunk, "Failed to create NetBindingTestComponent::NetChunk!"); - return m_chunk; - } - - void SetNetworkBinding(GridMate::ReplicaChunkPtr binding) override - { - AZ_TracePrintf("NetBinding", "NetBindingTestComponent::SetNetworkBinding()\n"); - AZ_TEST_ASSERT(binding); - AZ_TEST_ASSERT(binding->GetDescriptor()->GetChunkTypeId() == GridMate::ReplicaChunkClassId(NetChunk::GetChunkName())); - m_chunk = AZStd::static_pointer_cast(binding); - } - - void UnbindFromNetwork() override - { - if (m_chunk) - { - AZ_TracePrintf("NetBinding", "NetBindingTestComponent::UnbindFromNetwork()\n"); - m_chunk = nullptr; - } - } - /////////////////////////////////////////////////////////////////////// - - /////////////////////////////////////////////////////////////////////// - // AZ::Component - static void Reflect(AZ::ReflectContext* reflection) - { - AZ::SerializeContext* serializeContext = azrtti_cast(reflection); - if (serializeContext) - { - serializeContext->Class() - ; - } - - // We also need to register the chunk type, and this would be a good time to do so. - GridMate::ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - } - - void Activate() override - { - AZ_TracePrintf("NetBinding", "NetBindingTestComponent::Activate()\n"); - } - - void Deactivate() override - { - AZ_TracePrintf("NetBinding", "NetBindingTestComponent::Deactivate()\n"); - UnbindFromNetwork(); - } - /////////////////////////////////////////////////////////////////////// - - AZStd::intrusive_ptr m_chunk; - }; - - /** - * Fakes the behavior of NetBindingSystemContextData on the host side - */ - class FakeNetBindingContextChunk - : public GridMate::ReplicaChunk - { - public: - AZ_CLASS_ALLOCATOR(FakeNetBindingContextChunk, AZ::SystemAllocator, 0); - - static const char* GetChunkName() { return "NetBindingSystemContextData"; } // We are pretending to be a NetBindingSystemContextData - - FakeNetBindingContextChunk() - : m_bindingContextSequence("BindingContextSequence", AzFramework::UnspecifiedNetBindingContextSequence) - { - } - - bool IsReplicaMigratable() override { return true; } - - GridMate::DataSet m_bindingContextSequence; - }; - - /* - * NetBindingSystemComponentLifecycleTest - */ - class NetBindingSystemComponentLifecycleTest - : public GridMate::SessionEventBus::Handler - , public AzFramework::NetBindingHandlerBus::Handler - { - public: - void OnSessionCreated(GridMate::GridSession* session) override - { - if (session == m_session) - { - if (session->IsHost()) - { - EBUS_EVENT(AzFramework::NetBindingSystemBus, OnNetworkSessionActivated, session); - } - } - } - - void OnSessionJoined(GridMate::GridSession* session) override - { - if (session == m_session) - { - EBUS_EVENT(AzFramework::NetBindingSystemBus, OnNetworkSessionActivated, session); - } - } - - void OnSessionDelete(GridMate::GridSession* session) - { - if (session == m_session) - { - EBUS_EVENT(AzFramework::NetBindingSystemBus, OnNetworkSessionDeactivated, session); - m_session = nullptr; - } - } - - void BindToNetwork(GridMate::ReplicaPtr bindTo) override - { - // Verify that BindToNetwork() is not called more than once - AZ_TEST_ASSERT(!m_receivedBindEvent); - m_receivedBindEvent = true; - - // Test that now we should be binding to the network - bool shouldBindToNetwork = false; - EBUS_EVENT_RESULT(shouldBindToNetwork, AzFramework::NetBindingSystemBus, ShouldBindToNetwork); - AZ_TEST_ASSERT(shouldBindToNetwork); - - // Verify that the context sequence is no longer unspecified - AzFramework::NetBindingContextSequence contextSequence = AzFramework::UnspecifiedNetBindingContextSequence; - EBUS_EVENT_RESULT(contextSequence, AzFramework::NetBindingSystemBus, GetCurrentContextSequence); - AZ_TEST_ASSERT(contextSequence != AzFramework::UnspecifiedNetBindingContextSequence); - } - - void UnbindFromNetwork() override - { - // Verify that UnbindFromNetwork() is not called more than once - AZ_TEST_ASSERT(!m_receivedUnbindEvent); - m_receivedUnbindEvent = true; - } - - void run() - { - // Setup - AZ::ComponentApplication app; - AZ::ComponentApplication::Descriptor appDesc; - appDesc.m_recordsMode = AZ::Debug::AllocationRecords::RECORD_FULL; - AZ::Entity* systemEntity = app.Create(appDesc); - - app.RegisterComponentDescriptor(AzFramework::NetBindingSystemComponent::CreateDescriptor()); - app.RegisterComponentDescriptor(AzFramework::GameEntityContextComponent::CreateDescriptor()); - - systemEntity->Init(); - systemEntity->CreateComponent(); - systemEntity->CreateComponent(); - systemEntity->CreateComponent(); - systemEntity->CreateComponent(); - systemEntity->Activate(); - AzFramework::NetBindingHandlerBus::Handler::BusConnect(); - - GridMate::GridMateDesc gridMateDesc; - GridMate::IGridMate* gridMate = GridMate::GridMateCreate(gridMateDesc); - GridMate::GridMateAllocatorMP::Descriptor allocDesc; - allocDesc.m_stackRecordLevels = 15; - allocDesc.m_custom = &AZ::AllocatorInstance::Get(); - AZ::AllocatorInstance::Create(allocDesc); - if (AZ::AllocatorInstance::Get().GetRecords()) - { - AZ::AllocatorInstance::Get().GetRecords()->SetMode(AZ::Debug::AllocationRecords::RECORD_FULL); - } - GridMate::StartGridMateService(gridMate, GridMate::SessionServiceDesc()); - GridMate::SessionEventBus::Handler::BusConnect(gridMate); - - // Test offline behavior - { - bool shouldBindToNetwork = true; - EBUS_EVENT_RESULT(shouldBindToNetwork, AzFramework::NetBindingSystemBus, ShouldBindToNetwork); - AZ_TEST_ASSERT(!shouldBindToNetwork); - - AzFramework::NetBindingContextSequence offlineContextSequence = 0xBADF00D; - EBUS_EVENT_RESULT(offlineContextSequence, AzFramework::NetBindingSystemBus, GetCurrentContextSequence); - AZ_TEST_ASSERT(offlineContextSequence == AzFramework::UnspecifiedNetBindingContextSequence); - } - - // Test host-side behavior - { - m_receivedBindEvent = m_receivedUnbindEvent = false; - - // Host a session - GridMate::CarrierDesc carrierDesc; - carrierDesc.m_enableDisconnectDetection = true; - GridMate::LANSessionParams sessionParams; - sessionParams.m_numPublicSlots = 10; - sessionParams.m_flags = 0; - sessionParams.m_port = HOST_PORT; - sessionParams.m_params[sessionParams.m_numParams].m_id = "filter"; - sessionParams.m_params[sessionParams.m_numParams].m_value = GridMate::Utils::GetMachineAddress(); - sessionParams.m_numParams++; - m_session = gridMate->GetMultiplayerService()->HostSession(&sessionParams, carrierDesc); - - int nFrame = 0; - while (m_session) - { - if (nFrame == 10) - { - // Verify that BindToNetwork() has been called - AZ_TEST_ASSERT(m_receivedBindEvent); - - // Verify that we have a valid context sequence - AzFramework::NetBindingContextSequence contextSequence1 = AzFramework::UnspecifiedNetBindingContextSequence; - EBUS_EVENT_RESULT(contextSequence1, AzFramework::NetBindingSystemBus, GetCurrentContextSequence); - AZ_TEST_ASSERT(contextSequence1 != AzFramework::UnspecifiedNetBindingContextSequence); - - EBUS_EVENT(AzFramework::GameEntityContextRequestBus, ResetGameContext); - - // Verify that the context sequence was incremented - AzFramework::NetBindingContextSequence contextSequence2 = contextSequence1; - EBUS_EVENT_RESULT(contextSequence2, AzFramework::NetBindingSystemBus, GetCurrentContextSequence); - AZ_TEST_ASSERT(contextSequence2 != AzFramework::UnspecifiedNetBindingContextSequence); - AZ_TEST_ASSERT(contextSequence2 > contextSequence1); - - m_session->Leave(false); - } - - app.Tick(); - gridMate->Update(); - AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(10)); - nFrame++; - } - - // Verify that we should no longer bind to the network - bool shouldBindToNetwork = true; - EBUS_EVENT_RESULT(shouldBindToNetwork, AzFramework::NetBindingSystemBus, ShouldBindToNetwork); - AZ_TEST_ASSERT(!shouldBindToNetwork); - - // Verify that the context sequence was reset to unspecified - AzFramework::NetBindingContextSequence offlineContextSequence = 0xBADF00D; - EBUS_EVENT_RESULT(offlineContextSequence, AzFramework::NetBindingSystemBus, GetCurrentContextSequence); - AZ_TEST_ASSERT(offlineContextSequence == AzFramework::UnspecifiedNetBindingContextSequence); - } - - // Test nonhost-side behavior by faking the behavior on the host side and then joining the host session. - { - m_receivedBindEvent = m_receivedUnbindEvent = false; - - // Host a session - GridMate::CarrierDesc carrierDesc; - carrierDesc.m_enableDisconnectDetection = true; - GridMate::LANSessionParams sessionParams; - sessionParams.m_numPublicSlots = 10; - sessionParams.m_flags = 0; - sessionParams.m_port = HOST_PORT; - sessionParams.m_params[sessionParams.m_numParams].m_id = "filter"; - sessionParams.m_params[sessionParams.m_numParams].m_value = GridMate::Utils::GetMachineAddress(); - sessionParams.m_numParams++; - GridMate::GridSession* hostSession = gridMate->GetMultiplayerService()->HostSession(&sessionParams, carrierDesc); - - // Add the fake context replica on the host and set the context sequence to 1 - GridMate::ReplicaPtr replica = GridMate::Replica::CreateReplica("Potato"); - FakeNetBindingContextChunk* contextChunk = GridMate::CreateReplicaChunk(); - replica->AttachReplicaChunk(contextChunk); - while (!hostSession->IsReady()) - { - gridMate->Update(); - AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(10)); - } - hostSession->GetReplicaMgr()->AddMaster(replica); - contextChunk->m_bindingContextSequence.Set(1); - - int nFrame = 0; - while (m_session) - { - if (nFrame == 10) - { - // Join the hosted session - GridMate::SessionIdInfo sessionInfo; - sessionInfo.m_sessionId = hostSession->GetId(); - m_session = gridMate->GetMultiplayerService()->JoinSession(&sessionInfo, GridMate::JoinParams(), carrierDesc); - } - - if (nFrame == 20) - { - // Verify that BindToNetwork() has been called - AZ_TEST_ASSERT(m_receivedBindEvent); - - // Verify that we have a valid context sequence - AzFramework::NetBindingContextSequence contextSequence = AzFramework::UnspecifiedNetBindingContextSequence; - EBUS_EVENT_RESULT(contextSequence, AzFramework::NetBindingSystemBus, GetCurrentContextSequence); - AZ_TEST_ASSERT(contextSequence == contextChunk->m_bindingContextSequence.Get()); - - // Simulate a context switch on the host - contextChunk->m_bindingContextSequence.Set(contextChunk->m_bindingContextSequence.Get() + 1); - } - - if (nFrame == 30) - { - // Verify that the context sequence was incremented - AzFramework::NetBindingContextSequence contextSequence = AzFramework::UnspecifiedNetBindingContextSequence; - EBUS_EVENT_RESULT(contextSequence, AzFramework::NetBindingSystemBus, GetCurrentContextSequence); - AZ_TEST_ASSERT(contextSequence == contextChunk->m_bindingContextSequence.Get()); - - hostSession->Leave(false); - } - - app.Tick(); - gridMate->Update(); - AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(10)); - nFrame++; - } - - // Verify that we should no longer bind to the network - bool shouldBindToNetwork = true; - EBUS_EVENT_RESULT(shouldBindToNetwork, AzFramework::NetBindingSystemBus, ShouldBindToNetwork); - AZ_TEST_ASSERT(!shouldBindToNetwork); - - // Verify that the context sequence was reset to unspecified - AzFramework::NetBindingContextSequence offlineContextSequence = 0xBADF00D; - EBUS_EVENT_RESULT(offlineContextSequence, AzFramework::NetBindingSystemBus, GetCurrentContextSequence); - AZ_TEST_ASSERT(offlineContextSequence == AzFramework::UnspecifiedNetBindingContextSequence); - } - - // Clean up - GridMate::SessionEventBus::Handler::BusDisconnect(); - GridMate::GridMateDestroy(gridMate); - AZ::AllocatorInstance::Destroy(); - AzFramework::NetBindingHandlerBus::Handler::BusDisconnect(); - app.Destroy(); - } - - static const int HOST_PORT = 5000; - - GridMate::GridSession* m_session; - bool m_receivedBindEvent; - bool m_receivedUnbindEvent; - }; - - /* - * NetBindingFeatureTest (requires two instances) - */ - class NetBindingFeatureTest - : public GridMate::SessionEventBus::Handler - { - public: - void OnSessionCreated(GridMate::GridSession* session) override - { - if (session == m_session) - { - if (session->IsHost()) - { - EBUS_EVENT(AzFramework::NetBindingSystemBus, OnNetworkSessionActivated, session); - } - } - } - - void OnSessionJoined(GridMate::GridSession* session) override - { - if (session == m_session) - { - EBUS_EVENT(AzFramework::NetBindingSystemBus, OnNetworkSessionActivated, session); - } - } - - void OnSessionDelete(GridMate::GridSession* session) - { - if (session == m_session) - { - EBUS_EVENT(AzFramework::NetBindingSystemBus, OnNetworkSessionDeactivated, session); - m_session = nullptr; - } - } - - void OnGridSearchComplete(GridMate::GridSearch* results) override - { - if (results == m_search) - { - GridMate::CarrierDesc carrierDesc; - carrierDesc.m_enableDisconnectDetection = true; - - // Create an entity before we get in the session - AZ_TracePrintf("NetBinding", "Spawning master entity...\n"); - AZ::Entity* newEntity = nullptr; - newEntity = aznew Entity; - newEntity->CreateComponent(); - newEntity->CreateComponent(); - newEntity->Init(); - newEntity->Activate(); - m_entities.push_back(newEntity); - - if (results->GetNumResults() == 0) - { - // Host a session instead - GridMate::LANSessionParams sessionParams; - sessionParams.m_numPublicSlots = 10; - sessionParams.m_flags = 0; - sessionParams.m_port = HOST_PORT; - sessionParams.m_params[sessionParams.m_numParams].m_id = "filter"; - sessionParams.m_params[sessionParams.m_numParams].m_value = GridMate::Utils::GetMachineAddress(); - sessionParams.m_numParams++; - m_session = m_gridMate->GetMultiplayerService()->HostSession(&sessionParams, carrierDesc); - - m_search->Release(); - } - else - { - // Join the session - GridMate::JoinParams joinParams; - m_session = m_gridMate->GetMultiplayerService()->JoinSession(results->GetResult(0), joinParams, carrierDesc); - } - m_search = nullptr; - } - } - - void OnMemberJoined(GridMate::GridSession* session, GridMate::GridMember* member) override - { - if (session == m_session) - { - if (session->IsHost()) - { - if (member != session->GetMyMember()) - { - // Spawn an entity after session creation - AZ_TracePrintf("NetBinding", "Spawning master entity...\n"); - AZ::Entity* newEntity = nullptr; - EBUS_EVENT_RESULT(newEntity, AzFramework::GameEntityContextRequestBus, CreateGameEntity, "ReplicatedEntity2"); - newEntity->CreateComponent(); - newEntity->CreateComponent(); - newEntity->Init(); - newEntity->Activate(); - m_entities.push_back(newEntity); - } - } - } - } - - void run() - { - m_gridMate = nullptr; - m_session = nullptr; - - AZ::ComponentApplication app; - AZ::ComponentApplication::Descriptor appDesc; - AZ::Entity* systemEntity = app.Create(appDesc); - - app.RegisterComponentDescriptor(AzFramework::NetBindingSystemComponent::CreateDescriptor()); - app.RegisterComponentDescriptor(AzFramework::NetBindingComponent::CreateDescriptor()); - app.RegisterComponentDescriptor(NetBindingTestComponent::CreateDescriptor()); - app.RegisterComponentDescriptor(AzFramework::GameEntityContextComponent::CreateDescriptor()); - - systemEntity->Init(); - systemEntity->CreateComponent(); - systemEntity->CreateComponent(); - systemEntity->CreateComponent(); - systemEntity->CreateComponent(); - systemEntity->Activate(); - - GridMate::GridMateDesc gridMateDesc; - m_gridMate = GridMate::GridMateCreate(gridMateDesc); - - GridMate::GridMateAllocatorMP::Descriptor allocDesc; - allocDesc.m_custom = &AZ::AllocatorInstance::Get(); - AZ::AllocatorInstance::Create(allocDesc); - - GridMate::StartGridMateService(m_gridMate, GridMate::SessionServiceDesc()); - - GridMate::SessionEventBus::Handler::BusConnect(m_gridMate); - - // Search for an existing session - // If a session is not found, we will host a session from within the search callback. - { - GridMate::LANSearchParams searchParams; - searchParams.m_serverPort = HOST_PORT; - searchParams.m_params[searchParams.m_numParams].m_id = "filter"; - searchParams.m_params[searchParams.m_numParams].m_value = GridMate::Utils::GetMachineAddress(); - searchParams.m_params[searchParams.m_numParams].m_op = GridMate::GridSessionSearchOperators::SSO_OPERATOR_EQUAL; - searchParams.m_numParams++; - m_search = m_gridMate->GetMultiplayerService()->StartGridSearch(&searchParams); - - while (m_search) - { - m_gridMate->Update(); - AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(10)); - } - } - - // Tick for a while - //static int nTicks = 100; - for (int i = 0; m_session; ++i) - { - if (m_session->IsHost()) - { - if (i > 4000 && m_session->GetNumberOfMembers() == 1) - { - m_session->Leave(false); - } - } - - m_gridMate->Update(); - app.Tick(); - AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(10)); - } - - GridMate::SessionEventBus::Handler::BusDisconnect(); - - GridMate::GridMateDestroy(m_gridMate); - - AZ::AllocatorInstance::Destroy(); - - for (AZ::Entity* entity : m_entities) - { - AzFramework::EntityContextId contextId = AzFramework::EntityContextId::CreateNull(); - EBUS_EVENT_ID_RESULT(contextId, entity->GetId(), AzFramework::EntityIdContextQueryBus, GetOwningContextId); - if (contextId.IsNull()) - { - delete entity; - } - else - { - EBUS_EVENT(AzFramework::GameEntityContextRequestBus, DestroyGameEntity, entity); - } - } - - app.Destroy(); - } - - static const int HOST_PORT = 6000; - - GridMate::IGridMate* m_gridMate; - GridMate::GridSession* m_session; - GridMate::GridSearch* m_search; - AZStd::fixed_vector m_entities; - }; -#endif -} - -AZ_TEST_SUITE(NetBinding) -//AZ_TEST(UnitTest::NetBindingSystemComponentLifecycleTest) -//AZ_TEST(UnitTest::NetBindingFeatureTest) -AZ_TEST_SUITE_END diff --git a/Code/Framework/Tests/NetBindingMocks.h b/Code/Framework/Tests/NetBindingMocks.h deleted file mode 100644 index 3973fe670d..0000000000 --- a/Code/Framework/Tests/NetBindingMocks.h +++ /dev/null @@ -1,335 +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 AZCORE_UNITTEST_NETBINDINGMOCKS_H -#define AZCORE_UNITTEST_NETBINDINGMOCKS_H - -#include -#include -#include -#include -#include -#include -#include - -namespace UnitTest -{ - class MockGameEntityContext - : public AzFramework::GameEntityContextRequestBus::Handler - , public AzFramework::SliceGameEntityOwnershipServiceRequestBus::Handler - { - public: - MockGameEntityContext() - { - AzFramework::GameEntityContextRequestBus::Handler::BusConnect(); - AzFramework::SliceGameEntityOwnershipServiceRequestBus::Handler::BusConnect(); - } - - ~MockGameEntityContext() - { - AzFramework::SliceGameEntityOwnershipServiceRequestBus::Handler::BusDisconnect(); - AzFramework::GameEntityContextRequestBus::Handler::BusDisconnect(); - } - - MOCK_METHOD3(InstantiateDynamicSlice, AzFramework::SliceInstantiationTicket(const AZ::Data::Asset&, const AZ::Transform&, const AZ::IdUtils::Remapper::IdMapper&)); - MOCK_METHOD0(GetGameEntityContextId, AzFramework::EntityContextId()); - MOCK_METHOD0(GetGameEntityContextInstance, AzFramework::EntityContext*()); - MOCK_METHOD1(CreateGameEntity, AZ::Entity*(const char*)); - MOCK_METHOD1(AddGameEntity, void (AZ::Entity*)); - MOCK_METHOD1(DestroyGameEntity, void (const AZ::EntityId&)); - MOCK_METHOD1(DestroyGameEntityAndDescendants, void (const AZ::EntityId&)); - MOCK_METHOD1(ActivateGameEntity, void (const AZ::EntityId&)); - MOCK_METHOD1(DeactivateGameEntity, void (const AZ::EntityId&)); - MOCK_METHOD1(DestroyDynamicSliceByEntity, bool (const AZ::EntityId&)); - MOCK_METHOD2(LoadFromStream, bool (AZ::IO::GenericStream&, bool)); - MOCK_METHOD0(ResetGameContext, void ()); - MOCK_METHOD1(GetEntityName, AZStd::string (const AZ::EntityId&)); - MOCK_METHOD1(DestroySliceByEntity, bool(const AZ::EntityId&)); - MOCK_METHOD1(CreateGameEntityForBehaviorContext, AzFramework::BehaviorEntity (const char *)); - MOCK_METHOD1(CancelDynamicSliceInstantiation, void (const AzFramework::SliceInstantiationTicket &)); - }; - - class MockNetBindingSystemContextData - : public AzFramework::NetBindingSystemContextData - { - public: - AZ_CLASS_ALLOCATOR(MockNetBindingSystemContextData, AZ::SystemAllocator, 0); - - static const char* GetChunkName() - { - return "MockNetBindingSystemContextData"; - } - - MOCK_METHOD1(OnAttachedToReplica, void (GridMate::Replica*)); - MOCK_METHOD1(OnDetachedFromReplica, void (GridMate::Replica*)); - MOCK_METHOD1(UpdateChunk, void (const GridMate::ReplicaContext&)); - MOCK_METHOD1(UpdateFromChunk, void (const GridMate::ReplicaContext&)); - MOCK_METHOD2(AcceptChangeOwnership, bool (GridMate::PeerId, const GridMate::ReplicaContext&)); - MOCK_METHOD1(OnReplicaChangeOwnership, void (const GridMate::ReplicaContext&)); - MOCK_METHOD0(IsUpdateFromReplicaEnabled, bool ()); - MOCK_CONST_METHOD1(ShouldSendToPeer, bool (GridMate::ReplicaPeer*)); - MOCK_METHOD1(CalculateDirtyDataSetMask, AZ::u32 (GridMate::MarshalContext&)); - MOCK_METHOD1(OnDataSetChanged, void (const GridMate::DataSetBase&)); - MOCK_METHOD2(Marshal, void (GridMate::MarshalContext&, AZ::u32)); - MOCK_METHOD2(Unmarshal, void (GridMate::UnmarshalContext&, AZ::u32)); - MOCK_METHOD0(IsReplicaMigratable, bool ()); - MOCK_METHOD0(IsBroadcast, bool ()); - MOCK_METHOD1(OnReplicaActivate, void (const GridMate::ReplicaContext&)); - MOCK_METHOD1(OnReplicaDeactivate, void (const GridMate::ReplicaContext&)); - - /** - * \brief Helper method for GoogleMock to call NetBindingSystemContextData::OnReplicaActivate - */ - void Base_OnReplicaActivate(const GridMate::ReplicaContext& rc) - { - NetBindingSystemContextData::OnReplicaActivate(rc); - } - - MOCK_METHOD0(GetReplicaManager, GridMate::ReplicaManager* ()); - MOCK_METHOD0(ShouldBindToNetwork, bool ()); - }; - - class MockReplicaManager - : public GridMate::ReplicaManager - { - public: - MOCK_METHOD2(OnIncomingConnection, void (GridMate::Carrier*, GridMate::ConnectionID)); - MOCK_METHOD3(OnFailedToConnect, void (GridMate::Carrier*, GridMate::ConnectionID, GridMate::CarrierDisconnectReason)); - MOCK_METHOD3(OnDriverError, void (GridMate::Carrier*, GridMate::ConnectionID, const GridMate::DriverError&)); - MOCK_METHOD3(OnSecurityError, void (GridMate::Carrier*, GridMate::ConnectionID, const GridMate::SecurityError&)); - MOCK_METHOD1(Destroy, bool (GridMate::Replica*)); - MOCK_METHOD2(GetReplicaContext, void (const GridMate::Replica*, GridMate::ReplicaContext&)); - MOCK_METHOD2(OnConnectionEstablished, void (GridMate::Carrier*, GridMate::ConnectionID)); - MOCK_METHOD3(OnDisconnect, void (GridMate::Carrier*, GridMate::ConnectionID, GridMate::CarrierDisconnectReason)); - MOCK_METHOD3(OnRateChange, void (GridMate::Carrier*, GridMate::ConnectionID, AZ::u32)); - MOCK_METHOD1(FindReplica, GridMate::ReplicaPtr (GridMate::ReplicaId)); - }; - - class MockAssetHandler - : public AZ::Data::AssetHandler - { - public: - AZ_CLASS_ALLOCATOR(MockAssetHandler, AZ::SystemAllocator, 0) - - MOCK_METHOD2(CreateAsset, AZ::Data::AssetPtr (const AZ::Data::AssetId&, const AZ::Data::AssetType&)); - MOCK_METHOD3(LoadAssetData, AZ::Data::AssetHandler::LoadResult ( - const AZ::Data::Asset&, - AZStd::shared_ptr, - const AZ::Data::AssetFilterCB&)); - MOCK_METHOD2(SaveAssetData, bool (const AZ::Data::Asset&, AZ::IO::GenericStream*)); - MOCK_METHOD3(InitAsset, void (const AZ::Data::Asset&, bool, bool)); - MOCK_METHOD1(DestroyAsset, void (AZ::Data::AssetPtr)); - MOCK_METHOD1(GetHandledAssetTypes, void (AZStd::vector&)); - MOCK_CONST_METHOD1(CanHandleAsset, bool (const AZ::Data::AssetId&)); - }; - - class MockAsset - : public AZ::DynamicSliceAsset - { - public: - AZ_RTTI(MockAsset, "{78ABC204-452E-4621-A552-F04D3ABF1690}", DynamicSliceAsset); - - MockAsset(const AZ::Data::AssetId& assetId = AZ::Data::AssetId()) - : DynamicSliceAsset(assetId) - { - } - - ~MockAsset() = default; - }; - - class MockSliceReference - : public AZ::SliceComponent::SliceReference - { - public: - using SliceReference::SliceReference; - - MOCK_METHOD1(CreateInstance, AZ::SliceComponent::SliceInstance*(const AZ::IdUtils::Remapper::IdMapper&)); - MOCK_METHOD2(CloneInstance, AZ::SliceComponent::SliceInstance*(AZ::SliceComponent::SliceInstance*, AZ::SliceComponent::EntityIdToEntityIdMap&)); - MOCK_METHOD1(FindInstance, AZ::SliceComponent::SliceInstance*(const AZ::SliceComponent::SliceInstanceId&)); - MOCK_METHOD1(RemoveInstance, bool(AZ::SliceComponent::SliceInstance*)); - MOCK_METHOD3(RemoveEntity, bool(AZ::EntityId, bool, AZ::SliceComponent::SliceInstance*)); - MOCK_CONST_METHOD0(GetInstances, const AZ::SliceComponent::SliceReference::SliceInstances&()); - MOCK_CONST_METHOD0(GetSliceAsset, const AZ::Data::Asset& ()); - MOCK_CONST_METHOD0(GetSliceComponent, AZ::SliceComponent*()); - MOCK_CONST_METHOD0(IsInstantiated, bool ()); - MOCK_CONST_METHOD3(GetInstanceEntityAncestry, bool(const AZ::EntityId&, AZ::SliceComponent::EntityAncestorList&, AZ::u32)); - MOCK_METHOD0(ComputeDataPatch, void()); - }; - - class MockSliceInstance - : public AZ::SliceComponent::SliceInstance - { - public: - using SliceInstance::SliceInstance; - - void SetMockInstantiatedContainer(AZ::SliceComponent::InstantiatedContainer* newContainer) - { - m_instantiated = newContainer; - - for (AZ::Entity* entity : m_instantiated->m_entities) - { - m_entityIdToBaseCache.insert(AZStd::make_pair(entity->GetId(), entity->GetId())); - } - - for (AZ::Entity* entity : m_instantiated->m_entities) - { - m_baseToNewEntityIdMap.insert(AZStd::make_pair(entity->GetId(), entity->GetId())); - } - } - - MOCK_CONST_METHOD0(GetInstantiated, const AZ::SliceComponent::InstantiatedContainer*()); - MOCK_CONST_METHOD0(GetDataPatch, const AZ::DataPatch&()); - MOCK_CONST_METHOD0(GetDataFlags, const AZ::SliceComponent::DataFlagsPerEntity&()); - MOCK_METHOD0(GetDataFlags, AZ::SliceComponent::DataFlagsPerEntity&()); - MOCK_CONST_METHOD0(GetEntityIdMap, const AZ::SliceComponent::EntityIdToEntityIdMap& ()); - MOCK_CONST_METHOD0(GetEntityIdToBaseMap, const AZ::SliceComponent::EntityIdToEntityIdMap& ()); - MOCK_CONST_METHOD0(GetId, const AZ::SliceComponent::SliceInstanceId& ()); - MOCK_CONST_METHOD0(GetMetadataEntity, AZ::Entity* ()); - }; - - class MockEntity - : public AZ::Entity - { - public: - ~MockEntity() override {} - - MOCK_METHOD0(Init, void ()); - MOCK_METHOD0(Activate, void ()); - MOCK_METHOD0(Deactivate, void ()); - - /** - * \brief Helper method for GoogleMock to call base class method - */ - void Base_Init() - { - Entity::Init(); - } - - /** - * \brief Helper method for GoogleMock to mark an entity as activated - */ - void Base_Activate() - { - m_state = State::Active; - } - - /** - * \brief Helper method for GoogleMock to mark an entity as deactivated - */ - void Base_Deactivate() - { - m_state = State::Init; - } - }; - - class MockComponentApplication - : public AZ::ComponentApplicationBus::Handler - { - public: - MockComponentApplication() - { - AZ::ComponentApplicationBus::Handler::BusConnect(); - AZ::Interface::Register(this); - } - ~MockComponentApplication() - { - AZ::Interface::Unregister(this); - AZ::ComponentApplicationBus::Handler::BusDisconnect(); - } - - AZStd::vector m_mockEntities; - - bool AddEntity(AZ::Entity* entity) override - { - const auto it = AZStd::find(m_mockEntities.begin(), m_mockEntities.end(), entity); - if (it == m_mockEntities.end()) - { - m_mockEntities.push_back(entity); - return true; - } - - return false; - } - - AZ::Entity* FindEntity(const AZ::EntityId& id) override - { - const auto it = AZStd::find_if(m_mockEntities.begin(), m_mockEntities.end(), [id](AZ::Entity* entity) - { - return entity->GetId() == id; - }); - - if (it != m_mockEntities.end()) - { - return *it; - } - return nullptr; - } - - MOCK_METHOD0(Destroy, void ()); - MOCK_METHOD1(RegisterComponentDescriptor, void (const AZ::ComponentDescriptor*)); - MOCK_METHOD1(UnregisterComponentDescriptor, void (const AZ::ComponentDescriptor*)); - MOCK_METHOD1(RegisterEntityAddedEventHandler, void(AZ::EntityAddedEvent::Handler&)); - MOCK_METHOD1(RegisterEntityRemovedEventHandler, void(AZ::EntityRemovedEvent::Handler&)); - MOCK_METHOD1(RegisterEntityActivatedEventHandler, void(AZ::EntityActivatedEvent::Handler&)); - MOCK_METHOD1(RegisterEntityDeactivatedEventHandler, void(AZ::EntityDeactivatedEvent::Handler&)); - MOCK_METHOD1(SignalEntityActivated, void(AZ::Entity*)); - MOCK_METHOD1(SignalEntityDeactivated, void(AZ::Entity*)); - MOCK_METHOD1(RemoveEntity, bool (AZ::Entity*)); - MOCK_METHOD1(DeleteEntity, bool (const AZ::EntityId&)); - MOCK_METHOD1(GetEntityName, AZStd::string (const AZ::EntityId&)); - MOCK_METHOD1(EnumerateEntities, void (const ComponentApplicationRequests::EntityCallback&)); - MOCK_METHOD0(GetApplication, AZ::ComponentApplication* ()); - MOCK_METHOD0(GetSerializeContext, AZ::SerializeContext* ()); - MOCK_METHOD0(GetBehaviorContext, AZ::BehaviorContext* ()); - MOCK_METHOD0(GetJsonRegistrationContext, AZ::JsonRegistrationContext* ()); - MOCK_CONST_METHOD0(GetAppRoot, const char* ()); - MOCK_CONST_METHOD0(GetEngineRoot, const char* ()); - MOCK_CONST_METHOD0(GetExecutableFolder, const char* ()); - MOCK_METHOD0(GetDrillerManager, AZ::Debug::DrillerManager* ()); - MOCK_METHOD0(GetTickDeltaTime, float ()); - MOCK_METHOD0(GetTimeAtCurrentTick, AZ::ScriptTimePoint ()); - MOCK_METHOD1(Tick, void (float)); - MOCK_METHOD0(TickSystem, void ()); - MOCK_CONST_METHOD0(GetRequiredSystemComponents, AZ::ComponentTypeList ()); - MOCK_METHOD1(ResolveModulePath, void (AZ::OSString&)); - MOCK_METHOD0(RegisterCoreComponents, void ()); - MOCK_METHOD1(Reflect, void (AZ::ReflectContext*)); - MOCK_CONST_METHOD1(QueryApplicationType, void(AZ::ApplicationTypeQuery&)); - }; - - class MockBindingComponent - : public AZ::Component - , public AzFramework::NetBindingHandlerBus::Handler - { - public: - AZ_COMPONENT(MockBindingComponent, "{8393809A-3256-4865-97A9-1CCA43073B4A}", NetBindingHandlerInterface); - - static void Reflect(AZ::ReflectContext*) {} - - MOCK_METHOD0(Init, void ()); - MOCK_METHOD0(Activate, void ()); - MOCK_METHOD0(Deactivate, void ()); - MOCK_METHOD1(ReadInConfig, bool (const AZ::ComponentConfig*)); - MOCK_CONST_METHOD1(WriteOutConfig, bool (AZ::ComponentConfig*)); - MOCK_METHOD1(BindToNetwork, void (GridMate::ReplicaPtr)); - MOCK_METHOD0(UnbindFromNetwork, void ()); - MOCK_METHOD0(IsEntityBoundToNetwork, bool ()); - MOCK_METHOD0(IsEntityAuthoritative, bool ()); - MOCK_METHOD0(MarkAsLevelSliceEntity, void ()); - MOCK_METHOD1(SetSliceInstanceId, void (const AZ::SliceComponent::SliceInstanceId&)); - MOCK_METHOD1(SetReplicaPriority, void (GridMate::ReplicaPriority)); - MOCK_METHOD1(RequestEntityChangeOwnership, void (GridMate::PeerId)); - MOCK_CONST_METHOD0(GetReplicaPriority, GridMate::ReplicaPriority ()); - }; -} - -#endif // AZCORE_UNITTEST_NETBINDINGMOCKS_H diff --git a/Code/Framework/Tests/NetBindingSystemImplTest.cpp b/Code/Framework/Tests/NetBindingSystemImplTest.cpp deleted file mode 100644 index 790ef1cd72..0000000000 --- a/Code/Framework/Tests/NetBindingSystemImplTest.cpp +++ /dev/null @@ -1,605 +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 -#include "NetBindingMocks.h" -#include -#include -#include -#include - -namespace UnitTest -{ - using namespace AZ; - using namespace AzFramework; - using namespace GridMate; - - class NetBindingWithSlicesTest - : public ScopedAllocatorSetupFixture - { - public: - const NetBindingContextSequence k_fakeContextSeq = 1; - const AZ::SliceComponent::SliceInstanceId k_fakeSliceInstanceId = Uuid::CreateRandom(); - const AZ::SliceComponent::SliceInstanceId k_fakeSliceInstanceId_Another = Uuid::CreateRandom(); - - SliceInstantiationTicket m_sliceTicket = SliceInstantiationTicket(EntityContextId::CreateName("Test"), 1); - const Data::AssetId k_fakeAssetId = Data::AssetId(Uuid::CreateRandom(), 0); - - const EntityId k_fakeEntityId_One = EntityId(9001); - const ReplicaId k_repId_One = 1001; - const EntityId k_fakeEntityId_Two = EntityId(9002); - const ReplicaId k_repId_Two = 1002; - - AZStd::unique_ptr m_netBindingImpl; - AZStd::unique_ptr m_componentApplication; - AZStd::unique_ptr m_applicationContext; - - AZStd::unique_ptr m_gameEntityMock; - AZStd::unique_ptr m_replicaManagerMock; - ReplicaPtr m_replicaMock; - - ComponentDescriptor* m_netBindingSystemComponentDescriptor = nullptr; - - AZStd::intrusive_ptr m_contextChunkMock; - - MockAssetHandler* m_myAssetHandlerAndCatalog = nullptr; // owned by AssetManager - AZStd::unique_ptr m_fakeAsset; - - const float k_wayOverSliceTimeout = NetBindingSystemImpl::s_sliceBindingTimeout.count() * 2.f; - const float k_smallStep = 0.1f; - - void SetUpFakeAssetManager() - { - using namespace testing; - - const Data::AssetManager::Descriptor desc; - Data::AssetManager::Create(desc); - - m_myAssetHandlerAndCatalog = aznew NiceMock; - - ON_CALL(*m_myAssetHandlerAndCatalog, CreateAsset(_, _)) - .WillByDefault(Invoke([this](const Data::AssetId&, const Data::AssetType&) -> Data::AssetPtr - { - m_fakeAsset = AZStd::make_unique>(k_fakeAssetId); - return m_fakeAsset.get(); - })); - - ON_CALL(*m_myAssetHandlerAndCatalog, DestroyAsset(_)) - .WillByDefault(Invoke([this](const Data::AssetPtr asset) - { - EXPECT_EQ(asset, m_fakeAsset.get()); - m_fakeAsset.reset(); - })); - - Data::AssetManager::Instance().RegisterHandler(m_myAssetHandlerAndCatalog, AzTypeInfo::Uuid()); - Data::AssetManager::Instance().RegisterHandler(m_myAssetHandlerAndCatalog, AzTypeInfo::Uuid()); - } - - void SetUp() override - { - using namespace testing; - - m_applicationContext.reset(aznew SerializeContext()); - - AllocatorInstance::Create(); - AllocatorInstance::Create(); - - DefaultValue::Set(m_sliceTicket); - - m_gameEntityMock = AZStd::make_unique>(); - m_componentApplication = AZStd::make_unique>(); - - ON_CALL(*m_componentApplication, GetSerializeContext()) - .WillByDefault(Invoke([this]() - { - return m_applicationContext.get(); - })); - - ON_CALL(*m_gameEntityMock, GetGameEntityContextId()) - .WillByDefault(Return(EntityContextId::CreateRandom())); - - m_netBindingSystemComponentDescriptor = NetBindingSystemComponent::CreateDescriptor(); - - ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - m_contextChunkMock.reset(CreateReplicaChunk>()); - - ON_CALL(*m_contextChunkMock, ShouldBindToNetwork()) - .WillByDefault(Return(true)); - - m_replicaManagerMock = AZStd::make_unique>(); - - ON_CALL(*m_contextChunkMock, GetReplicaManager()) - .WillByDefault(Invoke([this]() - { - return m_replicaManagerMock.get(); - })); - - m_replicaMock = Replica::CreateReplica("unittest"); - - ON_CALL(*m_replicaManagerMock, FindReplica(_)) - .WillByDefault(Invoke([this](ReplicaId id) -> ReplicaPtr - { - AZ_UNUSED(id); - return m_replicaMock; - })); - - ON_CALL(*m_contextChunkMock, OnReplicaActivate(_)) - .WillByDefault(Invoke(m_contextChunkMock.get(), &MockNetBindingSystemContextData::Base_OnReplicaActivate)); - - m_netBindingImpl = AZStd::make_unique(); - m_netBindingImpl->Init(); - - m_contextChunkMock->OnReplicaActivate(ReplicaContext(nullptr, TimeContext())); - - SetUpFakeAssetManager(); - } - - void TearDown() override - { - Data::AssetManager::Destroy(); - - m_replicaMock.reset(); - m_replicaManagerMock.reset(); - m_contextChunkMock.reset(); - - m_fakeAsset.reset(); - m_netBindingImpl->Shutdown(); - m_netBindingImpl.reset(); - - ReplicaChunkDescriptorTable::Get().UnregisterReplicaChunkDescriptor(ReplicaChunkClassId(MockNetBindingSystemContextData::GetChunkName())); - - m_netBindingSystemComponentDescriptor->ReleaseDescriptor(); - - m_componentApplication.reset(); - m_gameEntityMock.reset(); - - AllocatorInstance::Destroy(); - AllocatorInstance::Destroy(); - - m_applicationContext.reset(); - } - }; - - TEST_F(NetBindingWithSlicesTest, SameSliceInstanceId_InstantiateDynamicSlice_CallOnce) - { - using namespace testing; - - EXPECT_CALL(*m_gameEntityMock, InstantiateDynamicSlice(_, _, _)) - .Times(1); - EXPECT_CALL(*m_gameEntityMock, CancelDynamicSliceInstantiation(_)) - .Times(1); - - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; // both mock entities come from the same slice - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_Two; - spawnContext.m_staticEntityId = k_fakeEntityId_Two; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; // both mock entities come from the same slice - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_Two, spawnContext); - } - - // this should kick off NetBindingSystemImpl::ProcessBindRequests - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - } - - TEST_F(NetBindingWithSlicesTest, DifferentSliceInstanceId_InstantiateDynamicSlice_CalledTwice) - { - using namespace testing; - - EXPECT_CALL(*m_gameEntityMock, InstantiateDynamicSlice(_, _, _)) - .Times(2); - EXPECT_CALL(*m_gameEntityMock, CancelDynamicSliceInstantiation(_)) - .Times(2); - - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_Two; - spawnContext.m_staticEntityId = k_fakeEntityId_Two; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId_Another; // different slice entity - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_Two, spawnContext); - } - - // this should kick off NetBindingSystemImpl::ProcessBindRequests - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - } - - TEST_F(NetBindingWithSlicesTest, AssetManagerDestroyed_InstantiateDynamicSlice_NotCalled) - { - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; // both mock entities come from the same slice - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - - Data::AssetManager::Destroy(); - - // this should kick off NetBindingSystemImpl::ProcessBindRequests, but InstantiateDynamicSlice will not be called - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - } - - class ExtendedBindingWithSlicesTest - : public NetBindingWithSlicesTest - { - public: - void SetUp() override - { - NetBindingWithSlicesTest::SetUp(); - } - - void TearDown() override - { - using namespace testing; - - EXPECT_CALL(*m_gameEntityMock, DestroyGameEntity(k_fakeEntityId_One)) - .Times(AtMost(1)); - EXPECT_CALL(*m_gameEntityMock, DestroyGameEntity(k_fakeEntityId_Two)) - .Times(AtMost(1)); - - NetBindingWithSlicesTest::TearDown(); - } - - class InstantiateMockSlice - { - public: - explicit InstantiateMockSlice(ExtendedBindingWithSlicesTest* parent) - { - using namespace testing; - - m_mockSliceRef = AZStd::make_unique(); - m_mockSliceInstance = AZStd::make_unique(); - - // container owns the entities and will delete them - auto mockContainer = AZStd::make_unique(); - - auto binding1 = AZStd::make_unique>(); - mockContainer->m_entities.push_back(CreateMockEntity(parent->k_fakeEntityId_One, binding1.release())); - - auto binding2 = AZStd::make_unique>(); - mockContainer->m_entities.push_back(CreateMockEntity(parent->k_fakeEntityId_Two, binding2.release())); - - m_mockSliceInstance->SetMockInstantiatedContainer(mockContainer.release()); - - SliceComponent::SliceInstanceAddress sliceInstanceAddress(m_mockSliceRef.get(), m_mockSliceInstance.get()); - - // This will pass our mock slice to NetBindingSystem - EBUS_EVENT_ID(parent->m_sliceTicket, SliceInstantiationResultBus, OnSlicePreInstantiate, parent->k_fakeAssetId, sliceInstanceAddress); - EBUS_EVENT_ID(parent->m_sliceTicket, SliceInstantiationResultBus, OnSliceInstantiated, parent->k_fakeAssetId, sliceInstanceAddress); - } - - Entity* CreateMockEntity(const EntityId& id, Component* optional = nullptr) - { - using namespace testing; - - auto mock = AZStd::make_unique>(); - mock->SetId(EntityId(id)); - if (optional) - { - mock->AddComponent(optional); // entity owns the component - } - ON_CALL(*mock, Init()) - .WillByDefault(Invoke(mock.get(), &MockEntity::Base_Init)); - mock->Init(); - - ON_CALL(*mock, Activate()) - .WillByDefault(Invoke(mock.get(), &MockEntity::Base_Activate)); - - ON_CALL(*mock, Deactivate()) - .WillByDefault(Invoke(mock.get(), &MockEntity::Base_Deactivate)); - - return mock.release(); - } - - AZStd::unique_ptr m_mockSliceRef; - AZStd::unique_ptr m_mockSliceInstance; - }; - - AZStd::unique_ptr m_slice; - - void CreateMockSlice() - { - m_slice = AZStd::make_unique(this); - } - }; - - TEST_F(ExtendedBindingWithSlicesTest, ActiveSlice_EntitiesThatWerentBounded_StayDeactivated) - { - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - CreateMockSlice(); - - MockEntity* mock1 = static_cast(m_componentApplication->FindEntity(k_fakeEntityId_One)); - EXPECT_CALL(*mock1, Activate()). - Times(1); - - MockEntity* mock2 = static_cast(m_componentApplication->FindEntity(k_fakeEntityId_Two)); - EXPECT_CALL(*mock2, Activate()). - Times(0); - - EXPECT_CALL(*m_gameEntityMock, DestroyGameEntity(k_fakeEntityId_Two)) - .Times(0); - - // Now it should time out the slice handler and the second entity should remain deactivated since we didn't give binding request for it - EBUS_EVENT(AZ::TickBus, OnTick, k_wayOverSliceTimeout, AZ::ScriptTimePoint()); - - } - - TEST_F(ExtendedBindingWithSlicesTest, ActiveSlice_SpawnSecondEntity_AfterLongDelay_InSameSlicenInstance) - { - EXPECT_CALL(*m_gameEntityMock, DestroyGameEntity(k_fakeEntityId_Two)) - .Times(0); - - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - CreateMockSlice(); - - MockEntity* mock2 = static_cast(m_componentApplication->FindEntity(k_fakeEntityId_Two)); - EXPECT_CALL(*mock2, Activate()). - Times(0); - - // This should not trigger removal of the second entity yet - auto halfTimeoutInSeconds = AZStd::chrono::seconds(NetBindingSystemImpl::s_sliceBindingTimeout).count() * 10.f; - EBUS_EVENT(AZ::TickBus, OnTick, halfTimeoutInSeconds, AZ::ScriptTimePoint()); - - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_Two; - spawnContext.m_staticEntityId = k_fakeEntityId_Two; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; // both mock entities come from the same slice - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_Two, spawnContext); - } - - EXPECT_CALL(*mock2, Activate()). - Times(1); - - // This should give net binding system time to bind the second entity - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - - // Let the slice timeout, this should lead to no destruction since both entities ought to have been bound by now - EBUS_EVENT(AZ::TickBus, OnTick, k_wayOverSliceTimeout, AZ::ScriptTimePoint()); - } - - TEST_F(ExtendedBindingWithSlicesTest, ActiveSlice_DespawnLastEntity_DespawnWholeSliceAfterTimeout) - { - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - CreateMockSlice(); - - MockEntity* mock1 = static_cast(m_componentApplication->FindEntity(k_fakeEntityId_One)); - EXPECT_CALL(*mock1, Activate()). - Times(1); - - // This should not trigger removal of the second entity yet - auto halfTimeoutInSeconds = AZStd::chrono::seconds(NetBindingSystemImpl::s_sliceBindingTimeout).count() * 10.f; - EBUS_EVENT(AZ::TickBus, OnTick, halfTimeoutInSeconds, AZ::ScriptTimePoint()); - - EXPECT_CALL(*mock1, Deactivate()). - Times(1); - EBUS_EVENT(NetBindingSystemBus, UnbindGameEntity, k_fakeEntityId_One, k_fakeSliceInstanceId); - - EXPECT_CALL(*m_gameEntityMock, DestroyGameEntity(k_fakeEntityId_One)) - .Times(1); - EXPECT_CALL(*m_gameEntityMock, DestroyGameEntity(k_fakeEntityId_Two)) - .Times(1); - - EBUS_EVENT(AZ::TickBus, OnTick, k_wayOverSliceTimeout, AZ::ScriptTimePoint()); - } - - TEST_F(ExtendedBindingWithSlicesTest, ActiveSlice_DespawnLastEntityBeforeSliceInstantiation_DespawnWholeSlice) - { - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - - EBUS_EVENT(NetBindingSystemBus, UnbindGameEntity, k_fakeEntityId_One, k_fakeSliceInstanceId); - - CreateMockSlice(); - - MockEntity* mock1 = static_cast(m_componentApplication->FindEntity(k_fakeEntityId_One)); - EXPECT_CALL(*mock1, Activate()). - Times(0); - - auto halfTimeoutInSeconds = AZStd::chrono::seconds(NetBindingSystemImpl::s_sliceBindingTimeout).count() * 10.f; - EBUS_EVENT(AZ::TickBus, OnTick, halfTimeoutInSeconds, AZ::ScriptTimePoint()); - - EBUS_EVENT(AZ::TickBus, OnTick, k_wayOverSliceTimeout, AZ::ScriptTimePoint()); - } - - TEST_F(ExtendedBindingWithSlicesTest, ActiveSlice_ReuseEntity) - { - EXPECT_CALL(*m_gameEntityMock, DestroyGameEntity(k_fakeEntityId_Two)) - .Times(0); - - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_Two; - spawnContext.m_staticEntityId = k_fakeEntityId_Two; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; // both mock entities come from the same slice - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_Two, spawnContext); - } - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - CreateMockSlice(); - - MockEntity* mock2 = static_cast(m_componentApplication->FindEntity(k_fakeEntityId_Two)); - EXPECT_CALL(*mock2, Activate()). - Times(1); - - EBUS_EVENT(AZ::TickBus, OnTick, k_wayOverSliceTimeout, AZ::ScriptTimePoint()); - - EXPECT_CALL(*mock2, Deactivate()). - Times(1); - - // some time later the second entity goes away and comes back - EBUS_EVENT(NetBindingSystemBus, UnbindGameEntity, k_fakeEntityId_Two, k_fakeSliceInstanceId); - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_Two; - spawnContext.m_staticEntityId = k_fakeEntityId_Two; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; // both mock entities come from the same slice - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_Two, spawnContext); - } - - // The same entity should be activated for the second time - EXPECT_CALL(*mock2, Activate()). - Times(1); // Note, Google Mock treats each expect_call separately and satisfies them separately. That's why it's 1 here, despite being a second call. - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - } - - TEST_F(ExtendedBindingWithSlicesTest, SliceFailedToSpawn) - { - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - - EBUS_EVENT_ID(m_sliceTicket, SliceInstantiationResultBus, OnSliceInstantiationFailed, k_fakeAssetId); - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - - EXPECT_TRUE(m_componentApplication->FindEntity(k_fakeEntityId_One) == nullptr); - } - - TEST_F(ExtendedBindingWithSlicesTest, SliceSpawned_AfterTimeout) - { - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - EBUS_EVENT(AZ::TickBus, OnTick, k_wayOverSliceTimeout, AZ::ScriptTimePoint()); - - CreateMockSlice(); - - MockEntity* mock1 = static_cast(m_componentApplication->FindEntity(k_fakeEntityId_One)); - EXPECT_CALL(*mock1, Activate()). - Times(1); - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - } -} diff --git a/Code/Framework/Tests/NetworkContext.cpp b/Code/Framework/Tests/NetworkContext.cpp deleted file mode 100644 index 5af9ca70d8..0000000000 --- a/Code/Framework/Tests/NetworkContext.cpp +++ /dev/null @@ -1,801 +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 -#include -#include -#include -#include -#include - -namespace UnitTest -{ - using namespace AZ; - using namespace AzFramework; - - class TestComponentExternalChunk - : public AZ::Component - , public NetBindable - { - public: - AZ_COMPONENT(TestComponentExternalChunk, "{73BB3B15-7C4D-4BD5-9568-F3B2DCBC7725}", AZ::Component); - - static void Reflect(ReflectContext* context); - - void Init() override - { - NetBindable::NetInit(); - } - - void Activate() override {} - void Deactivate() override {} - - bool SetPos(float x, float y, const RpcContext&) - { - m_x = x; - m_y = y; - return true; - } - - void OnFloatChanged(const float&, const TimeContext&) - { - m_floatChanged = true; - } - - bool m_floatChanged = false; - private: - float m_x = 0, m_y = 0; - }; - - class TestComponentReplicaChunk - : public ReplicaChunkBase - , public ReplicaChunkInterface - { - public: - GM_CLASS_ALLOCATOR(TestComponentReplicaChunk); - static const char* GetChunkName() { return "TestComponentReplicaChunk"; } - bool IsReplicaMigratable() override { return true; } - - public: - TestComponentReplicaChunk() - : m_int("m_int", 42) - , m_float("m_float", 96.4f) - , SetInt("SetInt") - , SetPos("SetPos") - { - } - - bool SetIntImpl(int newValue, const RpcContext&) - { - m_int.Set(newValue); - return true; - } - - DataSet m_int; - DataSet::BindInterface m_float; - GridMate::Rpc > >::BindInterface SetInt; - GridMate::Rpc, GridMate::RpcArg >::BindInterface SetPos; - }; - - void TestComponentExternalChunk::Reflect(ReflectContext* context) - { - NetworkContext* netContext = azrtti_cast(context); - if (netContext) - { - netContext->Class() - ->Chunk() - ->Field("m_int", &TestComponentReplicaChunk::m_int) - ->Field("m_float", &TestComponentReplicaChunk::m_float) - ->RPC("SetInt", &TestComponentReplicaChunk::SetInt) - ->RPC("SetPos", &TestComponentReplicaChunk::SetPos); - } - } - - class TestComponentAutoChunk - : public AZ::Component - , public NetBindable - { - public: - enum TestEnum - { - TEST_Value0 = 0, - TEST_Value1 = 1, - TEST_Value255 = 255 - }; - - AZ_COMPONENT(TestComponentAutoChunk, "{003FD1BC-8456-43D5-9879-1B3804327A4F}", AZ::Component); - - static void Reflect(ReflectContext* context) - { - NetworkContext* netContext = azrtti_cast(context); - if (netContext) - { - netContext->Class() - ->Field("m_int", &TestComponentAutoChunk::m_int) - ->Field("m_float", &TestComponentAutoChunk::m_float) - ->Field("m_enum", &TestComponentAutoChunk::m_enum) - ->RPC("SetInt", &TestComponentAutoChunk::SetInt) - ->CtorData("CtorInt", &TestComponentAutoChunk::GetCtorInt, &TestComponentAutoChunk::SetCtorInt) - ->CtorData("CtorVec", &TestComponentAutoChunk::GetCtorVec, &TestComponentAutoChunk::SetCtorVec); - } - SerializeContext* serializeContext = azrtti_cast(context); - if (serializeContext) - { - serializeContext->Class() - ->Version(1) - ->Field("m_int", &TestComponentAutoChunk::m_int) - ->Field("m_float", &TestComponentAutoChunk::m_float) - ->Field("m_enum", &TestComponentAutoChunk::m_enum) - ->Field("ctorInt", &TestComponentAutoChunk::m_ctorInt) - ->Field("ctorVec", &TestComponentAutoChunk::m_ctorVec); - } - } - - void Init() override - { - NetBindable::NetInit(); - } - - void Activate() override {} - void Deactivate() override {} - - void SetNetworkBinding(ReplicaChunkPtr chunk) override {} - void UnbindFromNetwork() override {} - - bool SetIntImpl(int val, const RpcContext&) - { - m_int = val; - return true; - } - - void OnFloatChanged(const float&, const TimeContext&) - { - } - - int GetCtorInt() const { return m_ctorInt; } - void SetCtorInt(const int& ctorInt) { m_ctorInt = ctorInt; } - - AZStd::vector& GetCtorVec() { return m_ctorVec; } - void SetCtorVec(const AZStd::vector& vec) { m_ctorVec = vec; } - - int m_ctorInt; - AZStd::vector m_ctorVec; - Field m_int; - BoundField m_float; - Field > m_enum; - Rpc::Binder SetInt; - }; - - class NetContextReflectionTest - : public AllocatorsTestFixture - { - public: - void SetUp() override - { - AllocatorsTestFixture::SetUp(); - - AZ::AllocatorInstance::Create(); - } - - void TearDown() override - { - AZ::AllocatorInstance::Destroy(); - - AllocatorsTestFixture::TearDown(); - } - - void run() - { - AzFramework::Application app; - AzFramework::Application::Descriptor appDesc; - appDesc.m_recordingMode = Debug::AllocationRecords::RECORD_NO_RECORDS; - appDesc.m_allocationRecords = false; - appDesc.m_enableDrilling = false; - - app.Start(appDesc); - - // Without this, the user settings component would attempt to save on finalize/shutdown. Since the file is - // shared across the whole engine, if multiple tests are run in parallel, the saving could cause a crash - // in the unit tests. - AZ::UserSettingsComponentRequestBus::Broadcast(&AZ::UserSettingsComponentRequests::DisableSaveOnFinalize); - - AzFramework::NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - AZ_TEST_ASSERT(netContext); - - AZ::ComponentDescriptor* descTestComponentExternalChunk = TestComponentExternalChunk::CreateDescriptor(); - app.RegisterComponentDescriptor(descTestComponentExternalChunk); - - AZ::ComponentDescriptor* descTestComponentAutoChunk = TestComponentAutoChunk::CreateDescriptor(); - app.RegisterComponentDescriptor(descTestComponentAutoChunk); - - AZ::Entity* testEntity = aznew AZ::Entity("TestEntity"); - testEntity->Init(); - testEntity->CreateComponent(); - testEntity->CreateComponent(); - testEntity->Activate(); - - // test field binding/auto reflection/creation - { - TestComponentAutoChunk* testComponent = testEntity->FindComponent(); - AZ_TEST_ASSERT(testComponent); - - testComponent->SetInt(2048); // should happen locally - AZ_TEST_ASSERT(testComponent->m_int == 2048); - - ReplicaChunkPtr chunk = testComponent->GetNetworkBinding(); - AZ_TEST_ASSERT(chunk); - - GridMate::ReplicaChunkDescriptor* desc = chunk->GetDescriptor(); - AZ_TEST_ASSERT(desc); - - testComponent->m_ctorInt = 8192; - for (int n = 0; n < 16; ++n) - { - testComponent->m_ctorVec.push_back(n); - } - - GridMate::WriteBufferDynamic wb(GridMate::EndianType::IgnoreEndian); - desc->MarshalCtorData(chunk.get(), wb); - - { - // Create a chunk from the recorded ctor data, ensure that it stores - // the ctor data in preparation for copying it to the instance - GridMate::TimeContext tc; - GridMate::ReplicaContext rc(nullptr, tc); - GridMate::ReadBuffer rb(wb.GetEndianType(), wb.Get(), wb.Size()); - GridMate::UnmarshalContext ctx(rc); - ctx.m_hasCtorData = true; - ctx.m_iBuf = &rb; - ReplicaChunkPtr chunk2 = desc->CreateFromStream(ctx); - AZ_TEST_ASSERT(chunk2); // ensure a new chunk was created - ReflectedReplicaChunkBase* refChunk = static_cast(chunk2.get()); - AZ_TEST_ASSERT(refChunk->m_ctorBuffer.Size() == sizeof(int) + sizeof(AZ::u16) + (sizeof(int) * testComponent->m_ctorVec.size())); - } - - { - // discard a ctor data stream and ensure that the stream is emptied - GridMate::TimeContext tc; - GridMate::ReplicaContext rc(nullptr, tc); - GridMate::ReadBuffer rb(wb.GetEndianType(), wb.Get(), wb.Size()); - GridMate::UnmarshalContext ctx(rc); - ctx.m_hasCtorData = true; - ctx.m_iBuf = &rb; - desc->DiscardCtorStream(ctx); - AZ_TEST_ASSERT(rb.IsEmptyIgnoreTrailingBits()); // should have discarded the whole stream - } - - { - // Make another chunk and bind it to a new component and make sure the ctor data matches - AZ::Entity* testEntity2 = aznew AZ::Entity("TestEntity2"); - testEntity2->Init(); - testEntity2->CreateComponent(); - testEntity2->Activate(); - - GridMate::TimeContext tc; - GridMate::ReplicaContext rc(nullptr, tc); - GridMate::ReadBuffer rb(wb.GetEndianType(), wb.Get(), wb.Size()); - GridMate::UnmarshalContext ctx(rc); - ctx.m_hasCtorData = true; - ctx.m_iBuf = &rb; - ReplicaChunkPtr chunk2 = desc->CreateFromStream(ctx); - - TestComponentAutoChunk* testComponent2 = testEntity2->FindComponent(); - netContext->Bind(testComponent2, chunk2, NetworkContextBindMode::NonAuthoritative); - // Ensure values match after ctor data is applied - AZ_TEST_ASSERT(testComponent2->m_ctorInt == testComponent->m_ctorInt); - AZ_TEST_ASSERT(testComponent2->m_ctorVec == testComponent->m_ctorVec); - } - - testComponent->SetInt(4096); - AZ_TEST_ASSERT(testComponent->m_int == 4096); - - testComponent->m_int = 42; // now it should change - AZ_TEST_ASSERT(testComponent->m_int == 42); - testComponent->m_enum = TestComponentAutoChunk::TEST_Value1; - - chunk.reset(); // should cause netContext->DestroyReplicaChunk() - } - - // test chunk binding/creation - { - TestComponentExternalChunk* testComponent = testEntity->FindComponent(); - AZ_TEST_ASSERT(testComponent); - - ReplicaChunkPtr chunk = testComponent->GetNetworkBinding(); - AZ_TEST_ASSERT(chunk); - - TestComponentReplicaChunk* testChunk = static_cast(chunk.get()); - - // for now, this will throw a warning, but will at least attempt the dispatch - testChunk->SetPos(42.0f, 96.0f); - - AZ_TEST_ASSERT(testComponent->m_floatChanged == false); - testChunk->m_float.Set(1024.0f); - // I would like to test that the notify fired, but without a Replica, cant :( - - testComponent->UnbindFromNetwork(); - chunk.reset(); ///// CRASHES FROM HERE - } - - // test serialization of NetBindable::Fields - { - TestComponentAutoChunk* testComponent = testEntity->FindComponent(); - AZStd::vector buffer; - AZ::IO::ByteContainerStream > saveStream(&buffer); - bool saved = AZ::Utils::SaveObjectToStream(saveStream, AZ::DataStream::ST_XML, testComponent); - AZ_TEST_ASSERT(saved); - AZ::IO::ByteContainerStream > loadStream(&buffer); - TestComponentAutoChunk* testCopy = AZ::Utils::LoadObjectFromStream(loadStream); - AZ_TEST_ASSERT(testCopy); - delete testCopy; - } - - testEntity->Deactivate(); - delete testEntity; - - descTestComponentExternalChunk->ReleaseDescriptor(); - descTestComponentAutoChunk->ReleaseDescriptor(); - - app.Stop(); - } - }; - - TEST_F(NetContextReflectionTest, Test) - { - run(); - } - - template - class NetContextFixture - : public ::testing::Test - { - public: - NetContextFixture() = default; - ~NetContextFixture() = default; - - void SetUp() override - { - AZ::AllocatorInstance::Create(); - - m_app = AZStd::make_unique(); - m_app->Start(AzFramework::Application::Descriptor()); - - // Without this, the user settings component would attempt to save on finalize/shutdown. Since the file is - // shared across the whole engine, if multiple tests are run in parallel, the saving could cause a crash - // in the unit tests. - AZ::UserSettingsComponentRequestBus::Broadcast(&AZ::UserSettingsComponentRequests::DisableSaveOnFinalize); - - AzFramework::NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - AZ_TEST_ASSERT(netContext); - - m_descTestComponentAutoChunk = ComponentType::CreateDescriptor(); - m_app->RegisterComponentDescriptor(m_descTestComponentAutoChunk); - - m_entity = AZStd::make_unique("TestEntity"); - m_entity->Init(); - m_entity->CreateComponent(); - m_entity->Activate(); - } - - void TearDown() override - { - m_descTestComponentAutoChunk->ReleaseDescriptor(); - - m_entity->Deactivate(); - m_entity.reset(); - - m_app->Stop(); - m_app.reset(); - - AZ::AllocatorInstance::Destroy(); - } - - void RunTest() - { - const ComponentType* testComponent = m_entity->FindComponent(); - AZStd::vector buffer; - AZ::IO::ByteContainerStream > saveStream(&buffer); - const bool saved = AZ::Utils::SaveObjectToStream(saveStream, AZ::DataStream::ST_XML, testComponent); - AZ_TEST_ASSERT(saved); - AZ::IO::ByteContainerStream > loadStream(&buffer); - const AZStd::unique_ptr testCopy(AZ::Utils::LoadObjectFromStream(loadStream)); - AZ_TEST_ASSERT(testCopy); - } - - AZStd::unique_ptr m_app; - AZStd::unique_ptr m_entity; - AZ::ComponentDescriptor* m_descTestComponentAutoChunk = nullptr; - }; - - class TestComponent_EmptyNetContext - : public AZ::Component - , public NetBindable - { - public: - AZ_COMPONENT(TestComponent_EmptyNetContext, "{B1E2E2DD-DA70-4D59-A185-AF9A5CCF1574}", AZ::Component, NetBindable); - - static void Reflect(ReflectContext* context) - { - if (SerializeContext* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1); - } - if (NetworkContext* netContext = azrtti_cast(context)) - { - netContext->Class(); - } - } - - void Activate() override {} - void Deactivate() override {} - }; - - using NetContextEmpty = NetContextFixture; - TEST_F(NetContextEmpty, SerializationTests) - { - RunTest(); - } - - template - class TestComponent_OneField - : public AZ::Component - , public NetBindable - { - public: - AZ_COMPONENT(TestComponent_OneField, "{A7BCDBEF-3D4F-4D04-A6FA-DF48D4B66ABE}", AZ::Component, NetBindable); - - using ThisComponentType = TestComponent_OneField; - - static void Reflect(ReflectContext* context) - { - if (SerializeContext* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Field("Field", &TestComponent_OneField::m_field) - ->Version(1); - } - if (NetworkContext* netContext = azrtti_cast(context)) - { - netContext->Class() - ->Field("Field", &TestComponent_OneField::m_field); - } - } - - void Activate() override {} - void Deactivate() override {} - - Field m_field; - }; - - TYPED_TEST_CASE_P(NetContextFixture); - - TYPED_TEST_P(NetContextFixture, SerializationTests) - { - this->RunTest(); - } - - REGISTER_TYPED_TEST_CASE_P(NetContextFixture, SerializationTests); - - /* - * Testing the basic common types. - */ - using CommonTypes = ::testing::Types< - TestComponent_OneField, - TestComponent_OneField, - TestComponent_OneField, - TestComponent_OneField, - TestComponent_OneField, - TestComponent_OneField, - TestComponent_OneField - >; - - INSTANTIATE_TYPED_TEST_CASE_P(NetContextCommonSerialization, NetContextFixture, CommonTypes); - - /* - * And some less common types. - */ - using LessCommonTypes = ::testing::Types< - TestComponent_OneField, - TestComponent_OneField, - TestComponent_OneField, - TestComponent_OneField>, - TestComponent_OneField - >; - - INSTANTIATE_TYPED_TEST_CASE_P(NetContextLessCommonSerialization, NetContextFixture, LessCommonTypes); - - /* - * Next up are marshal and unmarshal tests. - */ - - template - class NetContextMarshalFixture - : public UnitTest::AllocatorsTestFixture - { - public: - NetContextMarshalFixture() = default; - ~NetContextMarshalFixture() = default; - - void SetUp() override - { - UnitTest::AllocatorsTestFixture::SetUp(); - - AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); - - m_app = AZStd::make_unique(); - m_app->Start(AzFramework::Application::Descriptor()); - - // Without this, the user settings component would attempt to save on finalize/shutdown. Since the file is - // shared across the whole engine, if multiple tests are run in parallel, the saving could cause a crash - // in the unit tests. - AZ::UserSettingsComponentRequestBus::Broadcast(&AZ::UserSettingsComponentRequests::DisableSaveOnFinalize); - - AzFramework::NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - AZ_TEST_ASSERT(netContext); - - m_descTestComponentAutoChunk = ComponentType::CreateDescriptor(); - m_app->RegisterComponentDescriptor(m_descTestComponentAutoChunk); - - m_entityFrom = AZStd::make_unique("TestEntityFrom"); - m_entityFrom->Init(); - m_componentFrom = m_entityFrom->CreateComponent(); - m_entityFrom->Activate(); - - m_entityTo = AZStd::make_unique("TestEntityTo"); - m_entityTo->Init(); - m_componentTo = m_entityTo->CreateComponent(); - m_entityTo->Activate(); - } - - void MarshalUnMarshal() - { - AzFramework::NetworkContext* netContext = nullptr; - NetSystemRequestBus::BroadcastResult(netContext, &NetSystemRequestBus::Events::GetNetworkContext); - AZ_TEST_ASSERT(netContext); - - ComponentType* testComponent = m_entityFrom->FindComponent(); - AZ_TEST_ASSERT(testComponent); - ReplicaChunkPtr chunk = testComponent->GetNetworkBinding(); - AZ_TEST_ASSERT(chunk); - - m_outReplica = AZStd::make_unique("ReplicaTo"); - { - m_outManager = AZStd::make_unique(); - m_outPeer = AZStd::make_unique(m_outManager.get()); - - GridMate::WriteBufferDynamic wb(GridMate::EndianType::IgnoreEndian); - { - GridMate::TimeContext tc; - const GridMate::ReplicaContext rc(nullptr, tc); - GridMate::MarshalContext mc(GridMate::ReplicaMarshalFlags::FullSync, &wb, nullptr, rc); - mc.m_peer = m_outPeer.get(); - mc.m_rm = m_outManager.get(); - chunk->Debug_PrepareData(wb.GetEndianType(), GridMate::ReplicaMarshalFlags::FullSync); - chunk->Debug_Marshal(mc, 0); - } - - // and now unmarshal into the other entity - { - GridMate::TimeContext tc; - const GridMate::ReplicaContext rc(nullptr, tc); - GridMate::ReadBuffer rb(wb.GetEndianType(), wb.Get(), wb.Size()); - GridMate::UnmarshalContext ctx(rc); - ctx.m_hasCtorData = false; - ctx.m_iBuf = &rb; - ctx.m_peer = m_outPeer.get(); - ctx.m_rm = m_outManager.get(); - m_outReplicaChunk = chunk->GetDescriptor()->CreateFromStream(ctx); - - m_outReplicaChunk->Debug_AttachedToReplica(m_outReplica.get()); - ctx.m_peer->Debug_Add(m_outReplica.get()); - m_outReplicaChunk->Debug_Unmarshal(ctx, 0); - /* - * Note the order: unmarshal first to populate the chunk with data, then apply it to a component. - * The expectation is that the valid will apply to NetBindable::Field without being overwritten. - */ - m_componentTo->SetNetworkBinding(m_outReplicaChunk); - - // the main test body can now test for the equality - } - } - } - - void TearDown() override - { - m_outReplicaChunk.reset(); - m_outManager.reset(); - m_outPeer.reset(); - m_outReplica.release(); // Replica is held by as an intrusive pointer in @m_outPeer and is destroyed there. - - if (m_entityFrom) - { - m_entityFrom->Deactivate(); - m_entityFrom.reset(); - } - - if (m_entityTo) - { - m_entityTo->Deactivate(); - m_entityTo.reset(); - } - - m_descTestComponentAutoChunk->ReleaseDescriptor(); - - m_app->Stop(); - m_app.reset(); - - AZ::AllocatorInstance::Destroy(); - AZ::AllocatorInstance::Destroy(); - - UnitTest::AllocatorsTestFixture::TearDown(); - } - - AZStd::unique_ptr m_app; - AZStd::unique_ptr m_entityFrom; - AZStd::unique_ptr m_entityTo; - - ComponentType* m_componentFrom = nullptr; - ComponentType* m_componentTo = nullptr; - - AZ::ComponentDescriptor* m_descTestComponentAutoChunk = nullptr; - - GridMate::ReplicaChunkPtr m_outReplicaChunk; - AZStd::unique_ptr m_outReplica; - AZStd::unique_ptr m_outManager; - AZStd::unique_ptr m_outPeer; - }; - - using NetContextVector3 = NetContextMarshalFixture>; - TEST_F(NetContextVector3, SerializationTests) - { - const Vector3 value = AZ::Vector3::CreateAxisZ( 1.f ); - - m_componentFrom->m_field = value; - MarshalUnMarshal(); - - AZ_TEST_ASSERT(m_componentTo->m_field.Get() == value); - } - - /* - * Now the same test but with NetBindable::BoundField<> - */ - - template - class TestComponent_OneBoundField - : public AZ::Component - , public NetBindable - { - public: - AZ_COMPONENT(TestComponent_OneBoundField, "{2B283821-41DF-46BB-BE8E-66EF7301B62A}", AZ::Component, NetBindable); - - using ThisComponentType = TestComponent_OneBoundField; - - static void Reflect(ReflectContext* context) - { - if (SerializeContext* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Field("Field", &ThisComponentType::m_boundField) - ->Version(1); - } - if (NetworkContext* netContext = azrtti_cast(context)) - { - netContext->Class() - ->Field("Field", &ThisComponentType::m_boundField); - } - } - - void Activate() override {} - void Deactivate() override {} - - void OnBoundFieldChanged( const FieldType&, const GridMate::TimeContext& ) {} - - BoundField m_boundField; - }; - - using NetContextBoundVector2 = NetContextMarshalFixture>; - TEST_F(NetContextBoundVector2, SerializationTests) - { - const Vector2 value = AZ::Vector2::CreateAxisX( 4.f ); - - m_componentFrom->m_boundField = value; - MarshalUnMarshal(); - - AZ_TEST_ASSERT(m_componentTo->m_boundField.Get() == value); - } - - TEST_F(NetContextBoundVector2, Delete_Authoritative_Entity) - { - using ThisComponentType = TestComponent_OneBoundField; - - AzFramework::NetworkContext* netContext = nullptr; - NetSystemRequestBus::BroadcastResult(netContext, &NetSystemRequestBus::Events::GetNetworkContext); - AZ_TEST_ASSERT(netContext); - ThisComponentType* testComponent = m_entityFrom->FindComponent(); - AZ_TEST_ASSERT(testComponent); - ReplicaChunkPtr chunk = testComponent->GetNetworkBinding(); - - // Testing early deletion of an entity on the server. - m_entityFrom->Deactivate(); - m_entityFrom.reset(); - - // This test passes if it doesn't crash on cleanup. - chunk.reset(); - } - - template - class TestComponent_OneBoundField_ServerCallback - : public AZ::Component - , public NetBindable - { - public: - AZ_COMPONENT(TestComponent_OneBoundField_ServerCallback, "{74F5B232-0544-45CA-B207-9846052ED1AD}", AZ::Component, NetBindable); - - using ThisComponentType = TestComponent_OneBoundField_ServerCallback; - - static void Reflect(ReflectContext* context) - { - if (SerializeContext* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Field("Field", &ThisComponentType::m_boundField) - ->Version(1); - } - if (NetworkContext* netContext = azrtti_cast(context)) - { - netContext->Class() - ->Field("Field", &ThisComponentType::m_boundField); - } - } - - void Activate() override {} - void Deactivate() override {} - - void OnBoundFieldChanged( const FieldType&, const GridMate::TimeContext& ) - { - ++m_callbacksInvokeCount; - } - - AZ::u8 m_callbacksInvokeCount = 0; - - BoundField m_boundField; - }; - - using NetContextBoundVector2WithCallbackCount = NetContextMarshalFixture>; - TEST_F(NetContextBoundVector2WithCallbackCount, BoundField_Invoke_OnServer_Test) - { - MarshalUnMarshal(); - - m_componentFrom->m_callbacksInvokeCount = 0; // resetting the count - - const Vector2 value = AZ::Vector2::CreateAxisX( 4.f ); - m_componentFrom->m_boundField = value; - - AZ_TEST_ASSERT(m_componentFrom->m_callbacksInvokeCount == 1); - } -} diff --git a/Code/Framework/Tests/NetworkMarshal.cpp b/Code/Framework/Tests/NetworkMarshal.cpp deleted file mode 100644 index e9c8b336f6..0000000000 --- a/Code/Framework/Tests/NetworkMarshal.cpp +++ /dev/null @@ -1,552 +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 "TestTypes.h" - -#include -#include -#include -#include - -#include - -namespace UnitTest -{ - template - class MarshalerTester - : public AllocatorsFixture - { - public: - MarshalerTester() - : m_writeBuffer(GridMate::EndianType::BigEndian) - , m_readBuffer(GridMate::EndianType::BigEndian) - { - } - - void SetUp() override - { - AllocatorsFixture::SetUp(); - m_random.SetSeed(AZStd::chrono::milliseconds().count()); - } - - void PopulateReadBuffer() - { - m_readBuffer = GridMate::ReadBuffer(m_writeBuffer.GetEndianType(), m_writeBuffer.Get(), m_writeBuffer.Size()); - } - - AZ::SimpleLcgRandom m_random; - - GridMate::Marshaler m_marshaler; - GridMate::WriteBufferStatic<> m_writeBuffer; - GridMate::ReadBuffer m_readBuffer; - }; - - // EntityIdMarshalerTest - typedef MarshalerTester EntityIdMarshalerTest; - - TEST_F(EntityIdMarshalerTest, SingleMarshalUnmarshalTest_EquivalentEmptyValue) - { - AZ::EntityId initialId; - m_marshaler.Marshal(m_writeBuffer, initialId); - - PopulateReadBuffer(); - - AZ::EntityId receivedId; - m_marshaler.Unmarshal(receivedId, m_readBuffer); - - EXPECT_EQ(initialId,receivedId); - EXPECT_FALSE(receivedId.IsValid()); - } - - TEST_F(EntityIdMarshalerTest, SingleMarshalUnmarshalTest_EquivalentRandomValue) - { - AZ::EntityId initialId = AZ::EntityId(m_random.GetRandom()); - m_marshaler.Marshal(m_writeBuffer, initialId); - - PopulateReadBuffer(); - - AZ::EntityId receivedId; - m_marshaler.Unmarshal(receivedId, m_readBuffer); - - EXPECT_EQ(initialId,receivedId); - } - - TEST_F(EntityIdMarshalerTest, MultipleMarshalUnmarshalTest_EquivalentEmptyRandomEmptyRandomValueChain) - { - AZ::EntityId sentId1_empty; - AZ::EntityId sentId2_random = AZ::EntityId(m_random.GetRandom()); - AZ::EntityId sentId3_empty; - AZ::EntityId sentId4_random = AZ::EntityId(m_random.GetRandom()); - - m_marshaler.Marshal(m_writeBuffer, sentId1_empty); - m_marshaler.Marshal(m_writeBuffer, sentId2_random); - m_marshaler.Marshal(m_writeBuffer, sentId3_empty); - m_marshaler.Marshal(m_writeBuffer, sentId4_random); - - PopulateReadBuffer(); - - AZ::EntityId receivedId1_empty; - AZ::EntityId receivedId2_random; - AZ::EntityId receivedId3_empty; - AZ::EntityId receivedId4_random; - - m_marshaler.Unmarshal(receivedId1_empty, m_readBuffer); - m_marshaler.Unmarshal(receivedId2_random, m_readBuffer); - m_marshaler.Unmarshal(receivedId3_empty, m_readBuffer); - m_marshaler.Unmarshal(receivedId4_random, m_readBuffer); - - EXPECT_EQ(sentId1_empty, receivedId1_empty); - EXPECT_EQ(sentId2_random, receivedId2_random); - EXPECT_EQ(sentId3_empty, receivedId3_empty); - EXPECT_EQ(sentId4_random, receivedId4_random); - } - - // AZ::DynamicSerializableFieldMarshaler - class FooSerializable - { - public: - AZ_RTTI(FooSerializable, "{A60F0B2B-6085-4FF1-BD17-A0B0143BB03D}"); - AZ_CLASS_ALLOCATOR(FooSerializable, AZ::SystemAllocator,0); - - static void Reflect(AZ::SerializeContext& serializeContext) - { - serializeContext.Class() - ->Version(1) - ->Field("IntValue", &FooSerializable::m_intValue) - ->Field("FloatValue", &FooSerializable::m_floatValue) - ; - } - - FooSerializable() - : m_intValue(0) - , m_floatValue(0.0f) - { - } - - bool operator==(const FooSerializable& other) const - { - return m_intValue == other.m_intValue && AZ::IsClose(m_floatValue, other.m_floatValue,0.0001f); - } - - AZ::u32 m_intValue; - float m_floatValue; - }; - - class BarSerializable - { - public: - AZ_RTTI(BarSerializable, "{2389C23F-D247-420B-A385-71AB8455CD2E}"); - AZ_CLASS_ALLOCATOR(BarSerializable, AZ::SystemAllocator,0); - - static void Reflect(AZ::SerializeContext& serializeContext) - { - serializeContext.Class() - ->Version(1) - ->Field("LongValue", &BarSerializable::m_longValue) - ->Field("DoubleValue", &BarSerializable::m_doubleValue) - ; - } - - BarSerializable() - : m_longValue(0) - , m_doubleValue(0.0) - { - } - - bool operator==(const BarSerializable& other) const - { - return m_longValue == other.m_longValue && AZ::IsClose(m_doubleValue,other.m_doubleValue,0.0001); - } - - long m_longValue; - double m_doubleValue; - }; - - class ComplexSerializable - { - public: - AZ_RTTI(ComplexSerializable,"{055CB45C-702C-499F-8221-E9ABB21CF1D4}"); - AZ_CLASS_ALLOCATOR(ComplexSerializable, AZ::SystemAllocator,0); - - static void Reflect(AZ::SerializeContext& serializeContext) - { - serializeContext.Class() - ->Version(1) - ->Field("FooSerializable",&ComplexSerializable::m_fooField) - ->Field("BarSerializable",&ComplexSerializable::m_barField) - ; - } - - bool operator==(const ComplexSerializable& other) const - { - return m_fooField == other.m_fooField && m_barField == other.m_barField; - } - - FooSerializable m_fooField; - BarSerializable m_barField; - }; - - class DynamicSerializableFieldMarshalerTest - : public MarshalerTester - , public AZ::ComponentApplicationBus::Handler - { - public: - DynamicSerializableFieldMarshalerTest() - : MarshalerTester() - { - } - - void SetUp() override - { - MarshalerTester::SetUp(); - - FooSerializable::Reflect(m_serializeContext); - BarSerializable::Reflect(m_serializeContext); - ComplexSerializable::Reflect(m_serializeContext); - - // Create the Marshaler with access to our custom serialize context. - m_marshaler = GridMate::Marshaler(&m_serializeContext); - - AZ::ComponentApplicationBus::Handler::BusConnect(); - } - - void TearDown() override - { - MarshalerTester::TearDown(); - - AZ::ComponentApplicationBus::Handler::BusDisconnect(); - } - - FooSerializable* GenerateFooSerializable() - { - FooSerializable* field = new FooSerializable(); - - RandomizeFooSerializable((*field)); - - return field; - } - - void RandomizeFooSerializable(FooSerializable& serializable) - { - serializable.m_intValue = m_random.GetRandom(); - serializable.m_floatValue = m_random.GetRandomFloat(); - } - - BarSerializable* GenerateBarSerializable() - { - BarSerializable* field = new BarSerializable(); - - return field; - } - - void RandomizeBarSerializable(BarSerializable& serializable) - { - serializable.m_longValue = static_cast(m_random.GetRandom()); - serializable.m_doubleValue = static_cast(m_random.GetRandomFloat()); - } - - ComplexSerializable* GenerateComplexSerializable() - { - ComplexSerializable* complexField = new ComplexSerializable(); - - RandomizeFooSerializable(complexField->m_fooField); - RandomizeBarSerializable(complexField->m_barField); - - return complexField; - } - - // Used Component Application Methods - AZ::SerializeContext* GetSerializeContext() { return &m_serializeContext; } - - // Unused ComponentApplication methods - void RegisterComponentDescriptor(const AZ::ComponentDescriptor* descriptor) override { (void)descriptor; AZ_Assert(false,"Unsupported method in Unit Test"); } - void UnregisterComponentDescriptor(const AZ::ComponentDescriptor* descriptor) override { (void)descriptor; AZ_Assert(false,"Unsupported method in Unit Test"); } - - AZ::ComponentApplication* GetApplication() override { AZ_Assert(false,"Unsupported method in Unit Test"); return nullptr; } - bool AddEntity(AZ::Entity* entity) override { (void)entity; AZ_Assert(false,"Unsupported method in Unit Test"); return false; } - bool RemoveEntity(AZ::Entity* entity) override { (void)entity; AZ_Assert(false,"Unsupported method in Unit Test"); return false; } - bool DeleteEntity(const AZ::EntityId& id) override { (void)id; AZ_Assert(false,"Unsupported method in Unit Test"); return false; } - AZ::Entity* FindEntity(const AZ::EntityId& id) override { (void)id; AZ_Assert(false,"Unsupported method in Unit Test"); return nullptr; } - void EnumerateEntities(const EntityCallback& callback) override { (void)callback; AZ_Assert(false,"Unsupported method in Unit Test"); } - AZ::BehaviorContext* GetBehaviorContext() override { AZ_Assert(false,"Unsupported method in Unit Test"); return nullptr; } - const char* GetAppRoot() override { AZ_Assert(false,"Unsupported method in Unit Test"); return nullptr; } - const char* GetExecutableFolder() override { AZ_Assert(false,"Unsupported method in Unit Test"); return nullptr; } - AZ::Debug::DrillerManager* GetDrillerManager() override { AZ_Assert(false,"Unsupported method in Unit Test"); return nullptr; } - void ReloadModule(const char* moduleFullPath) override { (void)moduleFullPath; AZ_Assert(false,"Unsupported method in Unit Test"); } - - AZ::SerializeContext m_serializeContext; - }; - - TEST_F(DynamicSerializableFieldMarshalerTest, SingleMarshalUnmarshalTest_EquivalentEmptyValue) - { - AZ::DynamicSerializableField sentField; - m_marshaler.Marshal(m_writeBuffer, sentField); - - PopulateReadBuffer(); - - AZ::DynamicSerializableField receivedField; - m_marshaler.Unmarshal(receivedField,m_readBuffer); - - EXPECT_TRUE(sentField.IsEqualTo(receivedField, &m_serializeContext)); - } - - TEST_F(DynamicSerializableFieldMarshalerTest, SingleMarshalUnmarshalTest_EquivalentFooValue) - { - AZ::DynamicSerializableField sentField; - - FooSerializable* fooSerializable = GenerateFooSerializable(); - sentField.Set(fooSerializable); - - m_marshaler.Marshal(m_writeBuffer, sentField); - - PopulateReadBuffer(); - - AZ::DynamicSerializableField receivedField; - m_marshaler.Unmarshal(receivedField,m_readBuffer); - - EXPECT_TRUE(sentField.IsEqualTo(receivedField, &m_serializeContext)); - - sentField.DestroyData(&m_serializeContext); - receivedField.DestroyData(&m_serializeContext); - } - - TEST_F(DynamicSerializableFieldMarshalerTest, SingleMarshalUnmarshalTest_EquivalentBarValue) - { - AZ::DynamicSerializableField sentField; - - BarSerializable* barSerializable = GenerateBarSerializable(); - sentField.Set(barSerializable); - - m_marshaler.Marshal(m_writeBuffer, sentField); - - PopulateReadBuffer(); - - AZ::DynamicSerializableField receivedField; - m_marshaler.Unmarshal(receivedField,m_readBuffer); - - EXPECT_TRUE(sentField.IsEqualTo(receivedField, &m_serializeContext)); - - sentField.DestroyData(&m_serializeContext); - receivedField.DestroyData(&m_serializeContext); - } - - TEST_F(DynamicSerializableFieldMarshalerTest, SingleMarshalUnmarshalTest_EquivalentComplexValue) - { - AZ::DynamicSerializableField sentField; - - ComplexSerializable* complexSerializable = GenerateComplexSerializable(); - sentField.Set(complexSerializable); - - m_marshaler.Marshal(m_writeBuffer, sentField); - - PopulateReadBuffer(); - - AZ::DynamicSerializableField receivedField; - m_marshaler.Unmarshal(receivedField,m_readBuffer); - - EXPECT_TRUE(sentField.IsEqualTo(receivedField, &m_serializeContext)); - - sentField.DestroyData(&m_serializeContext); - receivedField.DestroyData(&m_serializeContext); - } - - TEST_F(DynamicSerializableFieldMarshalerTest, MultipleMarshalUnmarshalTest_EmptyEmptyChainEquivalentValue) - { - AZ::DynamicSerializableField sentField1; - AZ::DynamicSerializableField sentField2; - - m_marshaler.Marshal(m_writeBuffer, sentField1); - m_marshaler.Marshal(m_writeBuffer, sentField2); - - PopulateReadBuffer(); - - AZ::DynamicSerializableField receivedField1; - AZ::DynamicSerializableField receivedField2; - - m_marshaler.Unmarshal(receivedField1,m_readBuffer); - m_marshaler.Unmarshal(receivedField2,m_readBuffer); - - EXPECT_TRUE(sentField1.IsEqualTo(receivedField1, &m_serializeContext)); - EXPECT_TRUE(sentField2.IsEqualTo(receivedField2, &m_serializeContext)); - - sentField1.DestroyData(&m_serializeContext); - sentField2.DestroyData(&m_serializeContext); - receivedField1.DestroyData(&m_serializeContext); - receivedField2.DestroyData(&m_serializeContext); - } - - TEST_F(DynamicSerializableFieldMarshalerTest, MultipleMarshalUnmarshalTest_FooBarComplexChainEquivalentValue) - { - AZ::DynamicSerializableField sentField1; - FooSerializable* fooSerializable = GenerateFooSerializable(); - sentField1.Set(fooSerializable); - - AZ::DynamicSerializableField sentField2; - BarSerializable* barSerializable = GenerateBarSerializable(); - sentField2.Set(barSerializable); - - AZ::DynamicSerializableField sentField3; - ComplexSerializable* complexSerializable = GenerateComplexSerializable(); - sentField3.Set(complexSerializable); - - m_marshaler.Marshal(m_writeBuffer, sentField1); - m_marshaler.Marshal(m_writeBuffer, sentField2); - m_marshaler.Marshal(m_writeBuffer, sentField3); - - PopulateReadBuffer(); - - AZ::DynamicSerializableField receivedField1; - AZ::DynamicSerializableField receivedField2; - AZ::DynamicSerializableField receivedField3; - - m_marshaler.Unmarshal(receivedField1, m_readBuffer); - m_marshaler.Unmarshal(receivedField2, m_readBuffer); - m_marshaler.Unmarshal(receivedField3, m_readBuffer); - - EXPECT_TRUE(sentField1.IsEqualTo(receivedField1, &m_serializeContext)); - EXPECT_TRUE(sentField2.IsEqualTo(receivedField2, &m_serializeContext)); - EXPECT_TRUE(sentField3.IsEqualTo(receivedField3, &m_serializeContext)); - - sentField1.DestroyData(&m_serializeContext); - sentField2.DestroyData(&m_serializeContext); - sentField3.DestroyData(&m_serializeContext); - - receivedField1.DestroyData(&m_serializeContext); - receivedField2.DestroyData(&m_serializeContext); - receivedField3.DestroyData(&m_serializeContext); - } - - TEST_F(DynamicSerializableFieldMarshalerTest, MultipleMarshalUnmarshalTest_EmptyFooEmptyBarEmptyComplexChainEquivalentValue) - { - AZ::DynamicSerializableField emptyField; - - AZ::DynamicSerializableField sentField1; - FooSerializable* fooSerializable = GenerateFooSerializable(); - sentField1.Set(fooSerializable); - - AZ::DynamicSerializableField sentField2; - BarSerializable* barSerializable = GenerateBarSerializable(); - sentField2.Set(barSerializable); - - AZ::DynamicSerializableField sentField3; - ComplexSerializable* complexSerializable = GenerateComplexSerializable(); - sentField3.Set(complexSerializable); - - m_marshaler.Marshal(m_writeBuffer, emptyField); - m_marshaler.Marshal(m_writeBuffer, sentField1); - m_marshaler.Marshal(m_writeBuffer, emptyField); - m_marshaler.Marshal(m_writeBuffer, sentField2); - m_marshaler.Marshal(m_writeBuffer, emptyField); - m_marshaler.Marshal(m_writeBuffer, sentField3); - m_marshaler.Marshal(m_writeBuffer, emptyField); - - PopulateReadBuffer(); - - AZ::DynamicSerializableField receivedEmptyField1; - AZ::DynamicSerializableField receivedField1; - AZ::DynamicSerializableField receivedEmptyField2; - AZ::DynamicSerializableField receivedField2; - AZ::DynamicSerializableField receivedEmptyField3; - AZ::DynamicSerializableField receivedField3; - AZ::DynamicSerializableField receivedEmptyField4; - - m_marshaler.Unmarshal(receivedEmptyField1, m_readBuffer); - m_marshaler.Unmarshal(receivedField1, m_readBuffer); - m_marshaler.Unmarshal(receivedEmptyField2, m_readBuffer); - m_marshaler.Unmarshal(receivedField2, m_readBuffer); - m_marshaler.Unmarshal(receivedEmptyField3, m_readBuffer); - m_marshaler.Unmarshal(receivedField3, m_readBuffer); - m_marshaler.Unmarshal(receivedEmptyField4, m_readBuffer); - - EXPECT_TRUE(emptyField.IsEqualTo(receivedEmptyField1, &m_serializeContext)); - EXPECT_TRUE(sentField1.IsEqualTo(receivedField1, &m_serializeContext)); - EXPECT_TRUE(emptyField.IsEqualTo(receivedEmptyField2, &m_serializeContext)); - EXPECT_TRUE(sentField2.IsEqualTo(receivedField2, &m_serializeContext)); - EXPECT_TRUE(emptyField.IsEqualTo(receivedEmptyField3, &m_serializeContext)); - EXPECT_TRUE(sentField3.IsEqualTo(receivedField3, &m_serializeContext)); - EXPECT_TRUE(emptyField.IsEqualTo(receivedEmptyField4, &m_serializeContext)); - - emptyField.DestroyData(&m_serializeContext); - sentField1.DestroyData(&m_serializeContext); - sentField2.DestroyData(&m_serializeContext); - sentField3.DestroyData(&m_serializeContext); - - receivedEmptyField1.DestroyData(&m_serializeContext); - receivedField1.DestroyData(&m_serializeContext); - receivedEmptyField2.DestroyData(&m_serializeContext); - receivedField2.DestroyData(&m_serializeContext); - receivedEmptyField3.DestroyData(&m_serializeContext); - receivedField3.DestroyData(&m_serializeContext); - receivedEmptyField4.DestroyData(&m_serializeContext); - } - - TEST_F(DynamicSerializableFieldMarshalerTest, MultipleMarshalUnmarshalTest_RandomChainEquivalentValue) - { - // Need to watch out for the size of the WriteBuffer. It's about ~2048 bytes, at worst case here, I'll write ~100 Bytes to the field per test object) - // So I need to keep this ~20 elements. - int numValues = 5 + m_random.GetRandom()%10; - AZStd::vector< AZ::DynamicSerializableField > sentValues; - AZStd::vector< AZ::DynamicSerializableField > receivedValues; - - sentValues.resize(numValues); - receivedValues.resize(numValues); - - for (auto& currentField : sentValues) - { - int value = m_random.GetRandom() % 4; - switch (value) - { - case 0: - { - currentField.Set(GenerateFooSerializable()); - } - break; - case 1: - { - currentField.Set(GenerateBarSerializable()); - } - break; - case 2: - { - currentField.Set(GenerateComplexSerializable()); - } - break; - case 3: - default: - // Empty field - break; - } - } - - for (auto& currentField : sentValues) - { - m_marshaler.Marshal(m_writeBuffer,currentField); - } - - PopulateReadBuffer(); - - for (auto& currentField : receivedValues) - { - m_marshaler.Unmarshal(currentField,m_readBuffer); - } - - for (unsigned int i=0; i < sentValues.size(); ++i) - { - AZ::DynamicSerializableField& sentField = sentValues[i]; - AZ::DynamicSerializableField& receivedField = receivedValues[i]; - - EXPECT_TRUE(sentField.IsEqualTo(receivedField, &m_serializeContext)); - - sentField.DestroyData(&m_serializeContext); - receivedField.DestroyData(&m_serializeContext); - } - } -} diff --git a/Code/Framework/Tests/Script/ScriptComponentTests.cpp b/Code/Framework/Tests/Script/ScriptComponentTests.cpp index a463192dd0..54c0d1dfa3 100644 --- a/Code/Framework/Tests/Script/ScriptComponentTests.cpp +++ b/Code/Framework/Tests/Script/ScriptComponentTests.cpp @@ -17,7 +17,6 @@ #include #include #include -#include #include "EntityTestbed.h" @@ -63,8 +62,6 @@ namespace UnitTest EBUS_EVENT_RESULT(m_behaviorContext, AZ::ComponentApplicationBus, GetBehaviorContext); EBUS_EVENT_RESULT(m_serializeContext, AZ::ComponentApplicationBus, GetSerializeContext); - NetBindable::Reflect(m_serializeContext); - AzToolsFramework::Components::ScriptEditorComponent::CreateDescriptor(); // descriptor is deleted by app AzToolsFramework::Components::ScriptEditorComponent::Reflect(m_serializeContext); @@ -228,63 +225,4 @@ namespace UnitTest EXPECT_NE(scriptComponent->GetScriptProperty("myNum"), nullptr); } - - TEST_F(ScriptComponentTest, UpdateNetSynchedProperty) - { - // Make sure altering a netsynched property in script only affects the single entity instance - const AZStd::string script = "local test = {\ - Properties = {\ - myNetSynchedNum = { default = 41, netSynched ={} },\ - doUpdate = { default = false },\ - },\ - }\ - function test:OnActivate()\ - self.tickBusHandler = TickBus.Connect(self, self.entityId)\ - end\ - function test:OnDeactivate()\ - self.tickBusHandler:Disconnect()\ - end\ - function test:OnTick(deltaTime, timePoint)\ - if self.Properties.doUpdate then\ - self.Properties.myNetSynchedNum = self.Properties.myNetSynchedNum+1\ - end\ - end\ - return test"; - - - const Data::Asset scriptAsset = CreateAndLoadScriptAsset(script); - Entity entity1, entity2; - ScriptComponent* scriptComponentInstance1 = BuildGameEntity(scriptAsset, entity1); - ScriptComponent* scriptComponentInstance2 = BuildGameEntity(scriptAsset, entity2); - - // Change the value of entity1's doUpdate to true. - // This way entity1's myNetSynchedNum should be incremented during OnTick - auto* doUpdateScriptProperty = azrtti_cast(scriptComponentInstance1->GetScriptProperty("doUpdate")); - ASSERT_NE(doUpdateScriptProperty, nullptr); - doUpdateScriptProperty->m_value = true; - - entity1.Init(); - entity2.Init(); - entity1.Activate(); - entity2.Activate(); - - // Tick in order to call OnTick in our lua script. - m_app.Tick(); - m_app.TickSystem(); - - // Ensure Entity1's myNetSynchedNum updated, but not Entity2 - auto* netSynchedProperty1 = scriptComponentInstance1->GetNetworkedScriptProperty("myNetSynchedNum"); - auto* netSynchedProperty2 = scriptComponentInstance2->GetNetworkedScriptProperty("myNetSynchedNum"); - ASSERT_NE(netSynchedProperty1, nullptr); - ASSERT_NE(netSynchedProperty2, nullptr); - - auto* num1 = azrtti_cast(netSynchedProperty1); - auto* num2 = azrtti_cast(netSynchedProperty2); - - ASSERT_NE(num1, nullptr); - ASSERT_NE(num2, nullptr); - - EXPECT_EQ(num1->m_value, 42); - EXPECT_EQ(num2->m_value, 41); - } } // namespace UnitTest diff --git a/Code/Framework/Tests/TransformComponent.cpp b/Code/Framework/Tests/TransformComponent.cpp index de172dc051..c2615f2a30 100644 --- a/Code/Framework/Tests/TransformComponent.cpp +++ b/Code/Framework/Tests/TransformComponent.cpp @@ -955,37 +955,6 @@ namespace UnitTest const char* m_objectStreamBuffer = nullptr; }; - class TransformComponentConvertFromV2 - : public TransformComponentVersionConverter - { - public: - TransformComponentConvertFromV2() - { - m_objectStreamBuffer = - R"DELIMITER( - - - - - - - - - - - - - - -)DELIMITER"; - } - }; - - TEST_F(TransformComponentConvertFromV2, IsStatic_False) - { - EXPECT_FALSE(m_transformInterface->IsStaticTransform()); - } - /////////////////////////////////////////////////////////////////////////// // TransformConfig diff --git a/Code/Framework/Tests/frameworktests_files.cmake b/Code/Framework/Tests/frameworktests_files.cmake index cf02b007b4..07990dc8fa 100644 --- a/Code/Framework/Tests/frameworktests_files.cmake +++ b/Code/Framework/Tests/frameworktests_files.cmake @@ -26,8 +26,6 @@ set(FILES GenAppDescriptors.cpp GenericComponentWrapperTest.cpp InstanceDataHierarchy.cpp - NetBinding.cpp - NetworkContext.cpp OctreePerformanceTests.cpp OctreeTests.cpp Slices.cpp @@ -35,12 +33,8 @@ set(FILES Script/ScriptEntityTests.cpp AssetCatalog.cpp AssetProcessorConnection.cpp - NetBindingSystemImplTest.cpp - NetBindingMocks.h NativeWindow.cpp TransformComponent.cpp - GridMocks.h - InterestManagerComponentTests.cpp SQLiteConnectionTests.cpp ProcessLaunchParseTests.cpp Application.cpp From ab8738b7c398364d2f797da7c872132fcaa99edd Mon Sep 17 00:00:00 2001 From: Eric Phister <52085794+amzn-phist@users.noreply.github.com> Date: Tue, 11 May 2021 15:16:32 -0500 Subject: [PATCH 058/100] Updating to support Wwise SDK 2021.1.1.X (#686) * Code updates for Wwise 2021.1.X support. * [WIP] CMake updates for Wwise 2021.1.X support. * Updates FindWwise.cmake to search for a Wwise install or let user set it as cache variable. * Makes Wwise SDK optional, and the AudioEngineWwise Gem will revert to a 'stub' build if no SDK found. * Adding a .gitignore for Wwise project files. * Updates a .wcmdline file for integration into Wwise projects. * Updates the cmake messaging regarding Wwise SDK and smooths out some of configuration scenarios. * Updates the Wwise project for AutomatedTesting to ver 2021.1.1.7601 and rebuilds banks. --- AutomatedTesting/sounds/.gitignore | 8 + AutomatedTesting/sounds/wwise/Init.bnk | 4 +- AutomatedTesting/sounds/wwise/Init.txt | 1 - AutomatedTesting/sounds/wwise/PluginInfo.xml | 9 +- .../sounds/wwise/SoundbanksInfo.xml | 26 +- AutomatedTesting/sounds/wwise/test_bank1.bnk | 4 +- AutomatedTesting/sounds/wwise/test_bank1.txt | 4 +- AutomatedTesting/sounds/wwise/test_bank2.bnk | 4 +- .../sounds/wwise/test_bank3.bankdeps | 4 +- AutomatedTesting/sounds/wwise/test_bank3.bnk | 4 +- AutomatedTesting/sounds/wwise/test_bank3.txt | 2 +- AutomatedTesting/sounds/wwise/test_bank4.bnk | 2 +- AutomatedTesting/sounds/wwise/test_bank4.txt | 2 +- AutomatedTesting/sounds/wwise/test_bank5.bnk | 4 +- AutomatedTesting/sounds/wwise/test_bank5.txt | 2 +- AutomatedTesting/sounds/wwise/test_bank6.bnk | 4 +- .../sounds/wwise/test_bank7.bankdeps | 4 +- AutomatedTesting/sounds/wwise/test_bank7.bnk | 4 +- AutomatedTesting/sounds/wwise/test_bank7.txt | 4 +- .../Default Work Unit.wwu | 10 +- .../Attenuations/Default Work Unit.wwu | 2 +- .../Audio Devices/Default Work Unit.wwu | 3 +- .../wwise_project/AutomatedTesting.wproj | 13491 ++++++++++++++++ .../Default Work Unit.wwu | 2 +- .../Conversion Settings/Default Work Unit.wwu | 2 +- .../Factory Conversion Settings.wwu | 2 +- .../Dynamic Dialogue/Default Work Unit.wwu | 2 +- .../Effects/Default Work Unit.wwu | 2 +- .../wwise_project/Effects/Factory Effects.wwu | 2 +- .../wwise_project/Effects/Factory Reflect.wwu | 8 +- .../Events/Default Work Unit.wwu | 2 +- .../Game Parameters/Default Work Unit.wwu | 2 +- .../Game Parameters/Factory Motion.wwu | 2 +- .../Factory SoundSeed Air Game Syncs.wwu | 2 +- .../Default Work Unit.wwu | 2 +- .../Default Work Unit.wwu | 6 +- .../Metadata/Default Work Unit.wwu | 6 + .../Mixing Sessions/Default Work Unit.wwu | 2 +- .../Modulators/Default Work Unit.wwu | 2 +- .../Presets/Default Work Unit.wwu | 2 +- .../wwise_project/Presets/Factory Reflect.wwu | 3 +- .../Presets/Factory Spatial Audio.wwu | 3 +- .../Queries/Default Work Unit.wwu | 2 +- .../wwise_project/Queries/Factory Queries.wwu | 2 +- .../SoundBanks/Default Work Unit.wwu | 2 +- .../Default Work Unit.wwu | 2 +- .../States/Default Work Unit.wwu | 2 +- .../Switches/Default Work Unit.wwu | 2 +- .../Triggers/Default Work Unit.wwu | 2 +- .../Virtual Acoustics/Default Work Unit.wwu | 2 +- .../Factory Reflect Acoustic Textures.wwu | 2 +- Gems/AudioEngineWwise/Code/CMakeLists.txt | 22 +- .../Code/Platform/Android/PAL_android.cmake | 2 +- .../Code/Platform/Linux/PAL_linux.cmake | 2 +- .../Code/Platform/Mac/PAL_mac.cmake | 2 +- .../Windows/AudioSystemImpl_wwise_Windows.cpp | 2 - .../Code/Platform/Windows/PAL_windows.cmake | 2 +- .../Code/Platform/iOS/PAL_ios.cmake | 2 +- .../Source/Engine/AudioSystemImpl_wwise.cpp | 18 +- .../Code/Source/Engine/Common_wwise.h | 5 +- ...copy_output_and_generate_metadata.wcmdline | 4 +- cmake/3rdParty/FindWwise.cmake | 93 +- .../Platform/Android/Wwise_android.cmake | 3 - .../Platform/Windows/Wwise_windows.cmake | 7 +- 64 files changed, 13696 insertions(+), 142 deletions(-) create mode 100644 AutomatedTesting/sounds/.gitignore create mode 100644 AutomatedTesting/sounds/wwise_project/AutomatedTesting.wproj create mode 100644 AutomatedTesting/sounds/wwise_project/Metadata/Default Work Unit.wwu diff --git a/AutomatedTesting/sounds/.gitignore b/AutomatedTesting/sounds/.gitignore new file mode 100644 index 0000000000..80c66daa1c --- /dev/null +++ b/AutomatedTesting/sounds/.gitignore @@ -0,0 +1,8 @@ +.backup/ +.cache/ +*.log +*.akd +*.dat +*.prof +*.validationcache +*.wsettings \ No newline at end of file diff --git a/AutomatedTesting/sounds/wwise/Init.bnk b/AutomatedTesting/sounds/wwise/Init.bnk index 530a7e007f..292288ff26 100644 --- a/AutomatedTesting/sounds/wwise/Init.bnk +++ b/AutomatedTesting/sounds/wwise/Init.bnk @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:803ddb37eb27cba666f9320c2f5905219193e1a069d1144a64df92fab0e31878 -size 1243 +oid sha256:c9e6a4ef3d2f33f31827ce2bba2ed8bad87324f3fe86f79389ef2956b304a924 +size 1180 diff --git a/AutomatedTesting/sounds/wwise/Init.txt b/AutomatedTesting/sounds/wwise/Init.txt index 038359ac1a..4b989c4017 100644 --- a/AutomatedTesting/sounds/wwise/Init.txt +++ b/AutomatedTesting/sounds/wwise/Init.txt @@ -21,5 +21,4 @@ Audio Bus ID Name Wwise Object Path Notes Audio Devices ID Name Type Notes 2317455096 No_Output No Output 3859886410 System System - 4230635974 Default_Motion_Device Wwise Motion diff --git a/AutomatedTesting/sounds/wwise/PluginInfo.xml b/AutomatedTesting/sounds/wwise/PluginInfo.xml index 61e689f373..19f3fe9c1b 100644 --- a/AutomatedTesting/sounds/wwise/PluginInfo.xml +++ b/AutomatedTesting/sounds/wwise/PluginInfo.xml @@ -1,9 +1,8 @@ - + - - - - + + + diff --git a/AutomatedTesting/sounds/wwise/SoundbanksInfo.xml b/AutomatedTesting/sounds/wwise/SoundbanksInfo.xml index 22ae71f4dc..d7bfecaa53 100644 --- a/AutomatedTesting/sounds/wwise/SoundbanksInfo.xml +++ b/AutomatedTesting/sounds/wwise/SoundbanksInfo.xml @@ -1,11 +1,11 @@ - + - Q:\audio\dev\AutomatedTesting\sounds\wwise_project\ - Q:\audio\dev\AutomatedTesting\sounds\wwise_project\.cache\Windows\ - Q:\audio\dev\AutomatedTesting\sounds\wwise\ + D:\code\o3de\AutomatedTesting\sounds\wwise_project\ + D:\code\o3de\AutomatedTesting\sounds\wwise_project\.cache\Windows\ + D:\code\o3de\AutomatedTesting\sounds\wwise\ - Q:\audio\dev\AutomatedTesting\sounds\wwise_project\GeneratedSoundBanks\Windows + D:\code\o3de\AutomatedTesting\sounds\wwise_project\GeneratedSoundBanks\Windows @@ -28,7 +28,7 @@ - + \SoundBanks\Default Work Unit\test_bank2 test_bank2 test_bank2.bnk @@ -37,7 +37,7 @@ - + \SoundBanks\Default Work Unit\test_bank3 test_bank3 test_bank3.bnk @@ -60,7 +60,7 @@ - + \SoundBanks\Default Work Unit\test_bank1 test_bank1 test_bank1.bnk @@ -83,7 +83,7 @@ - + \SoundBanks\Default Work Unit\test_bank6 test_bank6 test_bank6.bnk @@ -102,7 +102,7 @@ - + \SoundBanks\Default Work Unit\test_bank7 test_bank7 test_bank7.bnk @@ -125,7 +125,7 @@ - + \SoundBanks\Default Work Unit\test_bank4 test_bank4 test_bank4.bnk @@ -136,7 +136,7 @@ - + \SoundBanks\Default Work Unit\test_bank5 test_bank5 test_bank5.bnk @@ -169,7 +169,7 @@ - + Init Init Init.bnk diff --git a/AutomatedTesting/sounds/wwise/test_bank1.bnk b/AutomatedTesting/sounds/wwise/test_bank1.bnk index 9e8f50a98a..bd0e1e66cb 100644 --- a/AutomatedTesting/sounds/wwise/test_bank1.bnk +++ b/AutomatedTesting/sounds/wwise/test_bank1.bnk @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:94ea13931c13592deba669bd4920328ff96f17e6f8fce280d03f00251a96327a -size 94122 +oid sha256:3db299d7d823b649ff20a7ffc986dccfce1fa3189f178491e2712d6c00b317af +size 94126 diff --git a/AutomatedTesting/sounds/wwise/test_bank1.txt b/AutomatedTesting/sounds/wwise/test_bank1.txt index a0c6e13621..5ec2e4b96b 100644 --- a/AutomatedTesting/sounds/wwise/test_bank1.txt +++ b/AutomatedTesting/sounds/wwise/test_bank1.txt @@ -3,8 +3,8 @@ Event ID Name Wwise Object Path Notes 865645077 test_event_1_bank1_embedded_target \Default Work Unit\test_event_1_bank1_embedded_target In Memory Audio ID Name Audio source file Wwise Object Path Notes Data Size - 23965881 test_sfx_1_bank1_embedded Q:\audio\dev\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\AMZ_sfx_NME_wpn_plasma_pistol_fire_impact004_56D34C19.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_1_bank1_embedded 93864 + 23965881 test_sfx_1_bank1_embedded D:\code\o3de\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\AMZ_sfx_NME_wpn_plasma_pistol_fire_impact004_56D34C19.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_1_bank1_embedded 93864 Streamed Audio ID Name Audio source file Generated audio file Wwise Object Path Notes - 499820003 test_sfx_2_bank1_streamed Q:\audio\dev\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\env_door_scanner_scan_success_56D34C19.wem 499820003.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_2_bank1_streamed + 499820003 test_sfx_2_bank1_streamed D:\code\o3de\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\env_door_scanner_scan_success_56D34C19.wem 499820003.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_2_bank1_streamed diff --git a/AutomatedTesting/sounds/wwise/test_bank2.bnk b/AutomatedTesting/sounds/wwise/test_bank2.bnk index 2e31c359bf..ee96554646 100644 --- a/AutomatedTesting/sounds/wwise/test_bank2.bnk +++ b/AutomatedTesting/sounds/wwise/test_bank2.bnk @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ad73fd0981e47fe3313eff51d2841ea5fd522a99103684d696849e7353277ea9 -size 430 +oid sha256:1bdaed4dc5cc514a8a3ddfaf990f59061514af7962a7a112eb677ad5c45fcb85 +size 434 diff --git a/AutomatedTesting/sounds/wwise/test_bank3.bankdeps b/AutomatedTesting/sounds/wwise/test_bank3.bankdeps index 606dbdbac8..51a952d463 100644 --- a/AutomatedTesting/sounds/wwise/test_bank3.bankdeps +++ b/AutomatedTesting/sounds/wwise/test_bank3.bankdeps @@ -2,9 +2,9 @@ "version": "1.0", "bankName": "test_bank3.bnk", "dependencies": [ - "196049145.wem", + "test_bank4.bnk", "Init.bnk", - "test_bank4.bnk" + "196049145.wem" ], "includedEvents": [ "test_event_5_bank3_embedded_target_bank4", diff --git a/AutomatedTesting/sounds/wwise/test_bank3.bnk b/AutomatedTesting/sounds/wwise/test_bank3.bnk index 32e6161e6c..6b83836c18 100644 --- a/AutomatedTesting/sounds/wwise/test_bank3.bnk +++ b/AutomatedTesting/sounds/wwise/test_bank3.bnk @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:33eabaa646e9567017946bee05b1b5a835e91862f63145ebe5a2fbdd9c9f5a49 -size 226 +oid sha256:57c75cf8745b31071a788a20d8de5a60cedbfb8a6155eae1a461b8c6501e5479 +size 230 diff --git a/AutomatedTesting/sounds/wwise/test_bank3.txt b/AutomatedTesting/sounds/wwise/test_bank3.txt index ca6efc6e02..9a843afad7 100644 --- a/AutomatedTesting/sounds/wwise/test_bank3.txt +++ b/AutomatedTesting/sounds/wwise/test_bank3.txt @@ -3,5 +3,5 @@ Event ID Name Wwise Object Path Notes 645979556 test_event_6_bank3_streamed_target_bank4 \Default Work Unit\test_event_6_bank3_streamed_target_bank4 Event that lives in test_bank3. This event targets only one media, which is streamed from test_bank4. Streamed Audio ID Name Audio source file Generated audio file Wwise Object Path Notes - 196049145 test_sfx_6_bank4_streamed Q:\audio\dev\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\AMZ_sfx_NME_wpn_plasma_pistol_fire003_56D34C19.wem 196049145.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_6_bank4_streamed + 196049145 test_sfx_6_bank4_streamed D:\code\o3de\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\AMZ_sfx_NME_wpn_plasma_pistol_fire003_56D34C19.wem 196049145.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_6_bank4_streamed diff --git a/AutomatedTesting/sounds/wwise/test_bank4.bnk b/AutomatedTesting/sounds/wwise/test_bank4.bnk index e169744d84..5f5883d559 100644 --- a/AutomatedTesting/sounds/wwise/test_bank4.bnk +++ b/AutomatedTesting/sounds/wwise/test_bank4.bnk @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:79d308f3c50fece383fd82fd0060e26558e6a2e78a4ecd5d8afe24907489a88f +oid sha256:3a635f7d1ccb256caed90d18ca566cd0fa56d49b491af7c88c0b5da55a3ef4fe size 142234 diff --git a/AutomatedTesting/sounds/wwise/test_bank4.txt b/AutomatedTesting/sounds/wwise/test_bank4.txt index 770cb7f171..7649b0eed5 100644 --- a/AutomatedTesting/sounds/wwise/test_bank4.txt +++ b/AutomatedTesting/sounds/wwise/test_bank4.txt @@ -1,3 +1,3 @@ In Memory Audio ID Name Audio source file Wwise Object Path Notes Data Size - 666825490 test_sfx_5_bank4_embedded Q:\audio\dev\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\AMZN_sfx_env_commsarray_apllyupdate_end_56D34C19.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_5_bank4_embedded 142170 + 666825490 test_sfx_5_bank4_embedded D:\code\o3de\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\AMZN_sfx_env_commsarray_apllyupdate_end_56D34C19.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_5_bank4_embedded 142170 diff --git a/AutomatedTesting/sounds/wwise/test_bank5.bnk b/AutomatedTesting/sounds/wwise/test_bank5.bnk index b4e629d9a7..168c7c1a4d 100644 --- a/AutomatedTesting/sounds/wwise/test_bank5.bnk +++ b/AutomatedTesting/sounds/wwise/test_bank5.bnk @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:80c02f30d439ffcfb479e4a82b0269fe4f479c50019028e51f0fa6e3fea0bfdd -size 290 +oid sha256:fa329eeb83184e88b7ab26fbff2479a98232210bcd130801041b20ccb3bcf16e +size 294 diff --git a/AutomatedTesting/sounds/wwise/test_bank5.txt b/AutomatedTesting/sounds/wwise/test_bank5.txt index 0f66c57f8e..3d560cf9f5 100644 --- a/AutomatedTesting/sounds/wwise/test_bank5.txt +++ b/AutomatedTesting/sounds/wwise/test_bank5.txt @@ -5,5 +5,5 @@ Event ID Name Wwise Object Path Notes 3546419658 test_event_7_bank5_referenced_event_bank1_embedded \Default Work Unit\test_event_7_bank5_referenced_event_bank1_embedded Streamed Audio ID Name Audio source file Generated audio file Wwise Object Path Notes - 499820003 test_sfx_2_bank1_streamed Q:\audio\dev\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\env_door_scanner_scan_success_56D34C19.wem 499820003.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_2_bank1_streamed + 499820003 test_sfx_2_bank1_streamed D:\code\o3de\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\env_door_scanner_scan_success_56D34C19.wem 499820003.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_2_bank1_streamed diff --git a/AutomatedTesting/sounds/wwise/test_bank6.bnk b/AutomatedTesting/sounds/wwise/test_bank6.bnk index 18ee92b51d..4c942037f0 100644 --- a/AutomatedTesting/sounds/wwise/test_bank6.bnk +++ b/AutomatedTesting/sounds/wwise/test_bank6.bnk @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:07d132d54b2c747e2409a56c05a4adca0dfa4407b791ffaa6bb14531f92f89aa -size 494 +oid sha256:80d3014fcfd3a8ff37219515f0c9d67a2a674094002538ac6741702dca07c14d +size 498 diff --git a/AutomatedTesting/sounds/wwise/test_bank7.bankdeps b/AutomatedTesting/sounds/wwise/test_bank7.bankdeps index 02be60a544..56cf29c619 100644 --- a/AutomatedTesting/sounds/wwise/test_bank7.bankdeps +++ b/AutomatedTesting/sounds/wwise/test_bank7.bankdeps @@ -2,9 +2,9 @@ "version": "1.0", "bankName": "test_bank7.bnk", "dependencies": [ + "656567798.wem", "601903616.wem", - "Init.bnk", - "656567798.wem" + "Init.bnk" ], "includedEvents": [ "test_event_11_bank7_streamed_target", diff --git a/AutomatedTesting/sounds/wwise/test_bank7.bnk b/AutomatedTesting/sounds/wwise/test_bank7.bnk index abc398d1f1..c01346fd58 100644 --- a/AutomatedTesting/sounds/wwise/test_bank7.bnk +++ b/AutomatedTesting/sounds/wwise/test_bank7.bnk @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:990538a33c72e79d63cab0c191b4e0f199688b923bb6bdcc8888aab375e7d11d -size 226 +oid sha256:0de33094b9792d7f9ff8042e16b153dd76729e9010d6713e1824d2229c653042 +size 230 diff --git a/AutomatedTesting/sounds/wwise/test_bank7.txt b/AutomatedTesting/sounds/wwise/test_bank7.txt index 033c2ea5b9..3bf2da686b 100644 --- a/AutomatedTesting/sounds/wwise/test_bank7.txt +++ b/AutomatedTesting/sounds/wwise/test_bank7.txt @@ -3,6 +3,6 @@ Event ID Name Wwise Object Path Notes 2110064689 test_event_11_bank7_streamed_target \Default Work Unit\test_event_11_bank7_streamed_target Streamed Audio ID Name Audio source file Generated audio file Wwise Object Path Notes - 601903616 test_sfx_8_bank7_streamed Q:\audio\dev\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\gun_blaster_no_trigger_shot_1_56D34C19.wem 601903616.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_8_bank7_streamed - 656567798 test_sfx_7_bank7_streamed Q:\audio\dev\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\impact_bot_hits_metalelement_56D34C19.wem 656567798.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_7_bank7_streamed + 601903616 test_sfx_8_bank7_streamed D:\code\o3de\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\gun_blaster_no_trigger_shot_1_56D34C19.wem 601903616.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_8_bank7_streamed + 656567798 test_sfx_7_bank7_streamed D:\code\o3de\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\impact_bot_hits_metalelement_56D34C19.wem 656567798.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_7_bank7_streamed diff --git a/AutomatedTesting/sounds/wwise_project/Actor-Mixer Hierarchy/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Actor-Mixer Hierarchy/Default Work Unit.wwu index 8cc6eeecc2..33ac513281 100644 --- a/AutomatedTesting/sounds/wwise_project/Actor-Mixer Hierarchy/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Actor-Mixer Hierarchy/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + @@ -21,6 +21,7 @@ + @@ -50,6 +51,7 @@ + @@ -72,6 +74,7 @@ + @@ -101,6 +104,7 @@ + @@ -130,6 +134,7 @@ + @@ -159,6 +164,7 @@ + @@ -187,6 +193,7 @@ SFX + @@ -215,6 +222,7 @@ SFX + diff --git a/AutomatedTesting/sounds/wwise_project/Attenuations/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Attenuations/Default Work Unit.wwu index 9034f07366..955c7d9e4a 100644 --- a/AutomatedTesting/sounds/wwise_project/Attenuations/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Attenuations/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Audio Devices/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Audio Devices/Default Work Unit.wwu index 472e9b12d1..f56682b0bf 100644 --- a/AutomatedTesting/sounds/wwise_project/Audio Devices/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Audio Devices/Default Work Unit.wwu @@ -1,11 +1,10 @@ - + - diff --git a/AutomatedTesting/sounds/wwise_project/AutomatedTesting.wproj b/AutomatedTesting/sounds/wwise_project/AutomatedTesting.wproj new file mode 100644 index 0000000000..1aead159ad --- /dev/null +++ b/AutomatedTesting/sounds/wwise_project/AutomatedTesting.wproj @@ -0,0 +1,13491 @@ + + + + + + + + + + + + + + + + + + + + + + GeneratedSoundBanks\Windows + + + + + 256 + + + + + + ..\wwise\ + + + + + Copy Streamed Files and Generate Dependency Info + + + + + "$(CopyStreamedFilesExePath)" -info "$(InfoFilePath)" -outputpath "$(SoundBankPath)" -banks "$(SoundBankListAsTextFile)" -languages "$(LanguageList)" +"$(WwiseProjectPath)\..\..\..\python\python.cmd" "$(WwiseProjectPath)\..\..\..\Gems\AudioEngineWwise\Tools\WwiseAuthoringScripts\bank_info_parser.py" "$(InfoFilePath)" "$(SoundBankPath)" + + + + + + + + + + + + + + + -80 + + + + + + + + + + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 8 + + + + + 0 + + + + + -1 + + + + + -1 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + -1 + + + + + -1 + + + + + 0 + + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + 0 + + + + + False + + + + + True + + + + + False + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 2 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + False + + + + + 65535 + + + + + 127 + + + + + 0 + + + + + 1 + + + + + 60 + + + + + 0 + + + + + 127 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + 50 + + + + + False + + + + + -10 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 50 + + + + + + + + + 1 + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 0 + + + + + 10000 + + + + + 1 + + + + + 400 + + + + + 1 + + + + + 1 + + + + + 0.5 + + + + + 0 + + + + + -96 + + + + + 0 + + + + + True + + + + + False + + + + + 0 + + + + + 0 + + + + + 16 + + + + + -96 + + + + + 0 + + + + + 48000 + + + + + 0 + + + + + + + + + 16 + + + + + False + + + + + 1 + + + + + 75 + + + + + + + + + False + + + + + 512 + + + + + -50 + + + + + -30 + + + + + -40 + + + + + 0 + + + + + 24024 + + + + + 0 + + + + + 8 + + + + + English(US) + + + + + 0 + + + + + 0 + + + + + False + + + + + + + + + + + + + + + 1 + + + + + True + + + + + False + + + + + False + + + + + True + + + + + 256 + + + + + + + + + + 50 + + + + + 100 + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + + + + + + True + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + False + + + + + True + + + + + True + + + + + True + + + + + True + + + + + -80 + + + + + + + + + + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 5 + + + + + 0.5 + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 5 + + + + + 0.5 + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 64 + + + + + 1.5 + + + + + 2 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + 64 + + + + + 64 + + + + + 4 + + + + + 0 + + + + + 0.1 + + + + + 4 + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 20 + + + + + 10000 + + + + + 0.2 + + + + + True + + + + + 80 + + + + + 0.2 + + + + + False + + + + + 200 + + + + + 0.25 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + True + + + + + True + + + + + True + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 4 + + + + + 4 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + True + + + + + 0 + + + + + 100 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 10 + + + + + 1 + + + + + 200 + + + + + 0 + + + + + 0 + + + + + 10 + + + + + 1 + + + + + 200 + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + 40 + + + + + 0 + + + + + 1000 + + + + + 160 + + + + + 0 + + + + + 0.5 + + + + + 0.2 + + + + + 0 + + + + + 0.5 + + + + + 0.2 + + + + + 0 + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 0.2 + + + + + 0 + + + + + 0.2 + + + + + 0.2 + + + + + 3000 + + + + + 0.2 + + + + + 0 + + + + + 6 + + + + + 15000 + + + + + 0 + + + + + 1000 + + + + + 20000 + + + + + 0 + + + + + 0.5 + + + + + 0.2 + + + + + 0 + + + + + 0.5 + + + + + 0.2 + + + + + 0 + + + + + 1 + + + + + True + + + + + False + + + + + + + + + 0 + + + + + 1 + + + + + False + + + + + + + + + 1 + + + + + 0 + + + + + True + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + False + + + + + 3 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + False + + + + + 65535 + + + + + 127 + + + + + 0 + + + + + 1 + + + + + 60 + + + + + 0 + + + + + 127 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 50 + + + + + False + + + + + -10 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + False + + + + + 65535 + + + + + 127 + + + + + 0 + + + + + 1 + + + + + 60 + + + + + 0 + + + + + 127 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 1 + + + + + False + + + + + 2 + + + + + True + + + + + False + + + + + 0 + + + + + 1 + + + + + 1 + + + + + 50 + + + + + False + + + + + -10 + + + + + True + + + + + 1 + + + + + 1 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 1 + + + + + 0 + + + + + 100 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 50 + + + + + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 5 + + + + + 0.5 + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 5 + + + + + 0.5 + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 5 + + + + + 0.5 + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 5 + + + + + 0.5 + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 5 + + + + + 0.5 + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 5 + + + + + 0.5 + + + + + 0 + + + + + True + + + + + 5000 + + + + + 10000 + + + + + False + + + + + + + + + False + + + + + 0 + + + + + 3 + + + + + 9 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + False + + + + + 65535 + + + + + 127 + + + + + 0 + + + + + 1 + + + + + 60 + + + + + 0 + + + + + 127 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 50 + + + + + False + + + + + -10 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + 0 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 50 + + + + + + + + + 1000 + + + + + 5000 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + + + 96 + + + + + -100 + + + + + -100 + + + + + -100 + + + + + False + + + + + False + + + + + + + + + False + + + + + 0 + + + + + 35 + + + + + 0 + + + + + True + + + + + 0 + + + + + 1 + + + + + 1 + + + + + True + + + + + + + + + 0 + + + + + + + + + False + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + 3 + + + + + 9 + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 0 + + + + + False + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + False + + + + + False + + + + + + + + + 64 + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 100 + + + + + 0 + + + + + True + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 100 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + -96 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + 100 + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + 100 + + + + + 0 + + + + + False + + + + + 0 + + + + + 50 + + + + + 50 + + + + + 50 + + + + + + + + + False + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + 4000 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 1 + + + + + 50 + + + + + False + + + + + -10 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + 120 + + + + + 4 + + + + + 4 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 100 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 100 + + + + + 50 + + + + + False + + + + + -10 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + False + + + + + 65535 + + + + + 127 + + + + + 0 + + + + + 1 + + + + + 60 + + + + + 0 + + + + + 127 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 50 + + + + + False + + + + + -10 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 50 + + + + + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 1 + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + 0 + + + + + 0 + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + True + + + + + False + + + + + False + + + + + True + + + + + True + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + + + + + + + + + + + 0 + + + + + + + + + + 0 + + + + + + + + + + + + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + + + + -1 + + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + 0 + + + + + + + + + + 0 + + + + + + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 1 + + + + + 50 + + + + + False + + + + + -10 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + 120 + + + + + 4 + + + + + 4 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + True + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 1 + + + + + 50 + + + + + False + + + + + -10 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + 120 + + + + + 4 + + + + + 4 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + + + + + 0 + + + + + 1 + + + + + 1 + + + + + False + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 50 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 7 + + + + + + + + + + False + + + + + 1 + + + + + + + + + + False + + + + + True + + + + + True + + + + + True + + + + + True + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + + + + + + 0 + + + + + 1 + + + + + False + + + + + 0 + + + + + + + + + 4 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + -6 + + + + + 0 + + + + + 90 + + + + + 0 + + + + + 245 + + + + + False + + + + + True + + + + + False + + + + + 100 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + False + + + + + 100 + + + + + + + + + True + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + False + + + + + + + + + + + + + + + False + + + + + False + + + + + True + + + + + False + + + + + False + + + + + True + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + + + + + + True + + + + + False + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + False + + + + + True + + + + + + + + + 0 + + + + + False + + + + + + + + + + + + + + + + + + True + + + + + 4 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + + + + + 0 + + + + + False + + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 1 + + + + + 0 + + + + + 1 + + + + + 8 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 100 + + + + + 0 + + + + + True + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 100 + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 1 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + False + + + + + + + + + 0 + + + + + 50 + + + + + 0.2 + + + + + False + + + + + 0.2 + + + + + 0.5 + + + + + True + + + + + 100 + + + + + 0 + + + + + 1 + + + + + 1 + + + + + False + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + + + + + + 1 + + + + + False + + + + + 0 + + + + + + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + + + + + + 1 + + + + + False + + + + + 0 + + + + + + + + + + 0 + + + + + + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + + + + + 0 + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + + + + + 0 + + + + + True + + + + + 1 + + + + + 1 + + + + + False + + + + + 1 + + + + + 0 + + + + + 1 + + + + + 1 + + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 4 + + + + + 1 + + + + + 440 + + + + + -12 + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 1 + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + 4 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 0 + + + + + -12 + + + + + 1 + + + + + False + + + + + 0 + + + + + -12 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + False + + + + + 10 + + + + + 0 + + + + + + + + + 0 + + + + + 4 + + + + + 6 + + + + + 5 + + + + + 100 + + + + + 1000 + + + + + 12000 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + True + + + + + True + + + + + True + + + + + True + + + + + 0 + + + + + False + + + + + True + + + + + 1 + + + + + 1 + + + + + 1 + + + + + + + + + 0 + + + + + 0.5 + + + + + 15 + + + + + True + + + + + True + + + + + 0 + + + + + False + + + + + True + + + + + 25 + + + + + + + + + 0.1 + + + + + True + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + True + + + + + 1.5 + + + + + 0.1 + + + + + 0 + + + + + + + + + 0.1 + + + + + True + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + True + + + + + 3 + + + + + 0.01 + + + + + -40 + + + + + + + + + True + + + + + 0 + + + + + True + + + + + 0.01 + + + + + 0 + + + + + False + + + + + True + + + + + 10 + + + + + 0.1 + + + + + 0 + + + + + + + + + 100 + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + True + + + + + 1 + + + + + 1000 + + + + + 0 + + + + + 0 + + + + + True + + + + + 40 + + + + + 0 + + + + + 0 + + + + + 18000 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + True + + + + + 10 + + + + + 0 + + + + + 100 + + + + + -40 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + True + + + + + 40 + + + + + 18000 + + + + + -96 + + + + + -20 + + + + + 20 + + + + + 0 + + + + + 0 + + + + + False + + + + + True + + + + + 100 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 13.62 + + + + + 26.09 + + + + + 26.55 + + + + + 26.91 + + + + + 28.04 + + + + + 29.09 + + + + + 29.9 + + + + + 30.86 + + + + + 15.66 + + + + + 17.52 + + + + + 19.02 + + + + + 20.83 + + + + + 22.6 + + + + + 24.05 + + + + + 24.78 + + + + + 25.6 + + + + + -96.3 + + + + + 2 + + + + + True + + + + + 8 + + + + + False + + + + + 0 + + + + + True + + + + + 4 + + + + + -35 + + + + + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + True + + + + + True + + + + + 0 + + + + + True + + + + + 100 + + + + + 0 + + + + + False + + + + + -96.3 + + + + + + + + + 0 + + + + + 0 + + + + + 40 + + + + + 1.2 + + + + + 80 + + + + + 50 + + + + + 8 + + + + + 2 + + + + + 100 + + + + + 15 + + + + + 5 + + + + + 66 + + + + + -96.3 + + + + + 0 + + + + + -20 + + + + + 23 + + + + + True + + + + + False + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 3 + + + + + 1 + + + + + 1 + + + + + 1000 + + + + + 0 + + + + + 3 + + + + + 1 + + + + + 2 + + + + + 10000 + + + + + 0 + + + + + 3 + + + + + 1 + + + + + 0 + + + + + 2.25 + + + + + True + + + + + 0 + + + + + -96.3 + + + + + -96.3 + + + + + False + + + + + 25 + + + + + 8 + + + + + 0 + + + + + -20 + + + + + 100 + + + + + 50 + + + + + 100 + + + + + 0.8 + + + + + 0.1 + + + + + 0 + + + + + 180 + + + + + + + + + 1 + + + + + 0 + + + + + False + + + + + 0 + + + + + 1 + + + + + 0 + + + + + False + + + + + 0 + + + + + 10 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0.5 + + + + + False + + + + + 0 + + + + + 10 + + + + + 5 + + + + + 1 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0.25 + + + + + False + + + + + 0 + + + + + 0.5 + + + + + + + + + 1 + + + + + 1 + + + + + True + + + + + 0.5 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + 10 + + + + + 0 + + + + + 1 + + + + + 1 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0 + + + + + False + + + + + 10 + + + + + 0.5 + + + + + 0 + + + + + 1 + + + + + + + + + 440 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 10 + + + + + + + + + False + + + + + 440 + + + + + 0 + + + + + 10 + + + + + 1 + + + + + + + + + 0 + + + + + 5 + + + + + 1 + + + + + True + + + + + 0 + + + + + 1 + + + + + True + + + + + 50 + + + + + 1 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + 100 + + + + + + + + + 0 + + + + + 50 + + + + + 50 + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + False + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + False + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + False + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + False + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + False + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + False + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 100 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + -96.3 + + + + + 0 + + + + + 0 + + + + + False + + + + + 4 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 0 + + + + + -75 + + + + + False + + + + + False + + + + + 6 + + + + + 0 + + + + + 0 + + + + + True + + + + + 100 + + + + + True + + + + + 0 + + + + + -96.3 + + + + + 0 + + + + + -60 + + + + + -96.3 + + + + + False + + + + + 0 + + + + + 0 + + + + + 1024 + + + + + 48000 + + + + + 48000 + + + + + 48000 + + + + + 180 + + + + + 0 + + + + + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + -48 + + + + + False + + + + + 0.1 + + + + + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + 100 + + + + + 0 + + + + + 2048 + + + + + + + + + 0 + + + + + True + + + + + 100 + + + + + 1 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + True + + + + + True + + + + + + + + + 1 + + + + + False + + + + + Recorder.wav + + + + + -3 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + + + + + + True + + + + + -96.3 + + + + + False + + + + + -3 + + + + + -3 + + + + + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + -100 + + + + + True + + + + + -12 + + + + + 0.1 + + + + + -12 + + + + + 0 + + + + + False + + + + + -12 + + + + + 0.1 + + + + + -12 + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + 50 + + + + + -96 + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + 0 + + + + + False + + + + + False + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + False + + + + + True + + + + + True + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1024 + + + + + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + + + + + 1000 + + + + + 0 + + + + + 0 + + + + + -96 + + + + + 0 + + + + + 0 + + + + + False + + + + + -6 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + False + + + + + -6 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + True + + + + + + + + + False + + + + + False + + + + + + + + + 1 + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 250 + + + + + 100 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + -96 + + + + + 3 + + + + + True + + + + + 1000 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0.5 + + + + + 0 + + + + + 2400 + + + + + 345 + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 1 + + + + + + + + + False + + + + + True + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 32 + + + + + False + + + + + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + False + + + + + True + + + + + False + + + + + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + False + + + + + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + False + + + + + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + False + + + + + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + False + + + + + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 100 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 10 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 20000 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0.707 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 256 + + + + + False + + + + + 100 + + + + + 100 + + + + + 100 + + + + + 100 + + + + + 1000 + + + + + 1000 + + + + + 1000 + + + + + 1000 + + + + + 20000 + + + + + 20000 + + + + + 20000 + + + + + 20000 + + + + + 1 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + 5 + + + + + 5 + + + + + 9 + + + + + 9 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 16641 + + + + + 0 + + + + + 0 + + + + + False + + + + + 10 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 60 + + + + + 1 + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + 0 + + + + + True + + + + + False + + + + + 0.01 + + + + + True + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0.1 + + + + + 0 + + + + + 0.01 + + + + + True + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0.1 + + + + + 0 + + + + + 0.01 + + + + + True + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0.1 + + + + + 0 + + + + + 0.01 + + + + + True + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0.1 + + + + + 0 + + + + + 150 + + + + + 1000 + + + + + 6000 + + + + + 0 + + + + + False + + + + + 0 + + + + + 4 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + True + + + + + True + + + + + True + + + + + True + + + + + True + + + + + 5 + + + + + 100 + + + + + 0 + + + + + 1 + + + + + True + + + + + 3 + + + + + 200 + + + + + 0 + + + + + 1 + + + + + True + + + + + 3 + + + + + 500 + + + + + 0 + + + + + 1 + + + + + True + + + + + 4 + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + False + + + + + 3 + + + + + 3000 + + + + + 0 + + + + + 1 + + + + + False + + + + + 3 + + + + + 6000 + + + + + 0 + + + + + 1 + + + + + 4 + + + + + + + + + -12 + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + False + + + + + + + + + 1 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 1 + + + + + 1 + + + + + 0 + + + + + -12 + + + + + 1 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 6 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 0 + + + + + + + + + + 0 + + + + + 0 + + + + + + + + + 0.6 + + + + + 0.6 + + + + + 0.5 + + + + + 0.3 + + + + + 0.05 + + + + + 0.25 + + + + + 0.02 + + + + + 1.5 + + + + + 0.2 + + + + + 0.3 + + + + + True + + + + + 0.2 + + + + + 8 + + + + + 0.2 + + + + + 12 + + + + + + + + + 20 + + + + + 0.7 + + + + + 100 + + + + + 0.1 + + + + + 1 + + + + + 1 + + + + + True + + + + + 1 + + + + + 0 + + + + + 3 + + + + + 1 + + + + + + + + + 2 + + + + + 0.7 + + + + + 1 + + + + + 0 + + + + + 1 + + + + + 0.9 + + + + + 0.1 + + + + + 3 + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + 0 + + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 2 + + + + + False + + + + + + + + + + + + + + + 1 + + + + + + + + + + + + + + 0 + + + + + + + + + False + + + + + 0 + + + + + 0 + + + + + 1.4 + + + + + -6 + + + + + True + + + + + 0 + + + + + 0 + + + + + False + + + + + True + + + + + 0.5 + + + + + 10000 + + + + + -6 + + + + + 7 + + + + + 1 + + + + + 1 + + + + + 7.25 + + + + + 2.75 + + + + + 3.25 + + + + + 4.25 + + + + + 4.75 + + + + + 3.75 + + + + + + + + + 100 + + + + + 50 + + + + + + + + + + + + + + + + + 0 + 0 + 5 + + + 100 + -200 + 37 + + + + + + + + + + + + + + 0 + 0 + 5 + + + 100 + 100 + 37 + + + + + + + + + + + + + + 0 + 0 + 5 + + + 100 + 100 + 37 + + + + + + + + + + + + + + 0 + 0 + 5 + + + 100 + -200 + 37 + + + + + + + + + + + + + + 0 + 0 + 5 + + + 100 + 100 + 37 + + + + + + + + + + + + + + 0 + 0 + 5 + + + 100 + 100 + 37 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/sounds/wwise_project/Control Surface Sessions/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Control Surface Sessions/Default Work Unit.wwu index 1f7d254b46..4e13dee554 100644 --- a/AutomatedTesting/sounds/wwise_project/Control Surface Sessions/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Control Surface Sessions/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Conversion Settings/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Conversion Settings/Default Work Unit.wwu index ac7c83d1db..236f5765db 100644 --- a/AutomatedTesting/sounds/wwise_project/Conversion Settings/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Conversion Settings/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Conversion Settings/Factory Conversion Settings.wwu b/AutomatedTesting/sounds/wwise_project/Conversion Settings/Factory Conversion Settings.wwu index 9a94d81c32..7873f5135a 100644 --- a/AutomatedTesting/sounds/wwise_project/Conversion Settings/Factory Conversion Settings.wwu +++ b/AutomatedTesting/sounds/wwise_project/Conversion Settings/Factory Conversion Settings.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Dynamic Dialogue/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Dynamic Dialogue/Default Work Unit.wwu index e6e033e251..5411c7d503 100644 --- a/AutomatedTesting/sounds/wwise_project/Dynamic Dialogue/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Dynamic Dialogue/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Effects/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Effects/Default Work Unit.wwu index f938135d6b..ca63005f4b 100644 --- a/AutomatedTesting/sounds/wwise_project/Effects/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Effects/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Effects/Factory Effects.wwu b/AutomatedTesting/sounds/wwise_project/Effects/Factory Effects.wwu index ac716afb97..5a545f5e61 100644 --- a/AutomatedTesting/sounds/wwise_project/Effects/Factory Effects.wwu +++ b/AutomatedTesting/sounds/wwise_project/Effects/Factory Effects.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Effects/Factory Reflect.wwu b/AutomatedTesting/sounds/wwise_project/Effects/Factory Reflect.wwu index f2269dd2dc..2c0ebb6b67 100644 --- a/AutomatedTesting/sounds/wwise_project/Effects/Factory Reflect.wwu +++ b/AutomatedTesting/sounds/wwise_project/Effects/Factory Reflect.wwu @@ -1,10 +1,9 @@ - + - - + @@ -185,8 +184,7 @@ - - + diff --git a/AutomatedTesting/sounds/wwise_project/Events/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Events/Default Work Unit.wwu index c65c8adca1..73c2e8f028 100644 --- a/AutomatedTesting/sounds/wwise_project/Events/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Events/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Game Parameters/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Game Parameters/Default Work Unit.wwu index e373885f46..a939ebe124 100644 --- a/AutomatedTesting/sounds/wwise_project/Game Parameters/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Game Parameters/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Game Parameters/Factory Motion.wwu b/AutomatedTesting/sounds/wwise_project/Game Parameters/Factory Motion.wwu index b06d283012..3989d74308 100644 --- a/AutomatedTesting/sounds/wwise_project/Game Parameters/Factory Motion.wwu +++ b/AutomatedTesting/sounds/wwise_project/Game Parameters/Factory Motion.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Game Parameters/Factory SoundSeed Air Game Syncs.wwu b/AutomatedTesting/sounds/wwise_project/Game Parameters/Factory SoundSeed Air Game Syncs.wwu index 049dacb51e..efe69cb1a8 100644 --- a/AutomatedTesting/sounds/wwise_project/Game Parameters/Factory SoundSeed Air Game Syncs.wwu +++ b/AutomatedTesting/sounds/wwise_project/Game Parameters/Factory SoundSeed Air Game Syncs.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Interactive Music Hierarchy/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Interactive Music Hierarchy/Default Work Unit.wwu index 1086c4511f..e8f4d23bb6 100644 --- a/AutomatedTesting/sounds/wwise_project/Interactive Music Hierarchy/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Interactive Music Hierarchy/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Master-Mixer Hierarchy/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Master-Mixer Hierarchy/Default Work Unit.wwu index a627ce106e..b6c14df7af 100644 --- a/AutomatedTesting/sounds/wwise_project/Master-Mixer Hierarchy/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Master-Mixer Hierarchy/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + @@ -9,13 +9,15 @@ + - + + diff --git a/AutomatedTesting/sounds/wwise_project/Metadata/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Metadata/Default Work Unit.wwu new file mode 100644 index 0000000000..0317c70b7c --- /dev/null +++ b/AutomatedTesting/sounds/wwise_project/Metadata/Default Work Unit.wwu @@ -0,0 +1,6 @@ + + + + + + diff --git a/AutomatedTesting/sounds/wwise_project/Mixing Sessions/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Mixing Sessions/Default Work Unit.wwu index 8c62ef9009..c24440febd 100644 --- a/AutomatedTesting/sounds/wwise_project/Mixing Sessions/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Mixing Sessions/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Modulators/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Modulators/Default Work Unit.wwu index 062f9f80df..dc16200be3 100644 --- a/AutomatedTesting/sounds/wwise_project/Modulators/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Modulators/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Presets/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Presets/Default Work Unit.wwu index 2bed1c6613..07f7565980 100644 --- a/AutomatedTesting/sounds/wwise_project/Presets/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Presets/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Presets/Factory Reflect.wwu b/AutomatedTesting/sounds/wwise_project/Presets/Factory Reflect.wwu index 53f828f459..8138f5bcdd 100644 --- a/AutomatedTesting/sounds/wwise_project/Presets/Factory Reflect.wwu +++ b/AutomatedTesting/sounds/wwise_project/Presets/Factory Reflect.wwu @@ -1,5 +1,5 @@ - + @@ -19,6 +19,7 @@ + diff --git a/AutomatedTesting/sounds/wwise_project/Presets/Factory Spatial Audio.wwu b/AutomatedTesting/sounds/wwise_project/Presets/Factory Spatial Audio.wwu index 5b96bd3b29..d73cf8d8c3 100644 --- a/AutomatedTesting/sounds/wwise_project/Presets/Factory Spatial Audio.wwu +++ b/AutomatedTesting/sounds/wwise_project/Presets/Factory Spatial Audio.wwu @@ -1,5 +1,5 @@ - + @@ -17,6 +17,7 @@ + diff --git a/AutomatedTesting/sounds/wwise_project/Queries/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Queries/Default Work Unit.wwu index f4e9f99aa4..ff80573330 100644 --- a/AutomatedTesting/sounds/wwise_project/Queries/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Queries/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Queries/Factory Queries.wwu b/AutomatedTesting/sounds/wwise_project/Queries/Factory Queries.wwu index 527315de63..813983d789 100644 --- a/AutomatedTesting/sounds/wwise_project/Queries/Factory Queries.wwu +++ b/AutomatedTesting/sounds/wwise_project/Queries/Factory Queries.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/SoundBanks/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/SoundBanks/Default Work Unit.wwu index da8fa90010..c12261ab5b 100644 --- a/AutomatedTesting/sounds/wwise_project/SoundBanks/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/SoundBanks/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Soundcaster Sessions/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Soundcaster Sessions/Default Work Unit.wwu index d6b8329537..379bf37da9 100644 --- a/AutomatedTesting/sounds/wwise_project/Soundcaster Sessions/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Soundcaster Sessions/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/States/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/States/Default Work Unit.wwu index f27a0d0310..b06937baa9 100644 --- a/AutomatedTesting/sounds/wwise_project/States/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/States/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Switches/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Switches/Default Work Unit.wwu index 49c00bc378..37fb0b424c 100644 --- a/AutomatedTesting/sounds/wwise_project/Switches/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Switches/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Triggers/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Triggers/Default Work Unit.wwu index 3b2e2634df..bb2a827d79 100644 --- a/AutomatedTesting/sounds/wwise_project/Triggers/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Triggers/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Virtual Acoustics/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Virtual Acoustics/Default Work Unit.wwu index 29c26cbbab..d10d9475dc 100644 --- a/AutomatedTesting/sounds/wwise_project/Virtual Acoustics/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Virtual Acoustics/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Virtual Acoustics/Factory Reflect Acoustic Textures.wwu b/AutomatedTesting/sounds/wwise_project/Virtual Acoustics/Factory Reflect Acoustic Textures.wwu index 864f6ba959..ca4a1ae8f2 100644 --- a/AutomatedTesting/sounds/wwise_project/Virtual Acoustics/Factory Reflect Acoustic Textures.wwu +++ b/AutomatedTesting/sounds/wwise_project/Virtual Acoustics/Factory Reflect Acoustic Textures.wwu @@ -1,5 +1,5 @@ - + diff --git a/Gems/AudioEngineWwise/Code/CMakeLists.txt b/Gems/AudioEngineWwise/Code/CMakeLists.txt index dfd9ae6e24..5ea6a6d461 100644 --- a/Gems/AudioEngineWwise/Code/CMakeLists.txt +++ b/Gems/AudioEngineWwise/Code/CMakeLists.txt @@ -18,10 +18,15 @@ set(AUDIOENGINEWWISE_COMPILEDEFINITIONS $,WWISE_RELEASE,ENABLE_AUDIO_LOGGING> ) +find_package(Wwise MODULE) +if (NOT Wwise_FOUND) + message(STATUS "** Update the LY_WWISE_INSTALL_PATH cache variable if you intend to use Wwise.") +endif() + ################################################################################ # Server / Unsupported ################################################################################ -if (PAL_TRAIT_BUILD_SERVER_SUPPORTED OR PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB) +if (PAL_TRAIT_BUILD_SERVER_SUPPORTED OR PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB OR NOT Wwise_FOUND) # Stub gem for server and unsupported platforms. Audio Engine Wwise is client only ly_add_target( NAME AudioEngineWwise.Stub ${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE} @@ -34,11 +39,17 @@ if (PAL_TRAIT_BUILD_SERVER_SUPPORTED OR PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB) ) endif() -if (PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB) - add_library(Gem::AudioEngineWwise ALIAS AudioEngineWwise.Stub) #setup an alias so the stub will be used if something references AudioEngineWwise +if (PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB OR NOT Wwise_FOUND) + # setup aliases so stubs will be used if something references AudioEngineWwise(.Editor) + add_library(Gem::AudioEngineWwise ALIAS AudioEngineWwise.Stub) + add_library(Gem::AudioEngineWwise.Editor ALIAS AudioEngineWwise.Stub) return() endif() + +################################################################################ +# Runtime / Game +################################################################################ ly_add_target( NAME AudioEngineWwise.Static STATIC NAMESPACE Gem @@ -165,7 +176,7 @@ if (PAL_TRAIT_BUILD_TESTS_SUPPORTED) TARGETS ${testTargets} FILES - ${CMAKE_CURRENT_SOURCE_DIR}/Tests/Sounds//wwise/soundbanks/init.bnk + ${CMAKE_CURRENT_SOURCE_DIR}/Tests/Sounds/wwise/soundbanks/init.bnk OUTPUT_SUBDIRECTORY Test.Assets/Gems/AudioEngineWwise/sounds/wwise/soundbanks ) @@ -173,7 +184,7 @@ if (PAL_TRAIT_BUILD_TESTS_SUPPORTED) endif() ################################################################################ -# Editor +# Tools / Editor ################################################################################ if (PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( @@ -199,7 +210,6 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME AudioEngineWwise.Editor GEM_MODULE - NAMESPACE Gem FILES_CMAKE audioenginewwise_editor_shared_files.cmake diff --git a/Gems/AudioEngineWwise/Code/Platform/Android/PAL_android.cmake b/Gems/AudioEngineWwise/Code/Platform/Android/PAL_android.cmake index 69420d8aca..9600a0a2cb 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Android/PAL_android.cmake +++ b/Gems/AudioEngineWwise/Code/Platform/Android/PAL_android.cmake @@ -9,4 +9,4 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB TRUE) +set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB FALSE) diff --git a/Gems/AudioEngineWwise/Code/Platform/Linux/PAL_linux.cmake b/Gems/AudioEngineWwise/Code/Platform/Linux/PAL_linux.cmake index 69420d8aca..9600a0a2cb 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Linux/PAL_linux.cmake +++ b/Gems/AudioEngineWwise/Code/Platform/Linux/PAL_linux.cmake @@ -9,4 +9,4 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB TRUE) +set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB FALSE) diff --git a/Gems/AudioEngineWwise/Code/Platform/Mac/PAL_mac.cmake b/Gems/AudioEngineWwise/Code/Platform/Mac/PAL_mac.cmake index 69420d8aca..9600a0a2cb 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Mac/PAL_mac.cmake +++ b/Gems/AudioEngineWwise/Code/Platform/Mac/PAL_mac.cmake @@ -9,4 +9,4 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB TRUE) +set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB FALSE) diff --git a/Gems/AudioEngineWwise/Code/Platform/Windows/AudioSystemImpl_wwise_Windows.cpp b/Gems/AudioEngineWwise/Code/Platform/Windows/AudioSystemImpl_wwise_Windows.cpp index b6ae569e30..2cf8acba9c 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Windows/AudioSystemImpl_wwise_Windows.cpp +++ b/Gems/AudioEngineWwise/Code/Platform/Windows/AudioSystemImpl_wwise_Windows.cpp @@ -25,8 +25,6 @@ namespace Audio void SetupAkSoundEngine(AkPlatformInitSettings& platformInitSettings) { - // Turn off XAudio2 output type due to rare startup crashes. Prefers WASAPI or DirectSound. - platformInitSettings.eAudioAPI = static_cast(platformInitSettings.eAudioAPI & ~AkAPI_XAudio2); platformInitSettings.threadBankManager.dwAffinityMask = 0; platformInitSettings.threadLEngine.dwAffinityMask = 0; platformInitSettings.threadMonitor.dwAffinityMask = 0; diff --git a/Gems/AudioEngineWwise/Code/Platform/Windows/PAL_windows.cmake b/Gems/AudioEngineWwise/Code/Platform/Windows/PAL_windows.cmake index 69420d8aca..9600a0a2cb 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Windows/PAL_windows.cmake +++ b/Gems/AudioEngineWwise/Code/Platform/Windows/PAL_windows.cmake @@ -9,4 +9,4 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB TRUE) +set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB FALSE) diff --git a/Gems/AudioEngineWwise/Code/Platform/iOS/PAL_ios.cmake b/Gems/AudioEngineWwise/Code/Platform/iOS/PAL_ios.cmake index 69420d8aca..9600a0a2cb 100644 --- a/Gems/AudioEngineWwise/Code/Platform/iOS/PAL_ios.cmake +++ b/Gems/AudioEngineWwise/Code/Platform/iOS/PAL_ios.cmake @@ -9,4 +9,4 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB TRUE) +set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB FALSE) diff --git a/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp b/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp index 2e11c7a810..6fb21964a3 100644 --- a/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp +++ b/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp @@ -66,12 +66,18 @@ namespace Audio { void* Malloc(AkMemPoolId memId, size_t size) { - return AZ::AllocatorInstance::Get().Allocate(size, 0, 0, MemoryManagerCategories[memId & AkMemID_MASK]); + size_t memCategory = memId & AkMemID_MASK; + AZ_Assert(memCategory < AkMemID_NUM, "Wwise::MemHooks::Malloc - Bad AkMemPoolId passed: %zu", memCategory); + return AZ::AllocatorInstance::Get().Allocate(size, 0, 0, + (memCategory < AkMemID_NUM) ? MemoryManagerCategories[memCategory] : nullptr); } void* Malign(AkMemPoolId memId, size_t size, AkUInt32 alignment) { - return AZ::AllocatorInstance::Get().Allocate(size, alignment, 0, MemoryManagerCategories[memId & AkMemID_MASK]); + size_t memCategory = memId & AkMemID_MASK; + AZ_Assert(memCategory < AkMemID_NUM, "WWise::MemHooks::Malign - Bad AkMemPoolId passed: %zu", memCategory); + return AZ::AllocatorInstance::Get().Allocate(size, alignment, 0, + (memCategory < AkMemID_NUM) ? MemoryManagerCategories[memCategory] : nullptr); } void* Realloc([[maybe_unused]] AkMemPoolId memId, void* address, size_t size) @@ -79,12 +85,12 @@ namespace Audio return AZ::AllocatorInstance::Get().ReAllocate(address, size, 0); } - void Free([[maybe_unused]] AkMemPoolId memId, void* address) + void* ReallocAligned([[maybe_unused]] AkMemPoolId memId, void* address, size_t size, AkUInt32 alignment) { - AZ::AllocatorInstance::Get().DeAllocate(address); + return AZ::AllocatorInstance::Get().ReAllocate(address, size, alignment); } - void Falign([[maybe_unused]] AkMemPoolId memId, void* address) + void Free([[maybe_unused]] AkMemPoolId memId, void* address) { AZ::AllocatorInstance::Get().DeAllocate(address); } @@ -427,8 +433,8 @@ namespace Audio akMemSettings.pfMalloc = Wwise::MemHooks::Malloc; akMemSettings.pfMalign = Wwise::MemHooks::Malign; akMemSettings.pfRealloc = Wwise::MemHooks::Realloc; + akMemSettings.pfReallocAligned = Wwise::MemHooks::ReallocAligned; akMemSettings.pfFree = Wwise::MemHooks::Free; - akMemSettings.pfFalign = Wwise::MemHooks::Falign; akMemSettings.pfTotalReservedMemorySize = Wwise::MemHooks::TotalReservedMemorySize; akMemSettings.pfSizeOfMemory = Wwise::MemHooks::SizeOfMemory; akMemSettings.uMemAllocationSizeLimit = Wwise::Cvars::s_PrimaryMemorySize << 10; diff --git a/Gems/AudioEngineWwise/Code/Source/Engine/Common_wwise.h b/Gems/AudioEngineWwise/Code/Source/Engine/Common_wwise.h index 2e806a80e9..25e6a22d84 100644 --- a/Gems/AudioEngineWwise/Code/Source/Engine/Common_wwise.h +++ b/Gems/AudioEngineWwise/Code/Source/Engine/Common_wwise.h @@ -91,8 +91,9 @@ namespace Audio // See AkMemoryMgr.h inline static const char* MemoryManagerCategories[] { - "Object", "Event", "Structure", "Media", "GameObject", "Processing", "ProcessingPlugin", "Streaming", "StreamingIO", "SpatialAudio", - "SpatialAudioGeometry", "SpatialAudioPaths", "GameSim", "MonitorQueue", "Profiler", "FilePackage", "SoundEngine" + "Object", "Event", "Structure", "Media", "GameObject", "Processing", "ProcessingPlugin", "Streaming", "StreamingIO", + "SpatialAudio", "SpatialAudioGeometry", "SpatialAudioPaths", "GameSim", "MonitorQueue", "Profiler", "FilePackage", + "SoundEngine", "Integration" }; static_assert(AZ_ARRAY_SIZE(MemoryManagerCategories) == AkMemID_NUM, diff --git a/Gems/AudioEngineWwise/Tools/WwiseAuthoringScripts/ly_copy_output_and_generate_metadata.wcmdline b/Gems/AudioEngineWwise/Tools/WwiseAuthoringScripts/ly_copy_output_and_generate_metadata.wcmdline index 5d2394fae2..3cc868384b 100644 --- a/Gems/AudioEngineWwise/Tools/WwiseAuthoringScripts/ly_copy_output_and_generate_metadata.wcmdline +++ b/Gems/AudioEngineWwise/Tools/WwiseAuthoringScripts/ly_copy_output_and_generate_metadata.wcmdline @@ -1,3 +1,3 @@ -"$(WwiseExePath)\CopyStreamedFiles.exe" -info "$(InfoFilePath)" -outputpath "$(SoundBankPath)" -banks "$(SoundBankListAsTextFile)" -languages "$(LanguageList)" -"$(WwiseProjectPath)\..\..\..\python.cmd" "$(WwiseProjectPath)\..\..\..\Gems\AudioEngineWwise\Tools\WwiseAuthoringScripts\bank_info_parser.py" "$(InfoFilePath)" "$(SoundBankPath)" +"$(CopyStreamedFilesExePath)" -info "$(InfoFilePath)" -outputpath "$(SoundBankPath)" -banks "$(SoundBankListAsTextFile)" -languages "$(LanguageList)" +"$(WwiseProjectPath)\..\..\..\python\python.cmd" "$(WwiseProjectPath)\..\..\..\Gems\AudioEngineWwise\Tools\WwiseAuthoringScripts\bank_info_parser.py" "$(InfoFilePath)" "$(SoundBankPath)" diff --git a/cmake/3rdParty/FindWwise.cmake b/cmake/3rdParty/FindWwise.cmake index 27b78695f2..9b46c24d75 100644 --- a/cmake/3rdParty/FindWwise.cmake +++ b/cmake/3rdParty/FindWwise.cmake @@ -9,6 +9,59 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# The current supported version of Wwise +set(WWISE_VERSION 2021.1.1.7601) + +# Wwise Install Path +# Initialize to the default 3rdParty path +set(LY_WWISE_INSTALL_PATH "" CACHE PATH "Path to Wwise version ${WWISE_VERSION} installation.") + +function(is_valid_sdk sdk_path is_valid) + set(${is_valid} FALSE PARENT_SCOPE) + if(EXISTS ${sdk_path}) + set(sdk_version_file ${sdk_path}/SDK/include/AK/AkWwiseSDKVersion.h) + if(EXISTS ${sdk_version_file}) + string(FIND ${sdk_path} ${WWISE_VERSION} index) + if(NOT index EQUAL -1) + set(${is_valid} TRUE PARENT_SCOPE) + else() + # The install path doesn't contain the WWISE_VERSION string. + # The path could still be correct, but it would require parsing the AkWwiseSDKVersion.h to verify. + endif() + endif() + endif() +endfunction() + +# Paths that will be checked, in order: +# - CMake cache variable +# - WWISEROOT Environment Variable +# - Standard 3rdParty path +set(WWISE_SDK_PATHS + "${LY_WWISE_INSTALL_PATH}" + "$ENV{WWISEROOT}" + "${LY_3RDPARTY_PATH}/Wwise/${WWISE_VERSION}" +) + +set(found_sdk FALSE) +foreach(test_path ${WWISE_SDK_PATHS}) + is_valid_sdk(${test_path} found_sdk) + if(found_sdk) + # Update the Wwise Install Path cache variable + set(LY_WWISE_INSTALL_PATH "${test_path}" CACHE PATH "Path to Wwise version ${WWISE_VERSION} installation." FORCE) + break() + endif() +endforeach() + +if(NOT found_sdk) + # If we don't find a path that appears to be a valid Wwise install, we can bail here. + # No 3rdParty::Wwise target will exist, so that can be checked elsewhere. + message(STATUS "Wwise SDK version ${WWISE_VERSION} was not found.") + return() +else() + message(STATUS "Using Wwise SDK at ${LY_WWISE_INSTALL_PATH}") +endif() + + set(WWISE_COMMON_LIB_NAMES # Core AK AkMemoryMgr @@ -55,44 +108,26 @@ set(WWISE_NON_RELEASE_LIB_NAMES CommunicationCentral ) -# Additional Libraries -# These can be added/enabled to the linker depending on what your Wwise project uses. -# In addition to uncommenting the libraries here, be sure to add the appropriate plugin factory -# header includes to PluginRegistration_wwise.h. - set(WWISE_ADDITIONAL_LIB_NAMES -# Common - #AkConvolutionReverbFX - #AkReflectFX - #AkRouterMixerFX - #ResonanceAudioFX - #MasteringSuiteFX - #AkSoundSeedImpactFX - #AkSoundSeedGrainSource - #AkSoundSeedWindSource - #AkSoundSeedWooshSource - #AuroHeadphoneFX - #CrankcaseAudioREVModelPlayerSource - #McDSPFutzBoxFX - #McDSPLimiterFX - -# iZotope - #iZHybridReverbFX - #iZTrashBoxModelerFX - #iZTrashDelayFX - #iZTrashDistortionFX - #iZTrashDynamicsFX - #iZTrashFiltersFX - #iZTrashMultibandDistortionFX + # Additional Libraries ) set(WWISE_COMPILE_DEFINITIONS $,AK_OPTIMIZED,> ) + +# The default install path might look different than the standard 3rdParty format (${LY_3RDPARTY_PATH}//). +# Use these to get the parent path and folder name before adding the external 3p target. +get_filename_component(WWISE_3P_ROOT ${LY_WWISE_INSTALL_PATH} DIRECTORY) +get_filename_component(WWISE_FOLDER ${LY_WWISE_INSTALL_PATH} NAME) + ly_add_external_target( NAME Wwise - VERSION 2019.2.8.7432 + VERSION "${WWISE_FOLDER}" + 3RDPARTY_ROOT_DIRECTORY "${WWISE_3P_ROOT}" INCLUDE_DIRECTORIES SDK/include COMPILE_DEFINITIONS ${WWISE_COMPILE_DEFINITIONS} ) + +set(Wwise_FOUND TRUE) diff --git a/cmake/3rdParty/Platform/Android/Wwise_android.cmake b/cmake/3rdParty/Platform/Android/Wwise_android.cmake index 5d7713511b..d204688489 100644 --- a/cmake/3rdParty/Platform/Android/Wwise_android.cmake +++ b/cmake/3rdParty/Platform/Android/Wwise_android.cmake @@ -10,9 +10,6 @@ # set(WWISE_ANDROID_LIB_NAMES - AkMotionGeneratorSource - AkMotionSink - AkMotionSourceSource zip ) diff --git a/cmake/3rdParty/Platform/Windows/Wwise_windows.cmake b/cmake/3rdParty/Platform/Windows/Wwise_windows.cmake index 37141f7e6d..09b9478ac0 100644 --- a/cmake/3rdParty/Platform/Windows/Wwise_windows.cmake +++ b/cmake/3rdParty/Platform/Windows/Wwise_windows.cmake @@ -10,16 +10,11 @@ # set(WWISE_WINDOWS_LIB_NAMES - ASIOSourceSink AkAutobahn - AkMotionGeneratorSource - AkMotionSink - AkMotionSourceSource - MSSpatialSink SFLib ) -set(WWISE_VS_VER "vc150") # use the version of Wwise built with MSVC2017, or toolset 141 +set(WWISE_VS_VER "vc160") set(WWISE_LIB_PATH ${BASE_PATH}/SDK/x64_${WWISE_VS_VER}/$,Debug,$,Profile,Release>>/lib) From 21dfcfed74ed657656c2d67ccda70a871b6bfd24 Mon Sep 17 00:00:00 2001 From: mbalfour Date: Tue, 11 May 2021 15:26:07 -0500 Subject: [PATCH 059/100] Fix bug where setting autoLoad to false for one gem will prevent every gem after it from loading as well. --- Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp index daf5b5efd2..b2fe4417d3 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp @@ -1304,7 +1304,7 @@ namespace AZ // Add all auto loadable non-asset gems to the list of gem modules to load if (!moduleLoadData.m_autoLoad) { - break; + continue; } for (AZ::OSString& dynamicLibraryPath : moduleLoadData.m_dynamicLibraryPaths) { From fe24f37a705738160a657bd22b4fe5c011e0f01e Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Tue, 11 May 2021 15:34:31 -0500 Subject: [PATCH 060/100] Fixing up null.builder loading issue --- Gems/Atom/RHI/Null/Code/CMakeLists.txt | 2 +- Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt | 9 --------- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/Gems/Atom/RHI/Null/Code/CMakeLists.txt b/Gems/Atom/RHI/Null/Code/CMakeLists.txt index 1b88e72648..be1c5d22aa 100644 --- a/Gems/Atom/RHI/Null/Code/CMakeLists.txt +++ b/Gems/Atom/RHI/Null/Code/CMakeLists.txt @@ -89,7 +89,7 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) ) ly_add_target( - NAME Atom_RHI_Null.Builders MODULE + NAME Atom_RHI_Null.Builders GEM_MODULE NAMESPACE Gem FILES_CMAKE atom_rhi_null_builders_shared_files.cmake diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt index 06b4e2a7fe..33873e0dfa 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt +++ b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt @@ -104,14 +104,5 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Gem::ImguiAtom Gem::AtomFont Gem::AtomToolsFramework.Editor - - # Testing jenkins issue - Gem::Atom_RHI_Vulkan.Private - Gem::Atom_RHI_Vulkan.Builders - Gem::Atom_RHI_DX12.Private - Gem::Atom_RHI_DX12.Builders - Gem::Atom_RHI_Null.Private - Gem::Atom_RHI_Null.Builders - Gem::Atom_RHI_Metal.Builders ) endif() From 5440d0926d432e8d59ea3a44a890c25a776783ea Mon Sep 17 00:00:00 2001 From: karlberg Date: Tue, 11 May 2021 13:42:44 -0700 Subject: [PATCH 061/100] Fixing some dependencies in script canvas and emfx --- .../Components/AnimGraphNetSyncComponent.cpp | 448 ------------------ .../Components/AnimGraphNetSyncComponent.h | 153 ------ .../Components/AnimGraphNetSyncTypes.h | 285 ----------- .../Integration/System/AnimationModule.cpp | 3 - .../Code/emotionfx_shared_files.cmake | 3 - .../Execution/RuntimeComponent.cpp | 4 - .../ScriptCanvas/Execution/RuntimeComponent.h | 9 +- .../Variable/GraphVariableMarshal.cpp | 245 ---------- .../Variable/GraphVariableMarshal.h | 86 ---- .../Variable/GraphVariableNetBindings.cpp | 181 ------- .../Variable/GraphVariableNetBindings.h | 101 ---- .../Code/scriptcanvasgem_common_files.cmake | 4 - 12 files changed, 1 insertion(+), 1521 deletions(-) delete mode 100644 Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncComponent.cpp delete mode 100644 Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncComponent.h delete mode 100644 Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncTypes.h delete mode 100644 Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableMarshal.cpp delete mode 100644 Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableMarshal.h delete mode 100644 Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableNetBindings.cpp delete mode 100644 Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableNetBindings.h diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncComponent.cpp deleted file mode 100644 index 904f500018..0000000000 --- a/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncComponent.cpp +++ /dev/null @@ -1,448 +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 "EMotionFX_precompiled.h" -#include -#include -#include -#include -#include -#include - -namespace EMotionFX -{ - namespace Integration - { - namespace Network - { - /** - * \brief This is a GridMate chunk that replicates Anim Graph parameters. - * It's challenge is to replicate any of the supported parameter types where - * the types are only known at runtime. To solve that, many datasets are created - * with helper macros to avoid code duplication (@PARAM_DATASET and @PARAM_DATASET_NAME). - * - * For maximum compression, one should build a custom component that specifies the anim graph parameters by hand, for example: - * - * DataSet m_param0; - * - * or if using delta compression feature of GridMate: - * - * DeltaCompressedDataSet m_param1; - * - * Active nodes (@m_activeNodes) change infrequently. - * - * Warning: @m_motionNodes motion nodes often do change frequently as their motion play time ticks down. - * Care must be applied when aiming for the network budget of a project. - */ - class AnimGraphNetSyncComponent::Chunk : public GridMate::ReplicaChunkBase - { - public: - GM_CLASS_ALLOCATOR(Chunk); - - Chunk() : m_activeNodes("Active Nodes", NodeIndexContainer{}), m_motionNodes("Motion Nodes", MotionNodePlaytimeContainer{}) {} - - static const char* GetChunkName() { return "AnimGraphNetSyncComponent::Chunk"; } - bool IsReplicaMigratable() override { return true; } - - using AnimDataSetType = GridMate::DataSet; - - template - using AnimDataSet = AnimDataSetType::BindInterface; - - // A helper macro that creates a variable like this one: - // AnimDataSet<&AnimGraphNetSyncComponent::OnAnimParameterChanged<0>> m_parameter0 = { "Param 0" }; - #define PARAM_DATASET( N ) AnimDataSet<&AnimGraphNetSyncComponent::OnAnimParameterChanged< N >> m_parameter##N = { "Param " #N } - - PARAM_DATASET(0); - PARAM_DATASET(1); - PARAM_DATASET(2); - PARAM_DATASET(3); - PARAM_DATASET(4); - PARAM_DATASET(5); - PARAM_DATASET(6); - PARAM_DATASET(7); - PARAM_DATASET(8); - PARAM_DATASET(9); - - /* - * Note: GridMate by default supports up to 32 DataSets per ReplicaChunk: @GM_MAX_DATASETS_IN_CHUNK. - * That means that a component can sync up to 32 separate network fields. One can vary the number of supported number - * of parameters by simply creating new entries of @PARAM_DATASET above and @PARAM_DATASET_NAME below. - */ - - // A collection of datasets that are used to synchronize anim graph parameters. - AZStd::array m_parameters = { { // clang pre-6.0 requires double "{{" here but doesn't perform compile length verification :( - &m_parameter0, - &m_parameter1, - &m_parameter2, - &m_parameter3, - &m_parameter4, - &m_parameter5, - &m_parameter6, - &m_parameter7, - &m_parameter8, - &m_parameter9, - } }; - - GridMate::DataSet:: - BindInterface m_activeNodes; - GridMate::DataSet:: - BindInterface m_motionNodes; - }; - - void AnimGraphNetSyncComponent::Reflect(AZ::ReflectContext* context) - { - GridMate::ReplicaChunkDescriptorTable& descTable = GridMate::ReplicaChunkDescriptorTable::Get(); - if (!descTable.FindReplicaChunkDescriptor(GridMate::ReplicaChunkClassId(Chunk::GetChunkName()))) - { - descTable.RegisterChunkType(); - } - - AZ::SerializeContext* serializeContext = azrtti_cast(context); - if (serializeContext) - { - serializeContext->Class() - ->Version(1) - ->Field( "Sync parameters", &AnimGraphNetSyncComponent::m_syncParameters ) - ->Field( "Sync active nodes", &AnimGraphNetSyncComponent::m_syncActiveNodes ) - ->Field( "Sync motion nodes", &AnimGraphNetSyncComponent::m_syncMotionNodes ) - ; - - AZ::EditContext* editContent = serializeContext->GetEditContext(); - if (editContent) - { - editContent->Class("Anim Graph Net Sync", - "Replicates anim graph parameters over the network using GridMate") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) - ->Attribute(AZ::Edit::Attributes::Category, "Networking") - ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/AnimGraphNetSync.svg") - ->DataElement( AZ::Edit::UIHandlers::Default, &AnimGraphNetSyncComponent::m_syncParameters, "Sync parameters", - "Synchronize parameters of the anim graph on the entity" ) - ->DataElement( AZ::Edit::UIHandlers::Default, &AnimGraphNetSyncComponent::m_syncActiveNodes, "Sync active nodes", - "Synchronize active nodes in the anim graph on the entity" ) - ->DataElement( AZ::Edit::UIHandlers::Default, &AnimGraphNetSyncComponent::m_syncMotionNodes, "Sync motion nodes", - "Synchronize motion nodes in the anim graph on the entity. Warning: this may take a significant amount of network bandwidth" ) - ; - } - } - } - - void AnimGraphNetSyncComponent::Activate() - { - AnimGraphComponentNotificationBus::Handler::BusConnect(GetEntityId()); - - if (m_syncMotionNodes || m_syncActiveNodes) // if there is anything synchronize over the network - { - const bool isAuthoritative = AzFramework::NetQuery::IsEntityAuthoritative(GetEntityId()); - if (isAuthoritative) - { - // Only the server (or authoritative entity) needs to watch the nodes values. - AZ::TickBus::Handler::BusConnect(); - } - - // We need to get anim graph instance. It will be either available to us now or later via a notification bus. See @OnAnimGraphInstanceCreated - AnimGraphComponentRequestBus::EventResult(m_instance, GetEntityId(), &AnimGraphComponentRequestBus::Events::GetAnimGraphInstance); - if (m_instance) - { - if (!m_instance->GetSnapshot()) - { - m_instance->CreateSnapshot(isAuthoritative); - } - } - } - } - - void AnimGraphNetSyncComponent::Deactivate() - { - AnimGraphComponentNotificationBus::Handler::BusDisconnect(); - AZ::TickBus::Handler::BusDisconnect(); - } - - void AnimGraphNetSyncComponent::SetParameterOnClient(const AnimParameter& value, AZ::u8 index) - { - switch (value.m_type) - { - case AnimParameter::Type::Unsupported: - break; - case AnimParameter::Type::Float: - AnimGraphComponentRequestBus::Event(GetEntityId(), &AnimGraphComponentRequestBus::Events::SetParameterFloat, index, value.m_value.f); - break; - case AnimParameter::Type::Bool: - AnimGraphComponentRequestBus::Event(GetEntityId(), &AnimGraphComponentRequestBus::Events::SetParameterBool, index, value.m_value.b); - break; - case AnimParameter::Type::Vector2: - AnimGraphComponentRequestBus::Event(GetEntityId(), &AnimGraphComponentRequestBus::Events::SetParameterVector2, index, value.m_value.v2); - break; - case AnimParameter::Type::Vector3: - AnimGraphComponentRequestBus::Event(GetEntityId(), &AnimGraphComponentRequestBus::Events::SetParameterVector3, index, value.m_value.v3); - break; - case AnimParameter::Type::Quaternion: - AnimGraphComponentRequestBus::Event(GetEntityId(), &AnimGraphComponentRequestBus::Events::SetParameterRotation, index, value.m_value.q); - break; - default: - AZ_Assert(false, "Unsupported type"); - break; - } - } - - template - void AnimGraphNetSyncComponent::OnAnimParameterChanged(const AnimParameter& value, const GridMate::TimeContext&) - { - SetParameterOnClient(value, Index); - } - - template - void AnimGraphNetSyncComponent::SetParameterOnServer(AZ::u8 parameterIndex, const FieldType& newValue) - { - if (m_syncParameters) - { - if (Chunk* chunk = GetChunk()) - { - if (parameterIndex < chunk->m_parameters.size()) - { - AnimParameter param; - param.m_type = AnimParameterType; - - static_assert(sizeof(FieldType) <= sizeof(param.m_value), "The largest value param.m_value can store is a Quaternion"); - // This is to simplify writing a value into a union. - // Ideally, one would use std::variant (C++17) instead of a union. - memcpy(¶m.m_value, &newValue, sizeof(FieldType)); - - chunk->m_parameters[parameterIndex]->Set(param); - } - else - { - AZ_Warning("EMotionFX", false, "AnimGraphNetSyncComponent does not support synchronizing more than %u parameters", chunk->m_parameters.size()); - } - } - } - } - - void AnimGraphNetSyncComponent::OnAnimGraphFloatParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - float beforeValue, - float afterValue) - { - AZ_UNUSED(beforeValue); - SetParameterOnServer(static_cast(parameterIndex), afterValue); - } - - void AnimGraphNetSyncComponent::OnAnimGraphBoolParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - bool beforeValue, - bool afterValue) - { - AZ_UNUSED(beforeValue); - SetParameterOnServer(static_cast(parameterIndex), afterValue); - } - - void AnimGraphNetSyncComponent::OnAnimGraphStringParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - const char* beforeValue, - const char* afterValue) - { - AZ_UNUSED(parameterIndex); - AZ_UNUSED(beforeValue); - AZ_UNUSED(afterValue); - AZ_Warning("EMotionFX", false, "AnimGraphNetSync component does not supported synchronizing string parameters, please consider refactoring your anim graph to replace strings with integers or enum values."); - } - - void AnimGraphNetSyncComponent::OnAnimGraphVector2ParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - const AZ::Vector2& beforeValue, - const AZ::Vector2& afterValue) - { - AZ_UNUSED(beforeValue); - SetParameterOnServer(static_cast(parameterIndex), afterValue); - } - - void AnimGraphNetSyncComponent::OnAnimGraphVector3ParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - const AZ::Vector3& beforeValue, - const AZ::Vector3& afterValue) - { - AZ_UNUSED(beforeValue); - SetParameterOnServer(static_cast(parameterIndex), afterValue); - } - - void AnimGraphNetSyncComponent::OnAnimGraphRotationParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - const AZ::Quaternion& beforeValue, - const AZ::Quaternion& afterValue) - { - AZ_UNUSED(beforeValue); - SetParameterOnServer(static_cast(parameterIndex), afterValue); - } - - void AnimGraphNetSyncComponent::OnActiveNodesChanged(const NodeIndexContainer& activeNodes, const GridMate::TimeContext& tc) - { - AZ_UNUSED(tc); - // Client receiving values - if (m_instance) - { - if (const AZStd::shared_ptr snapshot = m_instance->GetSnapshot()) - { - snapshot->SetActiveNodes(activeNodes); - } - } - } - - void AnimGraphNetSyncComponent::OnMotionNodesChanged(const MotionNodePlaytimeContainer& motionNodes, const GridMate::TimeContext& tc) - { - AZ_UNUSED(tc); - // Client receiving values - if (m_instance) - { - if (const AZStd::shared_ptr snapshot = m_instance->GetSnapshot()) - { - snapshot->SetMotionNodePlaytimes(motionNodes); - } - } - } - - bool AnimGraphNetSyncComponent::IsDifferent(const MotionNodePlaytimeContainer& oldList, const MotionNodePlaytimeContainer& newList) const - { - if (oldList.size() != newList.size()) - { - return true; - } - - AZStd::size_t i = 0; - for (auto& value : oldList) - { - if (value.first != newList[i].first || value.second != newList[i].second) - { - return true; - } - - ++i; - } - - return false; - } - - bool AnimGraphNetSyncComponent::IsDifferent(const NodeIndexContainer& oldList, const NodeIndexContainer& newList) const - { - if (oldList.size() != newList.size()) - { - return true; - } - - AZStd::size_t i = 0; - for (AZ::u32 value : oldList) - { - if (value != newList[i]) - { - return true; - } - - ++i; - } - - return false; - } - - void AnimGraphNetSyncComponent::OnTick(float deltaTime, AZ::ScriptTimePoint time) - { - AZ_UNUSED(deltaTime); - AZ_UNUSED(time); - - if (!GetChunk()) - { - return; // network is not ready yet - } - - if (m_instance) - { - if (const AZStd::shared_ptr snapshot = m_instance->GetSnapshot()) - { - if (m_syncActiveNodes) - { - const NodeIndexContainer& activeNodes = snapshot->GetActiveNodes(); - const NodeIndexContainer& currentValue = GetChunk()->m_activeNodes.Get(); - if (IsDifferent(currentValue, activeNodes)) - { - GetChunk()->m_activeNodes.Set(activeNodes); // Server sending the values - } - } - - if (m_syncMotionNodes) - { - const MotionNodePlaytimeContainer& playTimes = snapshot->GetMotionNodePlaytimes(); - const MotionNodePlaytimeContainer& currentTimes = GetChunk()->m_motionNodes.Get(); - if (IsDifferent(currentTimes, playTimes)) - { - GetChunk()->m_motionNodes.Set(playTimes); // Server sending the values - } - } - } - } - } - - void AnimGraphNetSyncComponent::OnAnimGraphInstanceCreated(EMotionFX::AnimGraphInstance* instance) - { - m_instance = instance; - if (m_instance) - { - const bool isAuthoritative = AzFramework::NetQuery::IsEntityAuthoritative(GetEntityId()); - if (!m_instance->GetSnapshot()) - { - m_instance->CreateSnapshot(isAuthoritative); - } - } - } - - void AnimGraphNetSyncComponent::OnAnimGraphInstanceDestroyed(EMotionFX::AnimGraphInstance*) - { - m_instance = nullptr; - } - - AnimGraphNetSyncComponent::Chunk* AnimGraphNetSyncComponent::GetChunk() const - { - return static_cast(m_chunk.get()); - } - - GridMate::ReplicaChunkPtr AnimGraphNetSyncComponent::GetNetworkBinding() - { - m_chunk = GridMate::CreateReplicaChunk(); - AZ_Assert(m_chunk, "Failed to create a chunk"); - - if (m_instance) - { - if (!m_instance->GetSnapshot()) - { - m_instance->CreateSnapshot(true /* authoritative */); - } - } - - return m_chunk; - } - - void AnimGraphNetSyncComponent::SetNetworkBinding(GridMate::ReplicaChunkPtr chunk) - { - m_chunk = chunk; - m_chunk->SetHandler(this); - } - - void AnimGraphNetSyncComponent::UnbindFromNetwork() - { - AZ_Assert(m_chunk, "There wasn't any chunk present"); - if (m_chunk) - { - m_chunk->SetHandler(nullptr); - m_chunk = nullptr; - } - } - } - } // namespace Integration -} // namespace EMotionFXAnimation diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncComponent.h b/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncComponent.h deleted file mode 100644 index b6cfc2c795..0000000000 --- a/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncComponent.h +++ /dev/null @@ -1,153 +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 -#include - -namespace EMotionFX -{ - namespace Integration - { - namespace Network - { - /** - * \brief Generic solution for synchronizing parameters of Anim Graph component. - * Synchronization is done over GridMate. - * - * Note that this is not the most optimal synchronization but it does - * work for just about all Anim Graphs. - * - * Disclaimer: string parameters are not supported! Because one should not synchronize - * strings over the network. They ought to be converted to enum/int values beforehand. - */ - class AnimGraphNetSyncComponent - : public AZ::Component - , public AzFramework::NetBindable - , public AnimGraphComponentNotificationBus::Handler - , public AZ::TickBus::Handler - { - public: - AZ_COMPONENT(AnimGraphNetSyncComponent, "{2F9428C1-0F07-4667-B052-40D9BC473AD3}", NetBindable); - - static void Reflect(AZ::ReflectContext* context); - - // AZ::Component interface implementation - void Activate() override; - void Deactivate() override; - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("EMotionFXAnimGraphNetSyncService", 0x42e6f127)); - } - - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("EMotionFXAnimGraphNetSyncService", 0x42e6f127)); - } - - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) - { - required.push_back(AZ_CRC("EMotionFXAnimGraphService", 0x9ec3c819)); - required.push_back(AZ_CRC("ReplicaChunkService", 0xf86b88a8)); - } - - protected: - // NetBindable interface implementation - GridMate::ReplicaChunkPtr GetNetworkBinding() override; - void SetNetworkBinding(GridMate::ReplicaChunkPtr chunk) override; - void UnbindFromNetwork() override; - - // AnimGraphComponentNotificationBus interface implementation - void OnAnimGraphFloatParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - float beforeValue, - float afterValue) override; - void OnAnimGraphBoolParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - bool beforeValue, - bool afterValue) override; - void OnAnimGraphStringParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - const char* beforeValue, - const char* afterValue) override; - void OnAnimGraphVector2ParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - const AZ::Vector2& beforeValue, - const AZ::Vector2& afterValue) override; - void OnAnimGraphVector3ParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - const AZ::Vector3& beforeValue, - const AZ::Vector3& afterValue) override; - void OnAnimGraphRotationParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - const AZ::Quaternion& beforeValue, - const AZ::Quaternion& afterValue) override; - - // TickBus - void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - - // AnimGraphComponentNotificationBus - void OnAnimGraphInstanceCreated(EMotionFX::AnimGraphInstance* instance) override; - void OnAnimGraphInstanceDestroyed(EMotionFX::AnimGraphInstance* instance) override; - - private: - class Chunk; - GridMate::ReplicaChunkPtr m_chunk; - Chunk* GetChunk() const; - - // DataSet callback, it's a template to avoid duplicating similar callbacks - template - void OnAnimParameterChanged(const AnimParameter& value, const GridMate::TimeContext& tc); - - // Helper on a client side - void SetParameterOnClient(const AnimParameter& value, AZ::u8 index); - - // Helper on the server side to avoid duplicating very similar callbacks - template - void SetParameterOnServer(AZ::u8 parameterIndex, const FieldType& newValue); - - /** - * \brief Optionally turn on or off replicating parameters of an anim graph on the same entity as this component. - */ - bool m_syncParameters = true; - - /** - * \brief Optionally turn on or off replicating active nodes of an anim graph on the same entity as this component. - */ - bool m_syncActiveNodes = false; - /** - * \brief Optionally turn on or off replicating motion playtime nodes of an anim graph on the same entity as this component. - * - * It's off by default because these nodes are very frequently changing and would result in a high network bandwidth use. - */ - bool m_syncMotionNodes = false; - - // GridMate DataSet callback on clients - void OnActiveNodesChanged(const NodeIndexContainer& activeNodes, const GridMate::TimeContext& tc); - // GridMate DataSet callback on clients - void OnMotionNodesChanged(const MotionNodePlaytimeContainer& motionNodes, const GridMate::TimeContext& tc); - - // Helper comparison method to avoid sending the same data - bool IsDifferent(const NodeIndexContainer& oldList, const NodeIndexContainer& newList) const; - // Helper comparison method to avoid sending the same data - bool IsDifferent(const MotionNodePlaytimeContainer& oldList, const MotionNodePlaytimeContainer& newList) const; - - EMotionFX::AnimGraphInstance* m_instance = nullptr; - }; - } - } // namespace Integration -} // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncTypes.h b/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncTypes.h deleted file mode 100644 index 9194dc1b65..0000000000 --- a/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncTypes.h +++ /dev/null @@ -1,285 +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 - -namespace EMotionFX -{ - namespace Integration - { - namespace Network - { - /** - * \brief A general storage for an anim graph parameter. - */ - class AnimParameter - { - public: - /** - * \brief String type is not supported because one should not be syncing strings over the network. - */ - enum class Type : AZ::u8 - { - Unsupported, - Float, - Bool, - Vector2, - Vector3, - Quaternion, - }; - - /** - * \brief A storage for all possible supported types in @AnimGraphNetSyncComponent - */ - union Value - { - Value() - { - q = AZ::Quaternion::CreateZero(); - } - - float f; - bool b = false; - AZ::Vector2 v2; - AZ::Vector3 v3; - AZ::Quaternion q; - }; - - AnimParameter() : m_type(Type::Unsupported) {} - - Type m_type; - Value m_value; - - AnimParameter(const AnimParameter& other) - { - m_type = other.m_type; - CopyValue(other); - } - - AnimParameter& operator=(const AnimParameter& other) - { - m_type = other.m_type; - CopyValue(other); - - return *this; - } - - friend bool operator==(const AnimParameter& lhs, const AnimParameter& rhs) - { - if (lhs.m_type != rhs.m_type) - { - return false; - } - - switch (lhs.m_type) - { - case Type::Float: - return lhs.m_value.f == rhs.m_value.f; - case Type::Bool: - return lhs.m_value.b == rhs.m_value.b; - case Type::Vector2: - return lhs.m_value.v2 == rhs.m_value.v2; - case Type::Vector3: - return lhs.m_value.v3 == rhs.m_value.v3; - case Type::Quaternion: - return lhs.m_value.q == rhs.m_value.q; - default: - return true; - } - } - - private: - void CopyValue(const AnimParameter& other) - { - switch (m_type) - { - case Type::Float: - m_value.f = other.m_value.f; - break; - case Type::Bool: - m_value.b = other.m_value.b; - break; - case Type::Vector2: - m_value.v2 = other.m_value.v2; - break; - case Type::Vector3: - m_value.v3 = other.m_value.v3; - break; - case Type::Quaternion: - m_value.q = other.m_value.q; - break; - default: - break; - } - } - }; - - /** - * \brief Custom GridMate throttler. See GridMate:: @BasicThrottle - */ - class AnimParameterThrottler - { - public: - bool WithinThreshold(const AnimParameter& newValue) const - { - return m_baseline == newValue; - } - - void UpdateBaseline(const AnimParameter& baseline) - { - m_baseline = baseline; - } - - private: - AnimParameter m_baseline; - }; - - /** - * \brief A custom GridMate marshaler. - * 1 byte is spend on the type. And a variable number of bytes afterwards for the value. - */ - class AnimParameterMarshaler - { - public: - void Marshal(GridMate::WriteBuffer& wb, const AnimParameter& parameter) - { - wb.Write(AZ::u8(parameter.m_type)); - - switch (parameter.m_type) - { - case AnimParameter::Type::Float: - wb.Write(parameter.m_value.f); - break; - case AnimParameter::Type::Bool: - wb.Write(parameter.m_value.b); - break; - case AnimParameter::Type::Vector2: - wb.Write(parameter.m_value.v2); - break; - case AnimParameter::Type::Vector3: - wb.Write(parameter.m_value.v3); - break; - case AnimParameter::Type::Quaternion: - wb.Write(parameter.m_value.q); - break; - default: - // other types are not supported - break; - } - } - - void Unmarshal(AnimParameter& parameter, GridMate::ReadBuffer& rb) - { - AZ::u8 type; - rb.Read(type); - parameter.m_type = static_cast(type); - - switch (parameter.m_type) - { - case AnimParameter::Type::Float: - rb.Read(parameter.m_value.f); - break; - case AnimParameter::Type::Bool: - rb.Read(parameter.m_value.b); - break; - case AnimParameter::Type::Vector2: - rb.Read(parameter.m_value.v2); - break; - case AnimParameter::Type::Vector3: - rb.Read(parameter.m_value.v3); - break; - case AnimParameter::Type::Quaternion: - rb.Read(parameter.m_value.q); - break; - default: - // other types are not supported - break; - } - } - }; - - /** - * \brief Custom marshaler for Animation node index that is used by Activate Nodes list - */ - struct NodeIndexContainerMarshaler - { - void Marshal(GridMate::WriteBuffer& wb, const NodeIndexContainer& source) const - { - GridMate::VlqU64Marshaler m64; - GridMate::VlqU32Marshaler m32; - - m64.Marshal(wb, source.size()); // 1 byte most of the time (if the size is less than 127) - for (AZ::u32 item : source) - { - m32.Marshal(wb, item); // 1 byte most of the time (if the value is less than 127) - } - } - - void Unmarshal(NodeIndexContainer& target, GridMate::ReadBuffer& rb) const - { - target.clear(); - GridMate::VlqU64Marshaler m64; - GridMate::VlqU32Marshaler m32; - - AZ::u64 arraySize; - m64.Unmarshal(arraySize, rb); - target.resize(arraySize); - - for (AZ::u64 i = 0; i < arraySize; ++i) - { - m32.Unmarshal(target[i], rb); - } - } - }; - - /** - * \brief Custom marshaler for Animation motion node information that is used by motion node playtime list - */ - struct MotionNodePlaytimeContainerMarshaler - { - void Marshal(GridMate::WriteBuffer& wb, const MotionNodePlaytimeContainer& source) const - { - GridMate::VlqU64Marshaler m64; - GridMate::VlqU32Marshaler m32; - - m64.Marshal(wb, source.size()); - for (const AZStd::pair& item : source) - { - m32.Marshal(wb, item.first); // average of 1 byte - wb.Write(item.second); // 4 bytes - } - } - - void Unmarshal(MotionNodePlaytimeContainer& target, GridMate::ReadBuffer& rb) const - { - target.clear(); - GridMate::VlqU64Marshaler m64; - GridMate::VlqU32Marshaler m32; - - AZ::u64 arraySize; - m64.Unmarshal(arraySize, rb); - target.resize(arraySize); - - for (AZ::u64 i = 0; i < arraySize; ++i) - { - m32.Unmarshal(target[i].first, rb); - rb.Read(target[i].second); - } - } - }; - } - } // namespace Integration -} // namespace EMotionFXAnimation diff --git a/Gems/EMotionFX/Code/Source/Integration/System/AnimationModule.cpp b/Gems/EMotionFX/Code/Source/Integration/System/AnimationModule.cpp index 4d7db16133..e5561697fd 100644 --- a/Gems/EMotionFX/Code/Source/Integration/System/AnimationModule.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/System/AnimationModule.cpp @@ -17,7 +17,6 @@ #include #include #include -#include #include #include #include @@ -74,8 +73,6 @@ namespace EMotionFX AnimGraphComponent::CreateDescriptor(), SimpleMotionComponent::CreateDescriptor(), SimpleLODComponent::CreateDescriptor(), - - Network::AnimGraphNetSyncComponent::CreateDescriptor(), #if defined(EMOTIONFXANIMATION_EDITOR) // Pipeline components diff --git a/Gems/EMotionFX/Code/emotionfx_shared_files.cmake b/Gems/EMotionFX/Code/emotionfx_shared_files.cmake index 0c7e4ef0e7..88c6525f91 100644 --- a/Gems/EMotionFX/Code/emotionfx_shared_files.cmake +++ b/Gems/EMotionFX/Code/emotionfx_shared_files.cmake @@ -31,9 +31,6 @@ set(FILES Source/Integration/Components/ActorComponent.cpp Source/Integration/Components/AnimAudioComponent.h Source/Integration/Components/AnimAudioComponent.cpp - Source/Integration/Components/AnimGraphNetSyncComponent.h - Source/Integration/Components/AnimGraphNetSyncTypes.h - Source/Integration/Components/AnimGraphNetSyncComponent.cpp Source/Integration/Components/AnimGraphComponent.h Source/Integration/Components/AnimGraphComponent.cpp Source/Integration/Components/SimpleMotionComponent.h diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.cpp index ba1d34fea0..d5745cf3cc 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.cpp @@ -19,11 +19,9 @@ #include #include #include -#include #include #include #include -#include #if !defined(_RELEASE) && !defined(PERFORMANCE_BUILD) #define SCRIPT_CANVAS_RUNTIME_ASSET_CHECK @@ -163,8 +161,6 @@ namespace ScriptCanvas ->Field("m_variableOverrides", &RuntimeComponent::m_variableOverrides) ; } - - GraphVariableNetBindingTable::Reflect(context); } void RuntimeComponent::SetVariableOverrides(const VariableData& overrideData) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.h index ef90155e41..81f46d27b9 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.h @@ -15,8 +15,6 @@ #include #include -#include - #include #include #include @@ -41,11 +39,10 @@ namespace ScriptCanvas //! This component should only be used at runtime class RuntimeComponent : public AZ::Component - , public AzFramework::NetBindable , public AZ::EntityBus::Handler { public: - AZ_COMPONENT(RuntimeComponent, "{95BFD916-E832-4956-837D-525DE8384282}", NetBindable); + AZ_COMPONENT(RuntimeComponent, "{95BFD916-E832-4956-837D-525DE8384282}", AZ::Component); static void Reflect(AZ::ReflectContext* context); @@ -67,8 +64,6 @@ namespace ScriptCanvas const VariableData& GetVariableOverrides() const; - void SetNetworkBinding(GridMate::ReplicaChunkPtr) {} - void SetVariableOverrides(const VariableData& overrideData); protected: @@ -103,8 +98,6 @@ namespace ScriptCanvas void StopExecution(); - void UnbindFromNetwork(void) {} - private: AZ::Data::Asset m_runtimeAsset; ExecutionStatePtr m_executionState; diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableMarshal.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableMarshal.cpp deleted file mode 100644 index 8d8db1d876..0000000000 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableMarshal.cpp +++ /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. -* -*/ - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ScriptCanvas -{ - void DatumMarshaler::SetNetBindingTable(GraphVariableNetBindingTable* netBindingTable) - { - m_graphVariableNetBindingTable = netBindingTable; - } - - void DatumMarshaler::Marshal(GridMate::WriteBuffer& wb, const Datum* const & property) const - { - if (!property) - { - return; - } - - GridMate::Marshaler typeMarshaler; - const Data::eType& datumType = property->GetType().GetType(); - typeMarshaler.Marshal(wb, datumType); - - VariableId assetVariableId; - AZStd::unordered_map>& variableIdMap = m_graphVariableNetBindingTable->GetVariableIdMap(); - - for (AZStd::pair>& pair : variableIdMap) - { - AZStd::pair& variableIndexPair = pair.second; - - if (variableIndexPair.first->GetDatum() == property) - { - assetVariableId = m_graphVariableNetBindingTable->FindAssetVariableIdByRuntimeVariableId(pair.first); - break; - } - } - - if (!assetVariableId.IsValid()) - { - return; - } - - GridMate::Marshaler uuidMarshaler; - uuidMarshaler.Marshal(wb, assetVariableId.GetDatumId()); - - AZStd::string uuidString = assetVariableId.m_id.ToString(); - - switch (datumType) - { - case Data::eType::AABB: - MarshalType(wb, property); - break; - - case Data::eType::Boolean: - MarshalType(wb, property); - break; - - case Data::eType::Color: - MarshalType(wb, property); - break; - - case Data::eType::CRC: - MarshalType(wb, property); - break; - - case Data::eType::EntityID: - MarshalType(wb, property); - break; - - case Data::eType::Matrix3x3: - MarshalType(wb, property); - break; - - case Data::eType::Matrix4x4: - MarshalType(wb, property); - break; - - case Data::eType::NamedEntityID: - MarshalType(wb, property); - break; - - case Data::eType::Number: - MarshalType(wb, property); - break; - - case Data::eType::OBB: - MarshalType(wb, property); - break; - - case Data::eType::Plane: - MarshalType(wb, property); - break; - - case Data::eType::Quaternion: - MarshalType(wb, property); - break; - - case Data::eType::String: - MarshalType(wb, property); - break; - - case Data::eType::Transform: - MarshalType(wb, property); - break; - - case Data::eType::Vector2: - MarshalType(wb, property); - break; - - case Data::eType::Vector3: - MarshalType(wb, property); - break; - - case Data::eType::Vector4: - MarshalType(wb, property); - break; - - default: - AZ_Warning("ScriptCanvasNetworking", false, "Marshal unsupported data type"); - break; - } - } - - bool DatumMarshaler::UnmarshalToPointer(const Datum*& target, GridMate::ReadBuffer& rb) - { - // :SCTODO: for some reason, this UnmarshalToPointer can get called before SetNetworkBinding is called - // (which is where we set m_graphVariableNetBindingTable). So we check for nullptr here just in case. - if (!m_graphVariableNetBindingTable) - { - return false; - } - - ScriptCanvas::Data::eType datumType = Data::eType::Invalid; - GridMate::Marshaler typeMarshaler; - typeMarshaler.Unmarshal(datumType, rb); - - AZ::Uuid uuid; - GridMate::Marshaler uuidMarshaler; - uuidMarshaler.Unmarshal(uuid, rb); - - VariableId runtimeVariableId = m_graphVariableNetBindingTable->FindRuntimeVariableIdByAssetVariableId(VariableId(uuid)); - - if (!runtimeVariableId.IsValid()) - { - return false; - } - - AZStd::string uuidString = runtimeVariableId.m_id.ToString(); - - AZStd::unordered_map>& m_variableIdMap = m_graphVariableNetBindingTable->GetVariableIdMap(); - AZStd::pair& variableIndexPair = m_variableIdMap[runtimeVariableId]; - GraphVariable* graphVariable = variableIndexPair.first; - - switch (datumType) - { - case Data::eType::AABB: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Boolean: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Color: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::CRC: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::EntityID: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Matrix3x3: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Matrix4x4: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::NamedEntityID: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Number: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::OBB: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Plane: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Quaternion: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::String: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Transform: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Vector2: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Vector3: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Vector4: - return UnmarshalType(target, rb, graphVariable); - - default: - AZ_Warning("ScriptCanvasNetworking", false, "Unmarshal unsupported data type"); - break; - } - - return false; - } - - void DatumThrottler::SignalDirty() - { - m_isDirty = true; - } - - bool DatumThrottler::WithinThreshold(const Datum* newValue) const - { - return (newValue == nullptr || !m_isDirty); - } - - void DatumThrottler::UpdateBaseline([[maybe_unused]] const Datum* baseline) - { - m_isDirty = false; - } -} diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableMarshal.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableMarshal.h deleted file mode 100644 index 5fd8c3fa0d..0000000000 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableMarshal.h +++ /dev/null @@ -1,86 +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 - -namespace ScriptCanvas -{ - class GraphVariableNetBindingTable; - - class DatumMarshaler - { - public: - void SetNetBindingTable(GraphVariableNetBindingTable* netBindingTable); - void Marshal(GridMate::WriteBuffer& wb, const Datum* const & cont) const; - bool UnmarshalToPointer(const Datum*& target, GridMate::ReadBuffer& rb); - - private: - template - void MarshalType(GridMate::WriteBuffer& wb, const Datum* const & property) const - { - GridMate::Marshaler marshaler; - const T* value = property->GetAs(); - marshaler.Marshal(wb, *value); - } - - template - bool UnmarshalType(const Datum*& target, GridMate::ReadBuffer& rb, GraphVariable* graphVariable) - { - bool valueChanged = false; - ModifiableDatumView datumView; - - if (graphVariable) - { - graphVariable->ConfigureDatumView(datumView); - - if (datumView.IsValid()) - { - GridMate::Marshaler marshaler; - T value; - - marshaler.Unmarshal(value, rb); - datumView.SetAs(value); - target = graphVariable->GetDatum(); - valueChanged = true; - } - } - - return valueChanged; - } - - private: - //! The network binding table is needed to determine which Datum to update - //! when unmarshaling data. - // :SCTODO: synced Datums should be tracked via ID - //! and that ID should be used to lookup Datums (right now we can assume - //! which Datum should be updated, since only one Datum is supported). - GraphVariableNetBindingTable* m_graphVariableNetBindingTable = nullptr; - }; - - //! Simple throttler that simple operates via dirty flag. - class DatumThrottler - { - public: - DatumThrottler() = default; - - void SignalDirty(); - bool WithinThreshold(const Datum* newValue) const; - void UpdateBaseline(const Datum* baseline); - - private: - bool m_isDirty = false; - }; -} diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableNetBindings.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableNetBindings.cpp deleted file mode 100644 index e30cb95255..0000000000 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableNetBindings.cpp +++ /dev/null @@ -1,181 +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 - -namespace ScriptCanvas -{ - const char* DatumDataSet::GetDataSetName() - { - static size_t s_chunkIndex = 0; - static const char* s_nameArray[] = { - "DataSet1","DataSet2","DataSet3","DataSet4","DataSet5", - "DataSet6","DataSet7","DataSet8","DataSet9","DataSet10", - "DataSet11","DataSet12","DataSet13","DataSet14","DataSet15", - "DataSet16","DataSet17","DataSet18","DataSet19","DataSet20", - "DataSet21","DataSet22","DataSet23","DataSet24","DataSet25", - "DataSet26","DataSet27","DataSet28","DataSet29","DataSet30", - "DataSet31","DataSet32" - }; - - if (s_chunkIndex > AZ_ARRAY_SIZE(s_nameArray) && AZ_ARRAY_SIZE(s_nameArray) >= 0) - { - s_chunkIndex = s_chunkIndex % AZ_ARRAY_SIZE(s_nameArray); - } - - return s_nameArray[s_chunkIndex++]; - } - - DatumDataSet::DatumDataSet() - : DatumDataSetType(DatumDataSet::GetDataSetName()) - { - } - - ////////////////////////// - // GraphVariableReplicaChunk - ////////////////////////// - - const char* GraphVariableReplicaChunk::GetChunkName() - { - return "GraphVariableReplicaChunk"; - } - - bool GraphVariableReplicaChunk::IsReplicaMigratable() - { - return true; - } - - ////////////////////////// - // GraphVariableNetBindingTable - ////////////////////////// - - void GraphVariableNetBindingTable::Reflect([[maybe_unused]] AZ::ReflectContext* reflect) - { - GridMate::ReplicaChunkDescriptorTable& descriptorTable = GridMate::ReplicaChunkDescriptorTable::Get(); - AZ::Crc32 hash = GridMate::ReplicaChunkClassId(GraphVariableReplicaChunk::GetChunkName()); - - if (!descriptorTable.FindReplicaChunkDescriptor(hash)) - { - descriptorTable.RegisterChunkType(); - } - } - - GridMate::ReplicaChunkPtr GraphVariableNetBindingTable::GetNetworkBinding() - { - if (!m_replicaChunk) - { - m_replicaChunk = GridMate::CreateReplicaChunk(); - m_replicaChunk->SetHandler(this); - SetGraphNetBindingTable(); - } - - return m_replicaChunk; - } - - void GraphVariableNetBindingTable::SetNetworkBinding(GridMate::ReplicaChunkPtr chunk) - { - m_replicaChunk = chunk; - m_replicaChunk->SetHandler(this); - SetGraphNetBindingTable(); - } - - void GraphVariableNetBindingTable::UnbindFromNetwork() - { - if (m_replicaChunk) - { - m_replicaChunk->SetHandler(nullptr); - m_replicaChunk = nullptr; - } - } - - void GraphVariableNetBindingTable::OnPropertyUpdate([[maybe_unused]] const Datum* const & scriptProperty, [[maybe_unused]] const GridMate::TimeContext& tc) - { - } - - void GraphVariableNetBindingTable::AddDatum(GraphVariable* variable) - { - size_t index = m_variableIdMap.size(); - - m_variableIdMap[variable->GetVariableId()] = AZStd::make_pair(variable, static_cast(index)); - } - - void GraphVariableNetBindingTable::OnDatumChanged(GraphVariable& variable) - { - if (m_replicaChunk && m_replicaChunk->IsMaster()) - { - GraphVariableReplicaChunk* graphVarChunk = static_cast(m_replicaChunk.get()); - auto iter = m_variableIdMap.find(variable.GetVariableId()); - - if (iter == m_variableIdMap.end()) - { - AZ_TracePrintf("ScriptCanvasNetworking", "GraphVariableNetBindingTable::OnDatumChanged: variable not found"); - return; - } - - const AZStd::pair& pair = iter->second; - DatumDataSet& datumDataSet = graphVarChunk->m_properties[pair.second]; - datumDataSet.GetThrottler().SignalDirty(); - datumDataSet.Set(variable.GetDatum()); - } - } - - void GraphVariableNetBindingTable::SetVariableMappings(const AZStd::unordered_map& assetToRuntimeVariableMap, const AZStd::unordered_map& runtimeToAssetVariableMap) - { - m_assetToRuntimeVariableMap = assetToRuntimeVariableMap; - m_runtimeToAssetVariableMap = runtimeToAssetVariableMap; - } - - VariableId GraphVariableNetBindingTable::FindAssetVariableIdByRuntimeVariableId(VariableId runtimeVariableId) - { - auto iter = m_runtimeToAssetVariableMap.find(runtimeVariableId); - - if (iter != m_runtimeToAssetVariableMap.end()) - { - return iter->second; - } - - return VariableId(); - } - - VariableId GraphVariableNetBindingTable::FindRuntimeVariableIdByAssetVariableId(VariableId assetVariableId) - { - auto iter = m_assetToRuntimeVariableMap.find(assetVariableId); - - if (iter != m_assetToRuntimeVariableMap.end()) - { - return iter->second; - } - - return VariableId(); - } - - AZStd::unordered_map>& GraphVariableNetBindingTable::GetVariableIdMap() - { - return m_variableIdMap; - } - - void GraphVariableNetBindingTable::SetGraphNetBindingTable() - { - GraphVariableReplicaChunk* graphVariableChunk = static_cast(m_replicaChunk.get()); - - for (DatumDataSet& dataSet : graphVariableChunk->m_properties) - { - dataSet.GetMarshaler().SetNetBindingTable(this); - } - } -} diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableNetBindings.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableNetBindings.h deleted file mode 100644 index d0f945523d..0000000000 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableNetBindings.h +++ /dev/null @@ -1,101 +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 -#include - -namespace ScriptCanvas -{ - class GraphVariable; - class GraphVariableReplicaChunk; - - //! Core functionality for managing replicated Datums in a script canvas and the - //! corresponding GridMate callbacks and data structs (DataSets). - class GraphVariableNetBindingTable - : public GridMate::ReplicaChunkInterface - { - public: - AZ_CLASS_ALLOCATOR(GraphVariableNetBindingTable, AZ::SystemAllocator, 0); - - static void Reflect(AZ::ReflectContext* reflect); - - GraphVariableNetBindingTable() = default; - ~GraphVariableNetBindingTable() = default; - - GridMate::ReplicaChunkPtr GetNetworkBinding(); - void SetNetworkBinding(GridMate::ReplicaChunkPtr chunk); - void UnbindFromNetwork(); - - //! Gets called when the given Datum object is updated with a new value - //! that was received over the network. - void OnPropertyUpdate(const Datum* const & scriptProperty, const GridMate::TimeContext& tc); - - //! Adds the given Datum to the list of "synced datums" for this instance. - void AddDatum(GraphVariable* variable); - - //! Called when local data changes for a Datum whose values should be replicated - //! over the network. - void OnDatumChanged(GraphVariable& variable); - - void SetVariableMappings(const AZStd::unordered_map& assetToRuntimeVariableMap, const AZStd::unordered_map& runtimeToAssetVariableMap); - VariableId FindAssetVariableIdByRuntimeVariableId(VariableId runtimeVariableId); - VariableId FindRuntimeVariableIdByAssetVariableId(VariableId assetVariableId); - AZStd::unordered_map>& GetVariableIdMap(); - - private: - void SetGraphNetBindingTable(); - - private: - AZStd::unordered_map m_assetToRuntimeVariableMap; - AZStd::unordered_map m_runtimeToAssetVariableMap; - - //! Replica chunk used for GridMate networking binding. See GraphVariableReplicaChunk. - GridMate::ReplicaChunkPtr m_replicaChunk; - - //! Contains pointers to all replicated variables contained within the runtime component - //! of the canvas this net binding is associated with. - AZStd::unordered_map> m_variableIdMap; - }; - - typedef GridMate::DataSet::BindInterface DatumDataSetType; - - class DatumDataSet - : public DatumDataSetType - { - public: - DatumDataSet(); - ~DatumDataSet() = default; - - private: - const char* GetDataSetName(); - }; - - class GraphVariableReplicaChunk - : public GridMate::ReplicaChunkBase - { - public: - AZ_CLASS_ALLOCATOR(GraphVariableReplicaChunk, AZ::SystemAllocator, 0); - - static const char* GetChunkName(); - - GraphVariableReplicaChunk() = default; - ~GraphVariableReplicaChunk() = default; - - bool IsReplicaMigratable() override; - - DatumDataSet m_properties[GM_MAX_DATASETS_IN_CHUNK]; - }; -} diff --git a/Gems/ScriptCanvas/Code/scriptcanvasgem_common_files.cmake b/Gems/ScriptCanvas/Code/scriptcanvasgem_common_files.cmake index 871d8d4c5d..84391021df 100644 --- a/Gems/ScriptCanvas/Code/scriptcanvasgem_common_files.cmake +++ b/Gems/ScriptCanvas/Code/scriptcanvasgem_common_files.cmake @@ -597,10 +597,6 @@ set(FILES Include/ScriptCanvas/Variable/GraphVariable.cpp Include/ScriptCanvas/Variable/GraphVariableManagerComponent.h Include/ScriptCanvas/Variable/GraphVariableManagerComponent.cpp - Include/ScriptCanvas/Variable/GraphVariableNetBindings.h - Include/ScriptCanvas/Variable/GraphVariableNetBindings.cpp - Include/ScriptCanvas/Variable/GraphVariableMarshal.h - Include/ScriptCanvas/Variable/GraphVariableMarshal.cpp Include/ScriptCanvas/Variable/VariableCore.h Include/ScriptCanvas/Variable/VariableCore.cpp Include/ScriptCanvas/Variable/VariableData.h From b5e87d3601d6fadf2a7f92531d317463efbb0cec Mon Sep 17 00:00:00 2001 From: mbalfour Date: Tue, 11 May 2021 16:13:04 -0500 Subject: [PATCH 062/100] Change SerializeContextTools into a ToolsApplication so that it can correctly read in slice data: - Uses ToolsApplication instead of ComponentApplication so that built-in Editor components are recognized and read in correctly - Starts up all the DynamicModules immediately so that the System Components are activated, which registers asset handlers and allows asset references to serialize in correctly - Adds a -specialization command-line flag to specify which project specialization to use (editor, game, etc) - Removes the filter to ignore unknown classes since they should all now be "known" - Adds a few gem autoload flags and a null thumbnail service so that Qt and Python systems can be skipped, as they aren't needed for the data conversions and would bring additional overhead and complications --- .../SerializeContextTools/Application.cpp | 43 ++++++++++++++++--- .../Tools/SerializeContextTools/Application.h | 5 ++- .../SerializeContextTools/CMakeLists.txt | 2 + .../Tools/SerializeContextTools/Utilities.cpp | 1 - Code/Tools/SerializeContextTools/main.cpp | 7 +-- .../gem_autoload.serializecontexttools.setreg | 15 +++++++ 6 files changed, 59 insertions(+), 14 deletions(-) create mode 100644 Registry/gem_autoload.serializecontexttools.setreg diff --git a/Code/Tools/SerializeContextTools/Application.cpp b/Code/Tools/SerializeContextTools/Application.cpp index 2ab9847aa6..72e68ebb1e 100644 --- a/Code/Tools/SerializeContextTools/Application.cpp +++ b/Code/Tools/SerializeContextTools/Application.cpp @@ -16,12 +16,23 @@ #include #include +#include + namespace AZ { + // SerializeContextTools is a full ToolsApplication that will load a project's Gem DLLs and initialize the system components. + // This level of initialization is required to get all the serialization contexts and asset handlers registered, so that when + // data transformations take place, none of the data is dropped due to not being recognized. + // However, as a simplification, anything requiring Python or Qt is skipped during initialization: + // - The gem_autoload.serializecontexttools.setreg file disables autoload for QtForPython, EditorPythonBindings, and PythonAssetBuilder + // - The system component initialization below uses ThumbnailerNullComponent so that other components relying on a ThumbnailService + // can still be started up, but the thumbnail service itself won't do anything. The real ThumbnailerComponent uses Qt, which is why + // it isn't used. + namespace SerializeContextTools { Application::Application(int argc, char** argv) - : AZ::ComponentApplication(argc, argv) + : AzToolsFramework::ToolsApplication(&argc, &argv) { AZ::IO::FixedMaxPath projectPath = AZ::Utils::GetProjectPath(); if (projectPath.empty()) @@ -51,14 +62,25 @@ namespace AZ else { AZ::SettingsRegistryInterface::Specializations projectSpecializations{ projectName }; - AZ::IO::PathView configFilenameStem = m_configFilePath.Stem(); - if (AZ::StringFunc::Equal(configFilenameStem.Native(), "Editor")) + + // If a project specialization has been passed in via the command line, use it. + if (m_commandLine.HasSwitch("specialization")) { - projectSpecializations.Append("editor"); + AZStd::string specialization = m_commandLine.GetSwitchValue("specialization", 0); + projectSpecializations.Append(specialization); } - else if (AZ::StringFunc::Equal(configFilenameStem.Native(), "Game")) + // Otherwise, if a config file was passed in, auto-set the specialization based on the config file name. + else { - projectSpecializations.Append(projectName + "_GameLauncher"); + AZ::IO::PathView configFilenameStem = m_configFilePath.Stem(); + if (AZ::StringFunc::Equal(configFilenameStem.Native(), "Editor")) + { + projectSpecializations.Append("editor"); + } + else if (AZ::StringFunc::Equal(configFilenameStem.Native(), "Game")) + { + projectSpecializations.Append(projectName + "_GameLauncher"); + } } // Used the project specializations to merge the build dependencies *.setreg files @@ -78,5 +100,14 @@ namespace AZ AZ::ComponentApplication::SetSettingsRegistrySpecializations(specializations); specializations.Append("serializecontexttools"); } + + AZ::ComponentTypeList Application::GetRequiredSystemComponents() const + { + // Use all of the default system components, but also add in the ThumbnailerNullComponent so that components requiring + // a ThumbnailService can still be started up. + AZ::ComponentTypeList components = AzToolsFramework::ToolsApplication::GetRequiredSystemComponents(); + components.emplace_back(azrtti_typeid()); + return components; + } } // namespace SerializeContextTools } // namespace AZ diff --git a/Code/Tools/SerializeContextTools/Application.h b/Code/Tools/SerializeContextTools/Application.h index 63bc1892ed..b1b818e27d 100644 --- a/Code/Tools/SerializeContextTools/Application.h +++ b/Code/Tools/SerializeContextTools/Application.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace AZ @@ -20,13 +20,14 @@ namespace AZ namespace SerializeContextTools { class Application final - : public AZ::ComponentApplication + : public AzToolsFramework::ToolsApplication { public: Application(int argc, char** argv); ~Application() override = default; const char* GetConfigFilePath() const; + AZ::ComponentTypeList GetRequiredSystemComponents() const override; protected: void SetSettingsRegistrySpecializations(AZ::SettingsRegistryInterface::Specializations& specializations) override; diff --git a/Code/Tools/SerializeContextTools/CMakeLists.txt b/Code/Tools/SerializeContextTools/CMakeLists.txt index 1a993de53c..e73fd014ab 100644 --- a/Code/Tools/SerializeContextTools/CMakeLists.txt +++ b/Code/Tools/SerializeContextTools/CMakeLists.txt @@ -29,4 +29,6 @@ ly_add_target( BUILD_DEPENDENCIES PRIVATE AZ::AzCore + AZ::AzFramework + AZ::AzToolsFramework ) diff --git a/Code/Tools/SerializeContextTools/Utilities.cpp b/Code/Tools/SerializeContextTools/Utilities.cpp index 127f833f6b..1c50466443 100644 --- a/Code/Tools/SerializeContextTools/Utilities.cpp +++ b/Code/Tools/SerializeContextTools/Utilities.cpp @@ -236,7 +236,6 @@ namespace AZ::SerializeContextTools AZ::IO::MemoryStream stream(data.data(), fileLength); ObjectStream::FilterDescriptor filter; - filter.m_flags = ObjectStream::FILTERFLAG_IGNORE_UNKNOWN_CLASSES; // Never load dependencies. That's another file that would need to be processed // separately from this one. filter.m_assetCB = AZ::Data::AssetFilterNoAssetLoading; diff --git a/Code/Tools/SerializeContextTools/main.cpp b/Code/Tools/SerializeContextTools/main.cpp index ee505c9cc0..4bff597d81 100644 --- a/Code/Tools/SerializeContextTools/main.cpp +++ b/Code/Tools/SerializeContextTools/main.cpp @@ -23,6 +23,7 @@ void PrintHelp() AZ_Printf("Help", "Serialize Context Tool\n"); AZ_Printf("Help", " [-config] *\n"); AZ_Printf("Help", " [opt] -config=: optional path to application's config file. Default is 'config/editor.xml'.\n"); + AZ_Printf("Help", " [opt] -specialization=: optional Registry project specialization, such as 'editor' or 'game'. Default is none. \n"); AZ_Printf("Help", "\n"); AZ_Printf("Help", " 'help': Print this help\n"); AZ_Printf("Help", " example: 'help'\n"); @@ -81,11 +82,7 @@ int main(int argc, char** argv) bool result = false; Application application(argc, argv); AZ::ComponentApplication::StartupParameters startupParameters; - startupParameters.m_loadDynamicModules = false; - application.Create({}, startupParameters); - // Load the DynamicModules after the Application starts to prevent Gem System Components - // from activating - application.LoadDynamicModules(); + application.Start({}, startupParameters); const AZ::CommandLine* commandLine = application.GetAzCommandLine(); if (commandLine->GetNumMiscValues() < 1) diff --git a/Registry/gem_autoload.serializecontexttools.setreg b/Registry/gem_autoload.serializecontexttools.setreg new file mode 100644 index 0000000000..1f4a8931c5 --- /dev/null +++ b/Registry/gem_autoload.serializecontexttools.setreg @@ -0,0 +1,15 @@ +{ + "Amazon": { + "Gems": { + "QtForPython.Editor": { + "AutoLoad": false + }, + "EditorPythonBindings.Editor": { + "AutoLoad": false + }, + "PythonAssetBuilder.Editor": { + "AutoLoad": false + } + } + } +} From 318f97a717bf367a7a96827e3891f3dbeacd5230 Mon Sep 17 00:00:00 2001 From: karlberg Date: Tue, 11 May 2021 14:28:10 -0700 Subject: [PATCH 063/100] build fix for removed gridmate headers --- .../ViewportSelection/EditorTransformComponentSelection.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index 9388f3f5f0..c6450d03c7 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -13,6 +13,9 @@ #include "EditorTransformComponentSelection.h" #include +#include +#include +#include #include #include #include From b92a1884a806a6df681ec95954a9a4e03688561c Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Tue, 11 May 2021 18:08:59 -0400 Subject: [PATCH 064/100] Addex dx12/metal builders to linux --- .../Code/Source/Platform/Linux/additional_linux_tool_deps.cmake | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake index 8fb58f5e56..942a694205 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake @@ -12,4 +12,6 @@ set(LY_RUNTIME_DEPENDENCIES Gem::Atom_RHI_Vulkan.Private Gem::Atom_RHI_Vulkan.Builders + Gem::Atom_RHI_DX12.Builders + Gem::Atom_RHI_Metal.Builders ) From 3169b3477d18572832e348527d30a766b9d43bcb Mon Sep 17 00:00:00 2001 From: karlberg Date: Tue, 11 May 2021 15:15:35 -0700 Subject: [PATCH 065/100] Adding missing files to azframework_files.cmake and fixing include errors due to network removal --- Code/Framework/AzFramework/AzFramework/Physics/WindBus.h | 1 + Code/Framework/AzFramework/AzFramework/azframework_files.cmake | 1 + .../Source/Components/ClothComponentMesh/ClothComponentMesh.h | 1 + 3 files changed, 3 insertions(+) diff --git a/Code/Framework/AzFramework/AzFramework/Physics/WindBus.h b/Code/Framework/AzFramework/AzFramework/Physics/WindBus.h index 60da2c3607..f96af2bcf9 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/WindBus.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/WindBus.h @@ -13,6 +13,7 @@ #include #include +#include #include namespace Physics diff --git a/Code/Framework/AzFramework/AzFramework/azframework_files.cmake b/Code/Framework/AzFramework/AzFramework/azframework_files.cmake index 135d9d36bd..48b0202a5b 100644 --- a/Code/Framework/AzFramework/AzFramework/azframework_files.cmake +++ b/Code/Framework/AzFramework/AzFramework/azframework_files.cmake @@ -255,6 +255,7 @@ set(FILES Physics/ClassConverters.cpp Physics/ClassConverters.h Physics/MaterialBus.h + Physics/WindBus.h Process/ProcessCommunicator.cpp Process/ProcessCommunicator.h Process/ProcessWatcher.cpp diff --git a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.h b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.h index 4374b67e32..a1fb6d5572 100644 --- a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.h +++ b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.h @@ -14,6 +14,7 @@ #include #include +#include #include From 7f5962d1ba4f2f81da1d002f9adc1a44f6f799d7 Mon Sep 17 00:00:00 2001 From: sharmajs-amzn <82233357+sharmajs-amzn@users.noreply.github.com> Date: Tue, 11 May 2021 15:23:43 -0700 Subject: [PATCH 066/100] disable AssetJobsFloodTest.ContainerCoreTest_BasicDependencyManagement_Success test (#703) --- .../Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Code/Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp b/Code/Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp index 78e2288a4c..d6122b81f1 100644 --- a/Code/Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp +++ b/Code/Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp @@ -1042,11 +1042,7 @@ namespace UnitTest -#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS TEST_F(AssetJobsFloodTest, DISABLED_ContainerCoreTest_BasicDependencyManagement_Success) -#else - TEST_F(AssetJobsFloodTest, ContainerCoreTest_BasicDependencyManagement_Success) -#endif // !AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS { m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusConnect(); // Setup has already created/destroyed assets From 93ef3acb504ca8b978e12b414d09cc5c835c4ac3 Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Tue, 11 May 2021 18:43:09 -0400 Subject: [PATCH 067/100] Removing non-tool modules from tools runtime deps --- .../Source/Platform/Linux/additional_linux_tool_deps.cmake | 1 - .../Code/Source/Platform/Mac/additional_mac_tool_deps.cmake | 3 --- .../Platform/Windows/additional_windows_tool_deps.cmake | 4 ---- 3 files changed, 8 deletions(-) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake index 942a694205..908417b1f8 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake @@ -10,7 +10,6 @@ # set(LY_RUNTIME_DEPENDENCIES - Gem::Atom_RHI_Vulkan.Private Gem::Atom_RHI_Vulkan.Builders Gem::Atom_RHI_DX12.Builders Gem::Atom_RHI_Metal.Builders diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake index 0b601adf8d..445a416a68 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake @@ -10,10 +10,7 @@ # set(LY_RUNTIME_DEPENDENCIES - Gem::Atom_RHI_Metal.Private Gem::Atom_RHI_Metal.Builders Gem::Atom_RHI_Vulkan.Builders Gem::Atom_RHI_DX12.Builders - Gem::Atom_RHI_Null.Private - Gem::Atom_RHI_Null.Builders ) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake index e30a9737ac..908417b1f8 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake @@ -10,11 +10,7 @@ # set(LY_RUNTIME_DEPENDENCIES - Gem::Atom_RHI_Vulkan.Private Gem::Atom_RHI_Vulkan.Builders - Gem::Atom_RHI_DX12.Private Gem::Atom_RHI_DX12.Builders - Gem::Atom_RHI_Null.Private - Gem::Atom_RHI_Null.Builders Gem::Atom_RHI_Metal.Builders ) From b2a92b1950ab010a09d3631a7cb2bf29d83e49fa Mon Sep 17 00:00:00 2001 From: karlberg Date: Tue, 11 May 2021 16:00:15 -0700 Subject: [PATCH 068/100] Removing test that required netbinding on the AzFramework TransformComponent --- .../Code/Tests/Builders/LevelBuilderTest.cpp | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/Gems/LmbrCentral/Code/Tests/Builders/LevelBuilderTest.cpp b/Gems/LmbrCentral/Code/Tests/Builders/LevelBuilderTest.cpp index 58e7e9e093..47d24f09f4 100644 --- a/Gems/LmbrCentral/Code/Tests/Builders/LevelBuilderTest.cpp +++ b/Gems/LmbrCentral/Code/Tests/Builders/LevelBuilderTest.cpp @@ -309,22 +309,6 @@ TEST_F(LevelBuilderTest, DynamicSlice_NoAssetReferences_HasNoProductDependencies ASSERT_EQ(productPathDependencies.size(), 0); } -TEST_F(LevelBuilderTest, DynamicSlice_HasAssetReference_HasCorrectProductDependency) -{ - LevelBuilderWorker worker; - AZStd::vector productDependencies; - ProductPathDependencySet productPathDependencies; - - AZStd::string filePath(GetTestFileAliasedPath("levelSlice_oneAssetRef.entities_xml")); - ASSERT_TRUE(AZ::IO::FileIOBase::GetInstance()->Exists(filePath.c_str())); - - worker.PopulateLevelSliceDependenciesHelper(filePath, productDependencies, productPathDependencies); - ASSERT_EQ(productPathDependencies.size(), 0); - ASSERT_EQ(productDependencies.size(), 1); - ASSERT_EQ(productDependencies[0].m_dependencyId.m_guid, AZ::Uuid("A8970A25-5043-5519-A927-F180E7D6E8C1")); - ASSERT_EQ(productDependencies[0].m_dependencyId.m_subId, 1); -} - void BuildSliceWithSimpleAssetReference(const AZStd::vector& filePaths, AZStd::vector& productDependencies, ProductPathDependencySet& productPathDependencies) { auto* assetComponent = aznew MockSimpleAssetRefComponent; From a2a315a6cd4d2e6bf4d9ade57e753c4e8b34528d Mon Sep 17 00:00:00 2001 From: catdo Date: Tue, 11 May 2021 16:29:26 -0700 Subject: [PATCH 069/100] Fixed all nits and took out the general module and its usage --- .../Gem/PythonTests/CMakeLists.txt | 5 +- .../PrefabLevel_OpensLevelWithEntities.py | 62 +++++++++---------- ...{TestSuite_Active.py => TestSuite_Main.py} | 18 +++--- .../Gem/PythonTests/prefab/__init__.py | 2 +- 4 files changed, 39 insertions(+), 48 deletions(-) rename AutomatedTesting/Gem/PythonTests/prefab/{TestSuite_Active.py => TestSuite_Main.py} (61%) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index e4b68b6120..86bcb967ab 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -129,11 +129,10 @@ endif() NAME AutomatedTesting::PrefabTests TEST_SUITE main TEST_SERIAL - PATH ${CMAKE_CURRENT_LIST_DIR}/prefab/TestSuite_Active.py - TIMEOUT 3600 + PATH ${CMAKE_CURRENT_LIST_DIR}/prefab/TestSuite_Main.py + TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor - Legacy::CryRenderNULL AZ::AssetProcessor AutomatedTesting.Assets ) diff --git a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py index 45f44474e1..ca59bbc2f8 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py +++ b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py @@ -9,22 +9,19 @@ remove or modify any license notices. This file is distributed on an "AS IS" BAS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ - # fmt:off -class Tests (): +class Tests(): find_empty_entity = ("Entity: 'EmptyEntity' found", "Entity: 'EmptyEntity' *not* found in level") - empty_entity_pos = ( - "'EmptyEntity' position is at the expected position", "'EmptyEntity' position is *not* at the expected position") + empty_entity_pos = ("'EmptyEntity' position is at the expected position", "'EmptyEntity' position is *not* at the expected position") find_pxentity = ("Entity: 'EntityWithPxCollider' found", "Entity: 'EntityWithPxCollider' *not* found in level") - pxentity_component = ( - "Entity: 'EntityWithPxCollider' has a Physx Collider", "Entity: 'EntityWithPxCollider' has *not* a Physx Collider") + pxentity_component = ("Entity: 'EntityWithPxCollider' has a Physx Collider", "Entity: 'EntityWithPxCollider' has *not* a Physx Collider") # fmt:on -def PrefabLevel_OpensLevelWithEntities (): +def PrefabLevel_OpensLevelWithEntities(): """ Opens the level that contains 2 entities, "EmptyEntity" and "EntityWithPxCollider". - This test makes sure that both entities exist after openning the level and that: + This test makes sure that both entities exist after opening the level and that: - EmptyEntity is at Position: (10, 20, 30) - EntityWithPxCollider has a PhysXCollider component """ @@ -37,42 +34,41 @@ def PrefabLevel_OpensLevelWithEntities (): import editor_python_test_tools.hydra_editor_utils as hydra - import azlmbr.legacy.general as general - import azlmbr.bus + import azlmbr.entity as entity + import azlmbr.bus as bus from azlmbr.math import Vector3 - EXPECTED_EMPTY_ENTITY_POS = Vector3 (10.00, 20.0, 30.0) - - helper.init_idle () - helper.open_level ("prefab", "PrefabLevel_OpensLevelWithEntities") + EXPECTED_EMPTY_ENTITY_POS = Vector3(10.00, 20.0, 30.0) - class EmptyEntity (): - value = None + helper.init_idle() + helper.open_level("prefab", "PrefabLevel_OpensLevelWithEntities") - def find_empty_entity (): - EmptyEntity.value = general.find_editor_entity ("EmptyEntity") - return EmptyEntity.value.IsValid () + def find_entity(entity_name): + searchFilter = entity.SearchFilter() + searchFilter.names = [entity_name] + entityIds = entity.SearchBus(bus.Broadcast, 'SearchEntities', searchFilter) + if entityIds[0].IsValid(): + return entityIds[0] + return None - helper.wait_for_condition (find_empty_entity, 5.0) - Report.result (Tests.find_empty_entity, EmptyEntity.value.IsValid ()) + helper.wait_for_condition(lambda: find_entity("EmptyEntity").IsValid(), 5.0) + empty_entity_id = find_entity("EmptyEntity") + Report.result(Tests.find_empty_entity, empty_entity_id.IsValid()) - empty_entity_pos = azlmbr.components.TransformBus (azlmbr.bus.Event, "GetWorldTranslation", EmptyEntity.value) - is_at_position = empty_entity_pos.IsClose (EXPECTED_EMPTY_ENTITY_POS) - Report.result (Tests.empty_entity_pos, is_at_position) + empty_entity_pos = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTranslation", empty_entity_id) + is_at_position = empty_entity_pos.IsClose(EXPECTED_EMPTY_ENTITY_POS) + Report.result(Tests.empty_entity_pos, is_at_position) if not is_at_position: - Report.info (f'Expected position: {EXPECTED_EMPTY_ENTITY_POS.ToString ()}, actual position: {empty_entity_pos.ToString ()}') - - pxentity = general.find_editor_entity ("EntityWithPxCollider") - Report.result (Tests.find_pxentity, pxentity.IsValid ()) + Report.info(f'Expected position: {EXPECTED_EMPTY_ENTITY_POS.ToString()}, actual position: {empty_entity_pos.ToString()}') - pxcollider_id = hydra.get_component_type_id ("PhysX Collider") - hasComponent = azlmbr.editor.EditorComponentAPIBus (azlmbr.bus.Broadcast, 'HasComponentOfType', pxentity, - pxcollider_id) - Report.result (Tests.pxentity_component, hasComponent) + pxentity = find_entity("EntityWithPxCollider") + Report.result(Tests.find_pxentity, pxentity.IsValid()) + pxcollider_id = hydra.get_component_type_id("PhysX Collider") + hasComponent = azlmbr.editor.EditorComponentAPIBus(azlmbr.bus.Broadcast, 'HasComponentOfType', pxentity, pxcollider_id) + Report.result(Tests.pxentity_component, hasComponent) if __name__ == "__main__": from editor_python_test_tools.utils import Report Report.start_test (PrefabLevel_OpensLevelWithEntities) - PrefabLevel_OpensLevelWithEntities () \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py similarity index 61% rename from AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Active.py rename to AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py index 3cd0a0d43d..51c78a99e2 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Active.py +++ b/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py @@ -22,18 +22,14 @@ sys.path.append (os.path.dirname (os.path.abspath (__file__)) + '/../automatedte from base import TestAutomationBase - @pytest.mark.SUITE_main -@pytest.mark.parametrize ("launcher_platform", ['windows_editor']) -@pytest.mark.parametrize ("project", ["AutomatedTesting"]) -class TestAutomation (TestAutomationBase): +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +class TestAutomation(TestAutomationBase): - def _run_prefab_test (self, request, workspace, editor, test_module): - self._run_test (request, workspace, editor, test_module, - ["--regset=/Amazon/Preferences/EnablePrefabSystem=true"]) + def _run_prefab_test(self, request, workspace, editor, test_module): + self._run_test(request, workspace, editor, test_module, ["--regset=/Amazon/Preferences/EnablePrefabSystem=true"]) - def test_PrefabLevel_OpensLevelWithEntities (self, request, workspace, editor, launcher_platform): + def test_PrefabLevel_OpensLevelWithEntities(self, request, workspace, editor, launcher_platform): from . import PrefabLevel_OpensLevelWithEntities as test_module - - - self._run_prefab_test (request, workspace, editor, test_module) \ No newline at end of file + self._run_prefab_test(request, workspace, editor, test_module) diff --git a/AutomatedTesting/Gem/PythonTests/prefab/__init__.py b/AutomatedTesting/Gem/PythonTests/prefab/__init__.py index 6ed3dc4bda..79f8fa4422 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/prefab/__init__.py @@ -7,4 +7,4 @@ distribution (the "License"). All use of this software is governed by the Licens 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. -""" \ No newline at end of file +""" From 35500981ebcee1c344b995b4f281963dbfe3c69f Mon Sep 17 00:00:00 2001 From: karlberg Date: Tue, 11 May 2021 16:36:44 -0700 Subject: [PATCH 070/100] More removal fixes --- .../Components/TransformComponent.cpp | 2 ++ .../Code/Tests/Builders/LevelBuilderTest.cpp | 16 ++++++++++++++++ Gems/PhysX/Code/Tests/PhysXTestCommon.h | 1 + 3 files changed, 19 insertions(+) diff --git a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp index 284df15eb9..3c05887a89 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp @@ -878,6 +878,8 @@ namespace AzFramework AZ::SerializeContext* serializeContext = azrtti_cast(reflection); if (serializeContext) { + serializeContext->ClassDeprecate("NetBindable", "{80206665-D429-4703-B42E-94434F82F381}"); + serializeContext->Class() ->Version(4, &TransformComponentVersionConverter) ->Field("Parent", &TransformComponent::m_parentId) diff --git a/Gems/LmbrCentral/Code/Tests/Builders/LevelBuilderTest.cpp b/Gems/LmbrCentral/Code/Tests/Builders/LevelBuilderTest.cpp index 47d24f09f4..58e7e9e093 100644 --- a/Gems/LmbrCentral/Code/Tests/Builders/LevelBuilderTest.cpp +++ b/Gems/LmbrCentral/Code/Tests/Builders/LevelBuilderTest.cpp @@ -309,6 +309,22 @@ TEST_F(LevelBuilderTest, DynamicSlice_NoAssetReferences_HasNoProductDependencies ASSERT_EQ(productPathDependencies.size(), 0); } +TEST_F(LevelBuilderTest, DynamicSlice_HasAssetReference_HasCorrectProductDependency) +{ + LevelBuilderWorker worker; + AZStd::vector productDependencies; + ProductPathDependencySet productPathDependencies; + + AZStd::string filePath(GetTestFileAliasedPath("levelSlice_oneAssetRef.entities_xml")); + ASSERT_TRUE(AZ::IO::FileIOBase::GetInstance()->Exists(filePath.c_str())); + + worker.PopulateLevelSliceDependenciesHelper(filePath, productDependencies, productPathDependencies); + ASSERT_EQ(productPathDependencies.size(), 0); + ASSERT_EQ(productDependencies.size(), 1); + ASSERT_EQ(productDependencies[0].m_dependencyId.m_guid, AZ::Uuid("A8970A25-5043-5519-A927-F180E7D6E8C1")); + ASSERT_EQ(productDependencies[0].m_dependencyId.m_subId, 1); +} + void BuildSliceWithSimpleAssetReference(const AZStd::vector& filePaths, AZStd::vector& productDependencies, ProductPathDependencySet& productPathDependencies) { auto* assetComponent = aznew MockSimpleAssetRefComponent; diff --git a/Gems/PhysX/Code/Tests/PhysXTestCommon.h b/Gems/PhysX/Code/Tests/PhysXTestCommon.h index c4d08953eb..d130cccf9f 100644 --- a/Gems/PhysX/Code/Tests/PhysXTestCommon.h +++ b/Gems/PhysX/Code/Tests/PhysXTestCommon.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #include From bf62687b37de60d3b5196dad620d1365c021cf2e Mon Sep 17 00:00:00 2001 From: Steve Pham <82231385+spham-amzn@users.noreply.github.com> Date: Tue, 11 May 2021 18:58:26 -0700 Subject: [PATCH 071/100] Update android installation script to install gradle 7.0 --- .../build/build_node/Platform/Windows/install_android.ps1 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/build/build_node/Platform/Windows/install_android.ps1 b/scripts/build/build_node/Platform/Windows/install_android.ps1 index 30e651cc3a..2fde5fcb8c 100644 --- a/scripts/build/build_node/Platform/Windows/install_android.ps1 +++ b/scripts/build/build_node/Platform/Windows/install_android.ps1 @@ -28,8 +28,8 @@ Start-Process -FilePath $sdkmanager -ArgumentList $build_tools -NoNewWindow -Wai Write-Host "Installing Gradle and Ninja" Import-Module C:\ProgramData\chocolatey\helpers\chocolateyInstaller.psm1 #Grade needs a custom installer due to being hardcoded to C:\Programdata in Chocolatey $packageName = 'gradle' -$version = '5.6.4' -$checksum = 'ABC10BCEDB58806E8654210F96031DB541BCD2D6FC3161E81CB0572D6A15E821' +$version = '7.0' +$checksum = '81003F83B0056D20EEDF48CDDD4F52A9813163D4BA185BCF8ABD34B8EEEA4CBD' $url = "https://services.gradle.org/distributions/gradle-$version-all.zip" $installDir = "C:\Gradle" @@ -38,6 +38,6 @@ Install-ChocolateyZipPackage $packageName $url $installDir -Checksum $checksum - $gradle_home = Join-Path $installDir "$packageName-$version" $gradle_bat = Join-Path $gradle_home 'bin/gradle.bat' -Install-ChocolateyEnvironmentVariable "GRADLE_HOME" $gradle_home 'Machine' +Install-ChocolateyEnvironmentVariable "GRADLE_BUILD_HOME" $gradle_home 'Machine' choco install -y ninja --version=1.10.0 --package-parameters="/installDir:C:\Ninja" \ No newline at end of file From f9fb61cc5df598f799d8b44d854fa6b1ea91b1ef Mon Sep 17 00:00:00 2001 From: Tom Hulton-Harrop <82228511+hultonha@users.noreply.github.com> Date: Wed, 12 May 2021 09:40:37 +0100 Subject: [PATCH 072/100] Fix issue with viewport interaction ordering and viewport matrix changed handler (#695) * fix for ctrl+mouse-wheel to cycle transform modes in the viewport * ensure correct callback function is invoked * remove redundant check in CameraInput --- .../AzFramework/Viewport/CameraInput.cpp | 5 - .../Editor/ViewportManipulatorController.cpp | 328 ++++++++++-------- .../Editor/ViewportManipulatorController.h | 2 +- .../Source/RPI.Public/ViewportContext.cpp | 3 +- 4 files changed, 178 insertions(+), 160 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 4c95865938..8669b58911 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -407,11 +407,6 @@ namespace AzFramework { if (input->m_state == InputChannel::State::Began) { - if (input->m_state == InputChannel::State::Updated) - { - return; - } - m_translation |= translationFromKey(input->m_channelId); if (m_translation != TranslationType::Nil) { diff --git a/Code/Sandbox/Editor/ViewportManipulatorController.cpp b/Code/Sandbox/Editor/ViewportManipulatorController.cpp index 0bf2bbc412..248d2ba52c 100644 --- a/Code/Sandbox/Editor/ViewportManipulatorController.cpp +++ b/Code/Sandbox/Editor/ViewportManipulatorController.cpp @@ -21,206 +21,228 @@ #include -static const auto ManipulatorPriority = AzFramework::ViewportControllerPriority::High; -static const auto InteractionPriority = AzFramework::ViewportControllerPriority::Low; +static const auto ManipulatorPriority = AzFramework::ViewportControllerPriority::Highest; +static const auto InteractionPriority = AzFramework::ViewportControllerPriority::High; namespace SandboxEditor { - -ViewportManipulatorControllerInstance::ViewportManipulatorControllerInstance(AzFramework::ViewportId viewport, ViewportManipulatorController* controller) - : AzFramework::MultiViewportControllerInstanceInterface(viewport, controller) -{ -} - -AzToolsFramework::ViewportInteraction::MouseButton ViewportManipulatorControllerInstance::GetMouseButton( - const AzFramework::InputChannel& inputChannel) -{ - using AzToolsFramework::ViewportInteraction::MouseButton; - using InputButton = AzFramework::InputDeviceMouse::Button; - const auto& id = inputChannel.GetInputChannelId(); - if (id == InputButton::Left) + ViewportManipulatorControllerInstance::ViewportManipulatorControllerInstance( + AzFramework::ViewportId viewport, ViewportManipulatorController* controller) + : AzFramework::MultiViewportControllerInstanceInterface(viewport, controller) { - return MouseButton::Left; } - if (id == InputButton::Middle) - { - return MouseButton::Middle; - } - if (id == InputButton::Right) - { - return MouseButton::Right; - } - return MouseButton::None; -} - -bool ViewportManipulatorControllerInstance::IsMouseMove(const AzFramework::InputChannel& inputChannel) -{ - return inputChannel.GetInputChannelId() == AzFramework::InputDeviceMouse::SystemCursorPosition; -} -AzToolsFramework::ViewportInteraction::KeyboardModifier ViewportManipulatorControllerInstance::GetKeyboardModifier( - const AzFramework::InputChannel& inputChannel) -{ - using AzToolsFramework::ViewportInteraction::KeyboardModifier; - using Key = AzFramework::InputDeviceKeyboard::Key; - const auto& id = inputChannel.GetInputChannelId(); - if (id == Key::ModifierAltL || id == Key::ModifierAltR) + AzToolsFramework::ViewportInteraction::MouseButton ViewportManipulatorControllerInstance::GetMouseButton( + const AzFramework::InputChannel& inputChannel) { - return KeyboardModifier::Alt; + using AzToolsFramework::ViewportInteraction::MouseButton; + using InputButton = AzFramework::InputDeviceMouse::Button; + const auto& id = inputChannel.GetInputChannelId(); + if (id == InputButton::Left) + { + return MouseButton::Left; + } + if (id == InputButton::Middle) + { + return MouseButton::Middle; + } + if (id == InputButton::Right) + { + return MouseButton::Right; + } + return MouseButton::None; } - if (id == Key::ModifierCtrlL || id == Key::ModifierCtrlR) + + bool ViewportManipulatorControllerInstance::IsMouseMove(const AzFramework::InputChannel& inputChannel) { - return KeyboardModifier::Ctrl; + return inputChannel.GetInputChannelId() == AzFramework::InputDeviceMouse::SystemCursorPosition; } - if (id == Key::ModifierShiftL || id == Key::ModifierShiftR) + + AzToolsFramework::ViewportInteraction::KeyboardModifier ViewportManipulatorControllerInstance::GetKeyboardModifier( + const AzFramework::InputChannel& inputChannel) { - return KeyboardModifier::Shift; + using AzToolsFramework::ViewportInteraction::KeyboardModifier; + using Key = AzFramework::InputDeviceKeyboard::Key; + const auto& id = inputChannel.GetInputChannelId(); + if (id == Key::ModifierAltL || id == Key::ModifierAltR) + { + return KeyboardModifier::Alt; + } + if (id == Key::ModifierCtrlL || id == Key::ModifierCtrlR) + { + return KeyboardModifier::Ctrl; + } + if (id == Key::ModifierShiftL || id == Key::ModifierShiftR) + { + return KeyboardModifier::Shift; + } + return KeyboardModifier::None; } - return KeyboardModifier::None; -} -bool ViewportManipulatorControllerInstance::HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) -{ - // We only care about manipulator and viewport interaction events - if (event.m_priority != ManipulatorPriority && event.m_priority != InteractionPriority) + bool ViewportManipulatorControllerInstance::HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) { - return false; - } + // We only care about manipulator and viewport interaction events + if (event.m_priority != ManipulatorPriority && event.m_priority != InteractionPriority) + { + return false; + } - using InteractionBus = AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; - using namespace AzToolsFramework::ViewportInteraction; - using AzFramework::InputChannel; + using InteractionBus = AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; + using namespace AzToolsFramework::ViewportInteraction; + using AzFramework::InputChannel; - bool interactionHandled = false; - AZStd::optional overrideButton; - AZStd::optional eventType; + bool interactionHandled = false; + float wheelDelta = 0.0f; + AZStd::optional overrideButton; + AZStd::optional eventType; - // Because we receive events multiple times at separate priorities for manipulator events and - // viewport interaction events, we want to avoid updating our "last tick state" until we're on our last event, - // which currently is the low priority Interaction processor. - const bool finishedProcessingEvents = event.m_priority == InteractionPriority; + // Because we receive events multiple times at separate priorities for manipulator events and + // viewport interaction events, we want to avoid updating our "last tick state" until we're on our last event, + // which currently is the low priority Interaction processor. + const bool finishedProcessingEvents = event.m_priority == InteractionPriority; - if (IsMouseMove(event.m_inputChannel)) - { - // Cache the ray trace results when doing manipulator interaction checks, no need to recalculate after - if (event.m_priority == ManipulatorPriority) + const auto state = event.m_inputChannel.GetState(); + if (IsMouseMove(event.m_inputChannel)) { - AzFramework::ScreenPoint screenPosition = AzFramework::ScreenPoint(0, 0); - ViewportMouseCursorRequestBus::EventResult( - screenPosition, GetViewportId(), &ViewportMouseCursorRequestBus::Events::ViewportCursorScreenPosition); + // Cache the ray trace results when doing manipulator interaction checks, no need to recalculate after + if (event.m_priority == ManipulatorPriority) + { + AzFramework::ScreenPoint screenPosition = AzFramework::ScreenPoint(0, 0); + ViewportMouseCursorRequestBus::EventResult( + screenPosition, GetViewportId(), &ViewportMouseCursorRequestBus::Events::ViewportCursorScreenPosition); - m_state.m_mousePick.m_screenCoordinates = screenPosition; - AZStd::optional ray; - ViewportInteractionRequestBus::EventResult( - ray, GetViewportId(), &ViewportInteractionRequestBus::Events::ViewportScreenToWorldRay, screenPosition); + m_mouseInteraction.m_mousePick.m_screenCoordinates = screenPosition; + AZStd::optional ray; + ViewportInteractionRequestBus::EventResult( + ray, GetViewportId(), &ViewportInteractionRequestBus::Events::ViewportScreenToWorldRay, screenPosition); - if (ray.has_value()) - { - m_state.m_mousePick.m_rayOrigin = ray.value().origin; - m_state.m_mousePick.m_rayDirection = ray.value().direction; + if (ray.has_value()) + { + m_mouseInteraction.m_mousePick.m_rayOrigin = ray.value().origin; + m_mouseInteraction.m_mousePick.m_rayDirection = ray.value().direction; + } } + eventType = MouseEvent::Move; } - eventType = MouseEvent::Move; - } - else if (auto mouseButton = GetMouseButton(event.m_inputChannel); mouseButton != MouseButton::None) - { - const AZ::u32 mouseButtonValue = static_cast(mouseButton); - overrideButton = mouseButton; - if (event.m_inputChannel.GetState() == InputChannel::State::Began) + else if (auto mouseButton = GetMouseButton(event.m_inputChannel); mouseButton != MouseButton::None) { - m_state.m_mouseButtons.m_mouseButtons |= mouseButtonValue; - if (IsDoubleClick(mouseButton)) + const AZ::u32 mouseButtonValue = static_cast(mouseButton); + overrideButton = mouseButton; + if (state == InputChannel::State::Began) { - // Only remove the double click flag once we're done processing both Manipulator and Interaction events - if (event.m_priority == InteractionPriority) + m_mouseInteraction.m_mouseButtons.m_mouseButtons |= mouseButtonValue; + if (IsDoubleClick(mouseButton)) + { + // Only remove the double click flag once we're done processing both Manipulator and Interaction events + if (event.m_priority == InteractionPriority) + { + m_pendingDoubleClicks.erase(mouseButton); + } + eventType = MouseEvent::DoubleClick; + } + else { - m_pendingDoubleClicks.erase(mouseButton); + // Only insert the double click timing once we're done processing events, to avoid a false IsDoubleClick positive + if (finishedProcessingEvents) + { + m_pendingDoubleClicks[mouseButton] = m_curTime; + } + eventType = MouseEvent::Down; } - eventType = MouseEvent::DoubleClick; } - else + else if (state == InputChannel::State::Ended) { - // Only insert the double click timing once we're done processing events, to avoid a false IsDoubleClick positive - if (finishedProcessingEvents) + // If we've actually logged a mouse down event, forward a mouse up event. + // This prevents corner cases like the context menu thinking it should be opened even though no one clicked in this viewport, + // due to RenderViewportWidget ensuring all controllers get InputChannel::State::Ended events. + if (m_mouseInteraction.m_mouseButtons.m_mouseButtons & mouseButtonValue) { - m_pendingDoubleClicks[mouseButton] = m_curTime; + // Erase the button from our state if we're done processing events. + if (event.m_priority == InteractionPriority) + { + m_mouseInteraction.m_mouseButtons.m_mouseButtons &= ~mouseButtonValue; + } + eventType = MouseEvent::Up; } - eventType = MouseEvent::Down; } } - else if (event.m_inputChannel.GetState() == InputChannel::State::Ended) + else if (auto keyboardModifier = GetKeyboardModifier(event.m_inputChannel); keyboardModifier != KeyboardModifier::None) { - // If we've actually logged a mouse down event, forward a mouse up event. - // This prevents corner cases like the context menu thinking it should be opened even though no one clicked in this viewport, - // due to RenderViewportWidget ensuring all controllers get InputChannel::State::Ended events. - if (m_state.m_mouseButtons.m_mouseButtons & mouseButtonValue) + if (state == InputChannel::State::Began || state == InputChannel::State::Updated) { - // Erase the button from our state if we're done processing events. - if (event.m_priority == InteractionPriority) - { - m_state.m_mouseButtons.m_mouseButtons &= ~mouseButtonValue; - } - eventType = MouseEvent::Up; + m_mouseInteraction.m_keyboardModifiers.m_keyModifiers |= static_cast(keyboardModifier); + } + else if (state == InputChannel::State::Ended) + { + m_mouseInteraction.m_keyboardModifiers.m_keyModifiers &= ~static_cast(keyboardModifier); } } - } - else if (auto keyboardModifier = GetKeyboardModifier(event.m_inputChannel); keyboardModifier != KeyboardModifier::None) - { - if (event.m_inputChannel.GetState() == InputChannel::State::Began || event.m_inputChannel.GetState() == InputChannel::State::Updated) + else if (event.m_inputChannel.GetInputChannelId() == AzFramework::InputDeviceMouse::Movement::Z) { - m_state.m_keyboardModifiers.m_keyModifiers |= static_cast(keyboardModifier); + if (state == InputChannel::State::Began || state == InputChannel::State::Updated) + { + eventType = MouseEvent::Wheel; + wheelDelta = event.m_inputChannel.GetValue(); + } } - else if (event.m_inputChannel.GetState() == InputChannel::State::Ended) + + if (eventType) { - m_state.m_keyboardModifiers.m_keyModifiers &= ~static_cast(keyboardModifier); + MouseInteraction mouseInteraction = m_mouseInteraction; + if (overrideButton) + { + mouseInteraction.m_mouseButtons.m_mouseButtons = static_cast(overrideButton.value()); + } + + mouseInteraction.m_interactionId.m_viewportId = GetViewportId(); + + // Depending on priority, we dispatch to either the manipulator or viewport interaction event + const auto& targetInteractionEvent = event.m_priority == ManipulatorPriority + ? &InteractionBus::Events::InternalHandleMouseManipulatorInteraction + : &InteractionBus::Events::InternalHandleMouseViewportInteraction; + + const auto mouseInteractionEvent = [mouseInteraction, event = eventType.value(), wheelDelta] { + switch (event) + { + case MouseEvent::Up: + case MouseEvent::Down: + case MouseEvent::Move: + case MouseEvent::DoubleClick: + return MouseInteractionEvent(AZStd::move(mouseInteraction), event); + case MouseEvent::Wheel: + return MouseInteractionEvent(AZStd::move(mouseInteraction), wheelDelta); + } + + AZ_Assert(false, "Unhandled MouseEvent"); + return MouseInteractionEvent(MouseInteraction{}, MouseEvent::Up); + }(); + + InteractionBus::EventResult( + interactionHandled, AzToolsFramework::GetEntityContextId(), targetInteractionEvent, mouseInteractionEvent); } + + return interactionHandled; } - if (eventType) + void ViewportManipulatorControllerInstance::ResetInputChannels() { - MouseInteraction mouseInteraction = m_state; - if (overrideButton) - { - mouseInteraction.m_mouseButtons.m_mouseButtons = static_cast(overrideButton.value()); - } - mouseInteraction.m_interactionId.m_viewportId = GetViewportId(); - - // Depending on priority, we dispatch to either the manipulator or viewport interaction event - const auto& targetInteractionEvent = - event.m_priority == ManipulatorPriority - ? &InteractionBus::Events::InternalHandleMouseManipulatorInteraction - : &InteractionBus::Events::InternalHandleMouseViewportInteraction; - - InteractionBus::EventResult( - interactionHandled, - AzToolsFramework::GetEntityContextId(), - targetInteractionEvent, - MouseInteractionEvent(AZStd::move(mouseInteraction), eventType.value())); + m_pendingDoubleClicks.clear(); + m_mouseInteraction = AzToolsFramework::ViewportInteraction::MouseInteraction(); } - return interactionHandled; -} - -void ViewportManipulatorControllerInstance::ResetInputChannels() -{ - m_pendingDoubleClicks.clear(); - m_state = AzToolsFramework::ViewportInteraction::MouseInteraction(); -} - -void ViewportManipulatorControllerInstance::UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) -{ - m_curTime = event.m_time; -} - -bool ViewportManipulatorControllerInstance::IsDoubleClick(AzToolsFramework::ViewportInteraction::MouseButton button) const -{ - auto clickIt = m_pendingDoubleClicks.find(button); - if (clickIt == m_pendingDoubleClicks.end()) + void ViewportManipulatorControllerInstance::UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) { - return false; + m_curTime = event.m_time; } - const double doubleClickThresholdMilliseconds = qApp->doubleClickInterval(); - return (m_curTime.GetMilliseconds() - clickIt->second.GetMilliseconds()) < doubleClickThresholdMilliseconds; -} + bool ViewportManipulatorControllerInstance::IsDoubleClick(AzToolsFramework::ViewportInteraction::MouseButton button) const + { + auto clickIt = m_pendingDoubleClicks.find(button); + if (clickIt == m_pendingDoubleClicks.end()) + { + return false; + } + const double doubleClickThresholdMilliseconds = qApp->doubleClickInterval(); + return (m_curTime.GetMilliseconds() - clickIt->second.GetMilliseconds()) < doubleClickThresholdMilliseconds; + } } //namespace SandboxEditor diff --git a/Code/Sandbox/Editor/ViewportManipulatorController.h b/Code/Sandbox/Editor/ViewportManipulatorController.h index d5540229c4..6d4ab4d1ba 100644 --- a/Code/Sandbox/Editor/ViewportManipulatorController.h +++ b/Code/Sandbox/Editor/ViewportManipulatorController.h @@ -39,7 +39,7 @@ namespace SandboxEditor static bool IsMouseMove(const AzFramework::InputChannel& inputChannel); static AzToolsFramework::ViewportInteraction::KeyboardModifier GetKeyboardModifier(const AzFramework::InputChannel& inputChannel); - AzToolsFramework::ViewportInteraction::MouseInteraction m_state; + AzToolsFramework::ViewportInteraction::MouseInteraction m_mouseInteraction; AZStd::unordered_map m_pendingDoubleClicks; AZ::ScriptTimePoint m_curTime; }; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp index cc25fb39ba..0dae5ac2d0 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp @@ -40,9 +40,10 @@ namespace AZ { m_projectionMatrixChangedEvent.Signal(matrix); }); + m_onViewMatrixChangedHandler = ViewportContext::MatrixChangedEvent::Handler([this](const AZ::Matrix4x4& matrix) { - m_projectionMatrixChangedEvent.Signal(matrix); + m_viewMatrixChangedEvent.Signal(matrix); }); SetRenderScene(renderScene); From ae9b36c135ac17d1e3a22e626084b4a4e359717e Mon Sep 17 00:00:00 2001 From: mbalfour Date: Wed, 12 May 2021 08:56:49 -0500 Subject: [PATCH 073/100] PR feedback - now allows for multiple specializations on the command-line, and changed the switch name to "specializations" to reflect that. --- Code/Tools/SerializeContextTools/Application.cpp | 8 +++++--- Code/Tools/SerializeContextTools/main.cpp | 3 ++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/Code/Tools/SerializeContextTools/Application.cpp b/Code/Tools/SerializeContextTools/Application.cpp index 72e68ebb1e..da0cca5ca6 100644 --- a/Code/Tools/SerializeContextTools/Application.cpp +++ b/Code/Tools/SerializeContextTools/Application.cpp @@ -64,10 +64,12 @@ namespace AZ AZ::SettingsRegistryInterface::Specializations projectSpecializations{ projectName }; // If a project specialization has been passed in via the command line, use it. - if (m_commandLine.HasSwitch("specialization")) + if (size_t specializationCount = m_commandLine.GetNumSwitchValues("specializations"); specializationCount > 0) { - AZStd::string specialization = m_commandLine.GetSwitchValue("specialization", 0); - projectSpecializations.Append(specialization); + for (size_t specializationIndex = 0; specializationIndex < specializationCount; ++specializationIndex) + { + projectSpecializations.Append(m_commandLine.GetSwitchValue("specializations", specializationIndex)); + } } // Otherwise, if a config file was passed in, auto-set the specialization based on the config file name. else diff --git a/Code/Tools/SerializeContextTools/main.cpp b/Code/Tools/SerializeContextTools/main.cpp index 4bff597d81..fb2dc442ed 100644 --- a/Code/Tools/SerializeContextTools/main.cpp +++ b/Code/Tools/SerializeContextTools/main.cpp @@ -23,7 +23,8 @@ void PrintHelp() AZ_Printf("Help", "Serialize Context Tool\n"); AZ_Printf("Help", " [-config] *\n"); AZ_Printf("Help", " [opt] -config=: optional path to application's config file. Default is 'config/editor.xml'.\n"); - AZ_Printf("Help", " [opt] -specialization=: optional Registry project specialization, such as 'editor' or 'game'. Default is none. \n"); + AZ_Printf("Help", " [opt] -specializations=: -separated list of optional Registry project\n"); + AZ_Printf("Help", " specializations, such as 'editor' or 'game' or 'editor;test'. Default is none. \n"); AZ_Printf("Help", "\n"); AZ_Printf("Help", " 'help': Print this help\n"); AZ_Printf("Help", " example: 'help'\n"); From 7cec2d8b076445ea8e2c965cc4a20bd424d74b50 Mon Sep 17 00:00:00 2001 From: bosnichd Date: Wed, 12 May 2021 08:30:15 -0600 Subject: [PATCH 074/100] Remove more unused things from CryCommon and CrySystem. (#709) Lots of unrelated removals, I basically tried to remove everything exposed via gEnv that isn't used anymore, and following the threads found a few other things to remove also. --- .../Engine/Config/engine_core.thread_config | 402 --- .../Config/engine_sandbox.thread_config | 128 - Code/CryEngine/CryCommon/CMakeLists.txt | 35 - Code/CryEngine/CryCommon/CryAssert_Android.h | 2 +- Code/CryEngine/CryCommon/CryAssert_Linux.h | 2 +- Code/CryEngine/CryCommon/CryAssert_Mac.h | 2 +- Code/CryEngine/CryCommon/CryAssert_iOS.h | 2 +- Code/CryEngine/CryCommon/CryAssert_impl.h | 2 +- Code/CryEngine/CryCommon/CrySystemBus.h | 6 - Code/CryEngine/CryCommon/CryThread.h | 3 - Code/CryEngine/CryCommon/CryThreadImpl.h | 19 - .../CryCommon/CryThreadImpl_windows.h | 2 - Code/CryEngine/CryCommon/CryThread_windows.h | 14 - .../CryCommon/EngineSettingsBackend.cpp | 34 - .../CryCommon/EngineSettingsBackend.h | 65 - .../CryCommon/EngineSettingsBackendApple.cpp | 486 --- .../CryCommon/EngineSettingsBackendApple.h | 51 - .../CryCommon/EngineSettingsBackendWin32.cpp | 431 --- .../CryCommon/EngineSettingsBackendWin32.h | 53 - .../CryCommon/EngineSettingsManager.cpp | 479 --- .../CryCommon/EngineSettingsManager.h | 89 - Code/CryEngine/CryCommon/IFlares.h | 228 -- Code/CryEngine/CryCommon/IMaterialEffects.h | 504 --- .../CryCommon/INotificationNetwork.h | 147 - Code/CryEngine/CryCommon/IRenderer.h | 28 +- .../CryCommon/IResourceCompilerHelper.cpp | 378 --- .../CryCommon/IResourceCompilerHelper.h | 167 - Code/CryEngine/CryCommon/IShader.h | 42 +- Code/CryEngine/CryCommon/ISoftCodeMgr.h | 276 -- Code/CryEngine/CryCommon/IStreamEngine.h | 1 - Code/CryEngine/CryCommon/ISystem.h | 327 +- Code/CryEngine/CryCommon/ISystemScheduler.h | 63 - Code/CryEngine/CryCommon/IThreadManager.h | 111 - Code/CryEngine/CryCommon/IThreadTask.h | 166 - .../CryEngine/CryCommon/Mocks/IRendererMock.h | 2 - Code/CryEngine/CryCommon/Mocks/ISystemMock.h | 44 - .../crycommon_enginesettings_mac_files.cmake | 15 - ...ycommon_enginesettings_windows_files.cmake | 15 - Code/CryEngine/CryCommon/ProfileLog.h | 70 - Code/CryEngine/CryCommon/ProjectDefines.h | 33 - .../CryCommon/ResourceCompilerHelper.cpp | 639 ---- .../CryCommon/ResourceCompilerHelper.h | 46 - .../CryCommon/SettingsManagerHelpers.cpp | 325 -- .../CryCommon/SettingsManagerHelpers.h | 491 --- .../crycommon_enginesettings_files.cmake | 27 - .../CryEngine/CryCommon/crycommon_files.cmake | 10 - Code/CryEngine/CryCommon/physinterface.h | 1 - Code/CryEngine/CryCommon/platform_impl.cpp | 3 +- Code/CryEngine/CrySystem/AutoDetectSpec.cpp | 4 +- Code/CryEngine/CrySystem/CMakeLists.txt | 2 - Code/CryEngine/CrySystem/ConsoleBatchFile.cpp | 17 - .../CrySystem/CrySystem_precompiled.h | 1 - .../CrySystem/CryThreadUtil_pthread.h | 259 -- .../CrySystem/CryThreadUtil_win32_thread.h | 432 --- Code/CryEngine/CrySystem/DebugCallStack.cpp | 926 ------ Code/CryEngine/CrySystem/DebugCallStack.h | 95 - Code/CryEngine/CrySystem/DllMain.cpp | 36 - Code/CryEngine/CrySystem/IDebugCallStack.cpp | 278 -- Code/CryEngine/CrySystem/IDebugCallStack.h | 90 - .../CrySystem/IThreadConfigManager.h | 59 - .../CrySystem/LevelSystem/LevelSystem.cpp | 17 - .../LevelSystem/SpawnableLevelSystem.cpp | 4 - Code/CryEngine/CrySystem/Log.cpp | 10 +- .../CrySystem/NotificationNetwork.cpp | 1345 -------- .../CryEngine/CrySystem/NotificationNetwork.h | 293 -- Code/CryEngine/CrySystem/ProfileLogSystem.cpp | 134 - Code/CryEngine/CrySystem/ProfileLogSystem.h | 74 - Code/CryEngine/CrySystem/ResourceManager.cpp | 11 +- .../CrySystem/SoftCode/SoftCodeMgr.cpp | 787 ----- .../CrySystem/SoftCode/SoftCodeMgr.h | 111 - Code/CryEngine/CrySystem/System.cpp | 562 ---- Code/CryEngine/CrySystem/System.h | 95 - Code/CryEngine/CrySystem/SystemInit.cpp | 164 +- Code/CryEngine/CrySystem/SystemRender.cpp | 48 - Code/CryEngine/CrySystem/SystemScheduler.cpp | 211 -- Code/CryEngine/CrySystem/SystemScheduler.h | 63 - Code/CryEngine/CrySystem/SystemThreading.cpp | 697 ---- Code/CryEngine/CrySystem/SystemWin32.cpp | 15 - .../CrySystem/ThreadConfigManager.cpp | 577 ---- .../CryEngine/CrySystem/ThreadConfigManager.h | 137 - Code/CryEngine/CrySystem/ThreadInfo.cpp | 123 - Code/CryEngine/CrySystem/ThreadInfo.h | 43 - Code/CryEngine/CrySystem/ThreadTask.cpp | 1046 ------ Code/CryEngine/CrySystem/ThreadTask.h | 181 - .../CrySystem/UnitTests/CryMathTests.cpp | 46 - .../CrySystem/UnitTests/CryPakUnitTests.cpp | 141 - Code/CryEngine/CrySystem/UnixConsole.cpp | 6 - Code/CryEngine/CrySystem/XConsole.cpp | 200 -- Code/CryEngine/CrySystem/XML/xml.cpp | 2 - .../CryEngine/CrySystem/crysystem_files.cmake | 21 - .../CrySystem/crysystem_test_files.cmake | 2 - .../AssetBrowser/AssetBrowserComponent.cpp | 2 - Code/LauncherUnified/Launcher.cpp | 5 - .../Editor/BackgroundScheduleManager.cpp | 629 ---- .../Editor/BackgroundScheduleManager.h | 117 - Code/Sandbox/Editor/BackgroundTaskManager.cpp | 410 --- Code/Sandbox/Editor/BackgroundTaskManager.h | 161 - Code/Sandbox/Editor/CMakeLists.txt | 1 - Code/Sandbox/Editor/CryEdit.cpp | 10 - Code/Sandbox/Editor/GameEngine.cpp | 21 - Code/Sandbox/Editor/IEditor.h | 2 - Code/Sandbox/Editor/IEditorImpl.cpp | 14 - Code/Sandbox/Editor/IEditorImpl.h | 17 - .../Include/IBackgroundScheduleManager.h | 207 -- .../Editor/Include/IBackgroundTaskManager.h | 230 -- Code/Sandbox/Editor/LevelInfo.cpp | 4 - Code/Sandbox/Editor/Lib/Tests/IEditorMock.h | 2 - Code/Sandbox/Editor/MainStatusBarItems.h | 1 - Code/Sandbox/Editor/MainWindow.cpp | 7 - Code/Sandbox/Editor/Objects/EntityObject.h | 1 - Code/Sandbox/Editor/UsedResources.cpp | 35 - Code/Sandbox/Editor/UsedResources.h | 2 - Code/Sandbox/Editor/editor_lib_files.cmake | 6 - .../SandboxIntegration.cpp | 25 - .../SandboxIntegration.h | 5 - .../CloudCanvasPythonWorkerInterface.h | 53 - .../MaglevControlPanelPlugin_stub.cpp | 31 - .../CryCommonTools/Export/AnimationData.cpp | 297 -- .../CryCommonTools/Export/AnimationData.h | 211 -- .../CryCommonTools/Export/CBAHelpers.cpp | 57 - Code/Tools/CryCommonTools/Export/CBAHelpers.h | 27 - .../Export/ColladaExportWriter.cpp | 556 ---- .../Export/ColladaExportWriter.h | 29 - .../CryCommonTools/Export/ColladaWriter.cpp | 2918 ----------------- .../CryCommonTools/Export/ColladaWriter.h | 32 - .../CryCommonTools/Export/ExportFileType.cpp | 66 - .../CryCommonTools/Export/ExportFileType.h | 42 - .../CryCommonTools/Export/ExportHelpers.h | 83 - .../Export/ExportSourceDecoratorBase.cpp | 130 - .../Export/ExportSourceDecoratorBase.h | 54 - .../Export/ExportStatusWindow.cpp | 215 -- .../Export/ExportStatusWindow.h | 67 - .../CryCommonTools/Export/GeometryData.cpp | 82 - .../CryCommonTools/Export/GeometryData.h | 102 - .../Export/GeometryExportSourceAdapter.cpp | 54 - .../Export/GeometryExportSourceAdapter.h | 36 - .../Export/GeometryFileData.cpp | 59 - .../CryCommonTools/Export/GeometryFileData.h | 52 - .../Export/GeometryMaterialData.cpp | 36 - .../Export/GeometryMaterialData.h | 35 - Code/Tools/CryCommonTools/Export/HelperData.h | 41 - .../CryCommonTools/Export/IAnimationData.h | 96 - .../CryCommonTools/Export/IExportContext.h | 55 - .../CryCommonTools/Export/IExportSource.h | 98 - .../CryCommonTools/Export/IExportWriter.h | 28 - .../CryCommonTools/Export/IGeometryData.h | 35 - .../CryCommonTools/Export/IGeometryFileData.h | 54 - .../Export/IGeometryMaterialData.h | 27 - .../CryCommonTools/Export/IMaterialData.h | 33 - Code/Tools/CryCommonTools/Export/IModelData.h | 36 - Code/Tools/CryCommonTools/Export/IMorphData.h | 29 - .../CryCommonTools/Export/ISkeletonData.h | 56 - .../CryCommonTools/Export/ISkinningData.h | 26 - .../CryCommonTools/Export/MaterialData.cpp | 69 - .../CryCommonTools/Export/MaterialData.h | 56 - .../CryCommonTools/Export/MaterialHelpers.cpp | 107 - .../CryCommonTools/Export/MaterialHelpers.h | 39 - Code/Tools/CryCommonTools/Export/MaxHelpers.h | 138 - .../Export/MaxUserPropertyHelpers.cpp | 99 - .../Export/MaxUserPropertyHelpers.h | 32 - Code/Tools/CryCommonTools/Export/MeshUtils.h | 914 ------ .../Tools/CryCommonTools/Export/ModelData.cpp | 118 - Code/Tools/CryCommonTools/Export/ModelData.h | 63 - .../Tools/CryCommonTools/Export/MorphData.cpp | 55 - Code/Tools/CryCommonTools/Export/MorphData.h | 52 - .../SingleAnimationExportSourceAdapter.cpp | 86 - .../SingleAnimationExportSourceAdapter.h | 45 - .../CryCommonTools/Export/SkeletonData.cpp | 309 -- .../CryCommonTools/Export/SkeletonData.h | 116 - .../CryCommonTools/Export/SkinningData.cpp | 45 - .../CryCommonTools/Export/SkinningData.h | 46 - .../CryCommonTools/Export/TransformHelpers.h | 119 - Code/Tools/CryCommonTools/UI/EULADialog.cpp | 132 - Code/Tools/CryCommonTools/UI/EULADialog.h | 55 - Code/Tools/CryCommonTools/UI/EditControl.cpp | 48 - Code/Tools/CryCommonTools/UI/EditControl.h | 36 - Code/Tools/CryCommonTools/UI/FrameWindow.cpp | 116 - Code/Tools/CryCommonTools/UI/FrameWindow.h | 44 - Code/Tools/CryCommonTools/UI/IUIComponent.h | 28 - Code/Tools/CryCommonTools/UI/Layout.cpp | 233 -- Code/Tools/CryCommonTools/UI/Layout.h | 61 - Code/Tools/CryCommonTools/UI/ListView.cpp | 96 - Code/Tools/CryCommonTools/UI/ListView.h | 42 - Code/Tools/CryCommonTools/UI/LogWindow.cpp | 158 - Code/Tools/CryCommonTools/UI/LogWindow.h | 71 - Code/Tools/CryCommonTools/UI/ProgressBar.cpp | 65 - Code/Tools/CryCommonTools/UI/ProgressBar.h | 39 - Code/Tools/CryCommonTools/UI/PushButton.cpp | 64 - Code/Tools/CryCommonTools/UI/PushButton.h | 78 - Code/Tools/CryCommonTools/UI/Spacer.cpp | 43 - Code/Tools/CryCommonTools/UI/Spacer.h | 40 - Code/Tools/CryCommonTools/UI/TaskList.cpp | 148 - Code/Tools/CryCommonTools/UI/TaskList.h | 48 - Code/Tools/CryCommonTools/UI/ToggleButton.cpp | 65 - Code/Tools/CryCommonTools/UI/ToggleButton.h | 78 - Code/Tools/CryCommonTools/UI/Win32GUI.cpp | 390 --- Code/Tools/CryCommonTools/UI/Win32GUI.h | 216 -- .../Code/Editor/PropertyHandlerSprite.cpp | 2 - 198 files changed, 29 insertions(+), 28558 deletions(-) delete mode 100644 Assets/Engine/Config/engine_core.thread_config delete mode 100644 Assets/Engine/Config/engine_sandbox.thread_config delete mode 100644 Code/CryEngine/CryCommon/EngineSettingsBackend.cpp delete mode 100644 Code/CryEngine/CryCommon/EngineSettingsBackend.h delete mode 100644 Code/CryEngine/CryCommon/EngineSettingsBackendApple.cpp delete mode 100644 Code/CryEngine/CryCommon/EngineSettingsBackendApple.h delete mode 100644 Code/CryEngine/CryCommon/EngineSettingsBackendWin32.cpp delete mode 100644 Code/CryEngine/CryCommon/EngineSettingsBackendWin32.h delete mode 100644 Code/CryEngine/CryCommon/EngineSettingsManager.cpp delete mode 100644 Code/CryEngine/CryCommon/EngineSettingsManager.h delete mode 100644 Code/CryEngine/CryCommon/IFlares.h delete mode 100644 Code/CryEngine/CryCommon/IMaterialEffects.h delete mode 100644 Code/CryEngine/CryCommon/INotificationNetwork.h delete mode 100644 Code/CryEngine/CryCommon/IResourceCompilerHelper.cpp delete mode 100644 Code/CryEngine/CryCommon/IResourceCompilerHelper.h delete mode 100644 Code/CryEngine/CryCommon/ISoftCodeMgr.h delete mode 100644 Code/CryEngine/CryCommon/ISystemScheduler.h delete mode 100644 Code/CryEngine/CryCommon/IThreadManager.h delete mode 100644 Code/CryEngine/CryCommon/IThreadTask.h delete mode 100644 Code/CryEngine/CryCommon/Platform/Mac/crycommon_enginesettings_mac_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Windows/crycommon_enginesettings_windows_files.cmake delete mode 100644 Code/CryEngine/CryCommon/ProfileLog.h delete mode 100644 Code/CryEngine/CryCommon/ResourceCompilerHelper.cpp delete mode 100644 Code/CryEngine/CryCommon/ResourceCompilerHelper.h delete mode 100644 Code/CryEngine/CryCommon/SettingsManagerHelpers.cpp delete mode 100644 Code/CryEngine/CryCommon/SettingsManagerHelpers.h delete mode 100644 Code/CryEngine/CryCommon/crycommon_enginesettings_files.cmake delete mode 100644 Code/CryEngine/CrySystem/CryThreadUtil_pthread.h delete mode 100644 Code/CryEngine/CrySystem/CryThreadUtil_win32_thread.h delete mode 100644 Code/CryEngine/CrySystem/DebugCallStack.cpp delete mode 100644 Code/CryEngine/CrySystem/DebugCallStack.h delete mode 100644 Code/CryEngine/CrySystem/IDebugCallStack.cpp delete mode 100644 Code/CryEngine/CrySystem/IDebugCallStack.h delete mode 100644 Code/CryEngine/CrySystem/IThreadConfigManager.h delete mode 100644 Code/CryEngine/CrySystem/NotificationNetwork.cpp delete mode 100644 Code/CryEngine/CrySystem/NotificationNetwork.h delete mode 100644 Code/CryEngine/CrySystem/ProfileLogSystem.cpp delete mode 100644 Code/CryEngine/CrySystem/ProfileLogSystem.h delete mode 100644 Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.cpp delete mode 100644 Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.h delete mode 100644 Code/CryEngine/CrySystem/SystemScheduler.cpp delete mode 100644 Code/CryEngine/CrySystem/SystemScheduler.h delete mode 100644 Code/CryEngine/CrySystem/SystemThreading.cpp delete mode 100644 Code/CryEngine/CrySystem/ThreadConfigManager.cpp delete mode 100644 Code/CryEngine/CrySystem/ThreadConfigManager.h delete mode 100644 Code/CryEngine/CrySystem/ThreadInfo.cpp delete mode 100644 Code/CryEngine/CrySystem/ThreadInfo.h delete mode 100644 Code/CryEngine/CrySystem/ThreadTask.cpp delete mode 100644 Code/CryEngine/CrySystem/ThreadTask.h delete mode 100644 Code/CryEngine/CrySystem/UnitTests/CryMathTests.cpp delete mode 100644 Code/CryEngine/CrySystem/UnitTests/CryPakUnitTests.cpp delete mode 100644 Code/Sandbox/Editor/BackgroundScheduleManager.cpp delete mode 100644 Code/Sandbox/Editor/BackgroundScheduleManager.h delete mode 100644 Code/Sandbox/Editor/BackgroundTaskManager.cpp delete mode 100644 Code/Sandbox/Editor/BackgroundTaskManager.h delete mode 100644 Code/Sandbox/Editor/Include/IBackgroundScheduleManager.h delete mode 100644 Code/Sandbox/Editor/Include/IBackgroundTaskManager.h delete mode 100644 Code/Sandbox/Plugins/MaglevControlPanel/CloudCanvasPythonWorkerInterface.h delete mode 100644 Code/Sandbox/Plugins/MaglevControlPanel/MaglevControlPanelPlugin_stub.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/AnimationData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/AnimationData.h delete mode 100644 Code/Tools/CryCommonTools/Export/CBAHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/CBAHelpers.h delete mode 100644 Code/Tools/CryCommonTools/Export/ColladaExportWriter.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/ColladaExportWriter.h delete mode 100644 Code/Tools/CryCommonTools/Export/ColladaWriter.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/ColladaWriter.h delete mode 100644 Code/Tools/CryCommonTools/Export/ExportFileType.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/ExportFileType.h delete mode 100644 Code/Tools/CryCommonTools/Export/ExportHelpers.h delete mode 100644 Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.h delete mode 100644 Code/Tools/CryCommonTools/Export/ExportStatusWindow.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/ExportStatusWindow.h delete mode 100644 Code/Tools/CryCommonTools/Export/GeometryData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/GeometryData.h delete mode 100644 Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.h delete mode 100644 Code/Tools/CryCommonTools/Export/GeometryFileData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/GeometryFileData.h delete mode 100644 Code/Tools/CryCommonTools/Export/GeometryMaterialData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/GeometryMaterialData.h delete mode 100644 Code/Tools/CryCommonTools/Export/HelperData.h delete mode 100644 Code/Tools/CryCommonTools/Export/IAnimationData.h delete mode 100644 Code/Tools/CryCommonTools/Export/IExportContext.h delete mode 100644 Code/Tools/CryCommonTools/Export/IExportSource.h delete mode 100644 Code/Tools/CryCommonTools/Export/IExportWriter.h delete mode 100644 Code/Tools/CryCommonTools/Export/IGeometryData.h delete mode 100644 Code/Tools/CryCommonTools/Export/IGeometryFileData.h delete mode 100644 Code/Tools/CryCommonTools/Export/IGeometryMaterialData.h delete mode 100644 Code/Tools/CryCommonTools/Export/IMaterialData.h delete mode 100644 Code/Tools/CryCommonTools/Export/IModelData.h delete mode 100644 Code/Tools/CryCommonTools/Export/IMorphData.h delete mode 100644 Code/Tools/CryCommonTools/Export/ISkeletonData.h delete mode 100644 Code/Tools/CryCommonTools/Export/ISkinningData.h delete mode 100644 Code/Tools/CryCommonTools/Export/MaterialData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/MaterialData.h delete mode 100644 Code/Tools/CryCommonTools/Export/MaterialHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/MaterialHelpers.h delete mode 100644 Code/Tools/CryCommonTools/Export/MaxHelpers.h delete mode 100644 Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.h delete mode 100644 Code/Tools/CryCommonTools/Export/MeshUtils.h delete mode 100644 Code/Tools/CryCommonTools/Export/ModelData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/ModelData.h delete mode 100644 Code/Tools/CryCommonTools/Export/MorphData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/MorphData.h delete mode 100644 Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.h delete mode 100644 Code/Tools/CryCommonTools/Export/SkeletonData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/SkeletonData.h delete mode 100644 Code/Tools/CryCommonTools/Export/SkinningData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/SkinningData.h delete mode 100644 Code/Tools/CryCommonTools/Export/TransformHelpers.h delete mode 100644 Code/Tools/CryCommonTools/UI/EULADialog.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/EULADialog.h delete mode 100644 Code/Tools/CryCommonTools/UI/EditControl.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/EditControl.h delete mode 100644 Code/Tools/CryCommonTools/UI/FrameWindow.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/FrameWindow.h delete mode 100644 Code/Tools/CryCommonTools/UI/IUIComponent.h delete mode 100644 Code/Tools/CryCommonTools/UI/Layout.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/Layout.h delete mode 100644 Code/Tools/CryCommonTools/UI/ListView.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/ListView.h delete mode 100644 Code/Tools/CryCommonTools/UI/LogWindow.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/LogWindow.h delete mode 100644 Code/Tools/CryCommonTools/UI/ProgressBar.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/ProgressBar.h delete mode 100644 Code/Tools/CryCommonTools/UI/PushButton.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/PushButton.h delete mode 100644 Code/Tools/CryCommonTools/UI/Spacer.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/Spacer.h delete mode 100644 Code/Tools/CryCommonTools/UI/TaskList.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/TaskList.h delete mode 100644 Code/Tools/CryCommonTools/UI/ToggleButton.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/ToggleButton.h delete mode 100644 Code/Tools/CryCommonTools/UI/Win32GUI.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/Win32GUI.h diff --git a/Assets/Engine/Config/engine_core.thread_config b/Assets/Engine/Config/engine_core.thread_config deleted file mode 100644 index f9183d9174..0000000000 --- a/Assets/Engine/Config/engine_core.thread_config +++ /dev/null @@ -1,402 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Assets/Engine/Config/engine_sandbox.thread_config b/Assets/Engine/Config/engine_sandbox.thread_config deleted file mode 100644 index 7c0dc00b71..0000000000 --- a/Assets/Engine/Config/engine_sandbox.thread_config +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Code/CryEngine/CryCommon/CMakeLists.txt b/Code/CryEngine/CryCommon/CMakeLists.txt index 4725489358..5105ff1a5b 100644 --- a/Code/CryEngine/CryCommon/CMakeLists.txt +++ b/Code/CryEngine/CryCommon/CMakeLists.txt @@ -32,41 +32,6 @@ ly_add_target( AZ::AzFramework ) -ly_add_target( - NAME CryCommon.EngineSettings.Static STATIC - NAMESPACE Legacy - FILES_CMAKE - crycommon_enginesettings_files.cmake - ${pal_dir}/crycommon_enginesettings_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - . - ${pal_dir} - BUILD_DEPENDENCIES - PUBLIC - AZ::AzCore - AZ::AzFramework -) - -ly_add_target( - NAME CryCommon.EngineSettings.RC.Static STATIC - NAMESPACE Legacy - FILES_CMAKE - crycommon_enginesettings_files.cmake - ${pal_dir}/crycommon_enginesettings_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - . - ${pal_dir} - COMPILE_DEFINITIONS - PRIVATE - RESOURCE_COMPILER - BUILD_DEPENDENCIES - PUBLIC - AZ::AzCore - AZ::AzFramework -) - if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) ly_add_target( diff --git a/Code/CryEngine/CryCommon/CryAssert_Android.h b/Code/CryEngine/CryCommon/CryAssert_Android.h index 68f716ec28..6e60df1bb1 100644 --- a/Code/CryEngine/CryCommon/CryAssert_Android.h +++ b/Code/CryEngine/CryCommon/CryAssert_Android.h @@ -31,7 +31,7 @@ void CryAssertTrace(const char* szFormat, ...) return; } - if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting) + if (!gEnv->bIgnoreAllAsserts) { if (szFormat == NULL) { diff --git a/Code/CryEngine/CryCommon/CryAssert_Linux.h b/Code/CryEngine/CryCommon/CryAssert_Linux.h index 7c52f78366..f0acdd79db 100644 --- a/Code/CryEngine/CryCommon/CryAssert_Linux.h +++ b/Code/CryEngine/CryCommon/CryAssert_Linux.h @@ -34,7 +34,7 @@ void CryAssertTrace(const char* szFormat, ...) return; } - if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting) + if (!gEnv->bIgnoreAllAsserts) { if (szFormat == NULL) { diff --git a/Code/CryEngine/CryCommon/CryAssert_Mac.h b/Code/CryEngine/CryCommon/CryAssert_Mac.h index 9502605fea..f7f74c3b58 100644 --- a/Code/CryEngine/CryCommon/CryAssert_Mac.h +++ b/Code/CryEngine/CryCommon/CryAssert_Mac.h @@ -30,7 +30,7 @@ void CryAssertTrace(const char* szFormat, ...) return; } - if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting) + if (!gEnv->bIgnoreAllAsserts) { if (szFormat == NULL) { diff --git a/Code/CryEngine/CryCommon/CryAssert_iOS.h b/Code/CryEngine/CryCommon/CryAssert_iOS.h index ad668fb131..2cb08befff 100644 --- a/Code/CryEngine/CryCommon/CryAssert_iOS.h +++ b/Code/CryEngine/CryCommon/CryAssert_iOS.h @@ -31,7 +31,7 @@ void CryAssertTrace(const char* szFormat, ...) return; } - if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting) + if (!gEnv->bIgnoreAllAsserts) { if (szFormat == NULL) { diff --git a/Code/CryEngine/CryCommon/CryAssert_impl.h b/Code/CryEngine/CryCommon/CryAssert_impl.h index ed55162f1a..edbbb2f0c4 100644 --- a/Code/CryEngine/CryCommon/CryAssert_impl.h +++ b/Code/CryEngine/CryCommon/CryAssert_impl.h @@ -305,7 +305,7 @@ void CryAssertTrace(const char* _pszFormat, ...) { return; } - if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting) + if (!gEnv->bIgnoreAllAsserts) { if (NULL == _pszFormat) { diff --git a/Code/CryEngine/CryCommon/CrySystemBus.h b/Code/CryEngine/CryCommon/CrySystemBus.h index f183de0fa9..def1ce4688 100644 --- a/Code/CryEngine/CryCommon/CrySystemBus.h +++ b/Code/CryEngine/CryCommon/CrySystemBus.h @@ -49,12 +49,6 @@ public: //! ISystem has shut down. virtual void OnCrySystemPostShutdown() {} - //! Engine pre physics update. - virtual void OnCrySystemPrePhysicsUpdate() {} - - //! Engine post physics update. - virtual void OnCrySystemPostPhysicsUpdate() {} - //! Sent when a new level is being created. virtual void OnCryEditorBeginCreate() {} diff --git a/Code/CryEngine/CryCommon/CryThread.h b/Code/CryEngine/CryCommon/CryThread.h index f1e97b2199..9aa7bce128 100644 --- a/Code/CryEngine/CryCommon/CryThread.h +++ b/Code/CryEngine/CryCommon/CryThread.h @@ -37,9 +37,6 @@ enum CryLockType #define CRYLOCK_HAVE_FASTLOCK 1 -void CryThreadSetName(threadID nThreadId, const char* sThreadName); -const char* CryThreadGetName(threadID nThreadId); - ///////////////////////////////////////////////////////////////////////////// // // Primitive locks and conditions. diff --git a/Code/CryEngine/CryCommon/CryThreadImpl.h b/Code/CryEngine/CryCommon/CryThreadImpl.h index b151b3da8a..da9be86dd5 100644 --- a/Code/CryEngine/CryCommon/CryThreadImpl.h +++ b/Code/CryEngine/CryCommon/CryThreadImpl.h @@ -31,22 +31,3 @@ #else // Put other platform specific includes here! #endif - -#include - -void CryThreadSetName(threadID dwThreadId, const char* sThreadName) -{ - if (gEnv && gEnv->pSystem && gEnv->pSystem->GetIThreadTaskManager()) - { - gEnv->pSystem->GetIThreadTaskManager()->SetThreadName(dwThreadId, sThreadName); - } -} - -const char* CryThreadGetName(threadID dwThreadId) -{ - if (gEnv && gEnv->pSystem && gEnv->pSystem->GetIThreadTaskManager()) - { - return gEnv->pSystem->GetIThreadTaskManager()->GetThreadName(dwThreadId); - } - return ""; -} diff --git a/Code/CryEngine/CryCommon/CryThreadImpl_windows.h b/Code/CryEngine/CryCommon/CryThreadImpl_windows.h index 6f37edeea1..3ff28a81be 100644 --- a/Code/CryEngine/CryCommon/CryThreadImpl_windows.h +++ b/Code/CryEngine/CryCommon/CryThreadImpl_windows.h @@ -13,8 +13,6 @@ #pragma once -//#include - #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif diff --git a/Code/CryEngine/CryCommon/CryThread_windows.h b/Code/CryEngine/CryCommon/CryThread_windows.h index 1d9ea6dc31..b70260c7ac 100644 --- a/Code/CryEngine/CryCommon/CryThread_windows.h +++ b/Code/CryEngine/CryCommon/CryThread_windows.h @@ -249,10 +249,6 @@ public: void SetName(const char* Name) { m_name = Name; - if (m_threadId) - { - CryThreadSetName(m_threadId, m_name); - } } const char* GetName() { return m_name; } @@ -289,11 +285,6 @@ private: self->m_bIsStarted = true; self->m_bIsRunning = true; - if (!self->m_name.empty()) - { - CryThreadSetName(-1, self->m_name); - } - self->m_Runnable->Run(); self->m_bIsRunning = false; self->m_bCreatedThread = false; @@ -311,11 +302,6 @@ private: self->m_bIsStarted = true; self->m_bIsRunning = true; - if (!self->m_name.empty()) - { - CryThreadSetName(-1, self->m_name); - } - self->Run(); self->m_bIsRunning = false; self->m_bCreatedThread = false; diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackend.cpp b/Code/CryEngine/CryCommon/EngineSettingsBackend.cpp deleted file mode 100644 index caf7e03f31..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackend.cpp +++ /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. - * - */ - - -#include "EngineSettingsBackend.h" - -#ifdef CRY_ENABLE_RC_HELPER - -CEngineSettingsBackend::CEngineSettingsBackend(CEngineSettingsManager* parent, const wchar_t* moduleName) - : m_parent(parent) - , m_moduleName() -{ - if (moduleName != nullptr) - { - m_moduleName = moduleName; - } -} - -CEngineSettingsBackend::~CEngineSettingsBackend() -{ - -} - -#endif // CRY_ENABLE_RC_HELPER - diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackend.h b/Code/CryEngine/CryCommon/EngineSettingsBackend.h deleted file mode 100644 index fce16517ec..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackend.h +++ /dev/null @@ -1,65 +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_CRYCOMMON_ENGINESETTINGSBACKEND_H -#define CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKEND_H -#pragma once - -#include "ProjectDefines.h" - -#ifdef CRY_ENABLE_RC_HELPER - -#include "SettingsManagerHelpers.h" - -#include - -class CEngineSettingsManager; - -class CEngineSettingsBackend -{ -public: - CEngineSettingsBackend(CEngineSettingsManager* parent, const wchar_t* moduleName = NULL); - virtual ~CEngineSettingsBackend(); - - virtual std::wstring GetModuleFilePath() const = 0; - - virtual bool GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) = 0; - virtual bool GetModuleSpecificIntEntry(const char* key, int& value) = 0; - virtual bool GetModuleSpecificBoolEntry(const char* key, bool& value) = 0; - - virtual bool SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) = 0; - virtual bool SetModuleSpecificIntEntry(const char* key, const int& value) = 0; - virtual bool SetModuleSpecificBoolEntry(const char* key, const bool& value) = 0; - - virtual bool GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) = 0; - - virtual void LoadEngineSettingsFromRegistry() = 0; - virtual bool StoreEngineSettingsToRegistry() = 0; - -protected: - CEngineSettingsManager* parent() const - { - return m_parent; - } - - const std::wstring& moduleName() const - { - return m_moduleName; - } - -private: - std::wstring m_moduleName; - CEngineSettingsManager* m_parent; -}; - -#endif // CRY_ENABLE_RC_HELPER - -#endif // CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKEND_H diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackendApple.cpp b/Code/CryEngine/CryCommon/EngineSettingsBackendApple.cpp deleted file mode 100644 index 06f8d532d3..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackendApple.cpp +++ /dev/null @@ -1,486 +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 "EngineSettingsBackendApple.h" - -#ifdef CRY_ENABLE_RC_HELPER - -#include "AzCore/PlatformDef.h" - -#if AZ_TRAIT_OS_PLATFORM_APPLE - -#include "EngineSettingsManager.h" -#include "SettingsManagerHelpers.h" - -#include "platform.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -using namespace SettingsManagerHelpers; - -static const char gDefaultRegistryLocation[] = "/EngineSettings.reg"; - -#define REG_SOFTWARE L"Software\\" -#define REG_COMPANY_NAME L"Amazon\\" -#define REG_PRODUCT_NAME L"Lumberyard\\" -#define REG_SETTING L"Settings\\" -#define REG_BASE_SETTING_KEY REG_SOFTWARE REG_COMPANY_NAME REG_PRODUCT_NAME REG_SETTING - -////////////////////////////////////////////////////////////////////////// -class SimpleRegistry -{ - typedef std::map< std::wstring, std::wstring > WStringMap; - std::map< std::wstring, WStringMap * > m_modules; - -public: - SimpleRegistry(); - ~SimpleRegistry(); - - void setBoolValue(const std::wstring& module, const std::wstring& key, bool value); - void setIntValue(const std::wstring& module, const std::wstring& key, int value); - void setStrValue(const std::wstring& module, const std::wstring& key, const std::wstring& value); - - bool getBoolValue(const std::wstring& module, const std::wstring& key, bool& value); - bool getIntValue(const std::wstring& module, const std::wstring& key, int& value); - bool getStrValue(const std::wstring& module, const std::wstring& key, std::wstring& value); - - bool loadFromFile(const char* fileName); - bool saveToFile(const char* fileName); - -protected: - void clear(); - -private: - static const wchar_t gSimpleMagic[]; - static const size_t gMetaCharCount; -}; - -const wchar_t SimpleRegistry::gSimpleMagic[] = L"FR0"; -const size_t SimpleRegistry::gMetaCharCount = sizeof(size_t) / sizeof(wchar_t); - -SimpleRegistry::SimpleRegistry() -{ -} - -SimpleRegistry::~SimpleRegistry() -{ - clear(); -} - -void SimpleRegistry::setBoolValue(const std::wstring& module, const std::wstring& key, bool value) -{ - return setStrValue(module, key, value ? L"true" : L"false"); -} - -void SimpleRegistry::setIntValue(const std::wstring& module, const std::wstring& key, int value) -{ - return setStrValue(module, key, std::to_wstring(value)); -} - -void SimpleRegistry::setStrValue(const std::wstring& module, const std::wstring& key, const std::wstring& value) -{ - WStringMap *map = nullptr; - - auto i = m_modules.find(module); - - if (i == m_modules.end()) - { - map = new WStringMap; - m_modules.emplace(module, map); - } - else - { - map = i->second; - } - - assert(map); - - (*map)[key] = value; -} - -bool SimpleRegistry::getBoolValue(const std::wstring& module, const std::wstring& key, bool& value) -{ - std::wstring str; - - if (!getStrValue(module, key, str)) - { - return false; - } - - value = (0 == str.compare(L"true")); - - return true; -} - -bool SimpleRegistry::getIntValue(const std::wstring& module, const std::wstring& key, int& value) -{ - std::wstring str; - - if (!getStrValue(module, key, str)) - { - return false; - } - - value = std::stoi(str); - - return true; -} - -bool SimpleRegistry::getStrValue(const std::wstring& module, const std::wstring& key, std::wstring& value) -{ - WStringMap *map = nullptr; - - auto mi = m_modules.find(module); - if (mi == m_modules.end()) - { - return false; - } - - map = mi->second; - assert(map); - - auto ki = map->find(key); - if (ki == map->end()) - { - return false; - } - - value = ki->second; - - return true; -} - -bool SimpleRegistry::loadFromFile(const char* fileName) -{ - clear(); - - std::wifstream file(fileName, std::ios_base::in|std::ios_base::binary); - file.imbue(std::locale(file.getloc(), new std::codecvt_utf16)); - if (!file.is_open()) - { - AZ_Warning("EngineSettings", false, "Failed to open registry settings file: %s", fileName); - return false; - } - - std::wstring module; - std::wstring key; - std::wstring value; - - wchar_t buffer[512]; - size_t size; - wchar_t meta[gMetaCharCount]; - - /* magic number */ - if(!file.read(buffer, sizeof(gSimpleMagic) / sizeof(wchar_t)) || - wcsncmp(gSimpleMagic, buffer, sizeof(gSimpleMagic) / sizeof(wchar_t)) != 0) - { - file.close(); - AZ_Warning("EngineSettings", false, "Failed to load registry settings from file: %s", fileName); - return false; - } - - while (file.good()) - { - file.read(meta, gMetaCharCount); - if (!file.good()) - { - break; - } - - memcpy(&size, meta, sizeof(size)); - file.read(buffer, size); - buffer[file.gcount()] = L'\0'; - module = buffer; - - file.read(meta, gMetaCharCount); - memcpy(&size, meta, sizeof(size)); - file.read(buffer, size); - buffer[file.gcount()] = L'\0'; - key = buffer; - - file.read(meta, gMetaCharCount); - memcpy(&size, meta, sizeof(size)); - file.read(buffer, size); - buffer[file.gcount()] = L'\0'; - value = buffer; - - setStrValue(module, key, value); - } - - file.close(); - - return true; -} - -bool SimpleRegistry::saveToFile(const char* fileName) -{ - std::wofstream file(fileName, std::ios_base::out|std::ios_base::trunc|std::ios_base::binary); - file.imbue(std::locale(file.getloc(), new std::codecvt_utf16)); - if (!file.is_open()) - { - return false; - } - - std::wstring module; - - size_t size; - wchar_t meta[gMetaCharCount]; - - /* magic number */ - file.write(gSimpleMagic, sizeof(gSimpleMagic) / sizeof(wchar_t)); - - for (auto j : m_modules) - { - module = j.first; - - for (auto i : *j.second) - { - size = module.size(); - memcpy(meta, &size, sizeof(meta)); - file.write(meta, gMetaCharCount); - file.write(module.c_str(), size); - - size = i.first.size(); - memcpy(meta, &size, sizeof(meta)); - file.write(meta, gMetaCharCount); - file.write(i.first.c_str(), size); - - size = i.second.size(); - memcpy(meta, &size, sizeof(meta)); - file.write(meta, gMetaCharCount); - file.write(i.second.c_str(), size); - } - } - - file.close(); - - return true; -} - -void SimpleRegistry::clear() -{ - for (auto pair : m_modules) - { - delete pair.second; - } - - m_modules.clear(); -} -////////////////////////////////////////////////////////////////////////// - -CEngineSettingsBackendApple::CEngineSettingsBackendApple(CEngineSettingsManager* parent, const wchar_t* moduleName) - : CEngineSettingsBackend(parent, moduleName) - , m_registry(new SimpleRegistry) - , m_registryFilePath() -{ - std::string rootValue = gEnv->pFileIO->GetAlias("@root@"); - if (rootValue.empty()) - { - AZ_Warning("EngineSettings", false, "Could not get engine root."); - return; - } - - rootValue.append(gDefaultRegistryLocation); - m_registryFilePath = rootValue; -} - -CEngineSettingsBackendApple::~CEngineSettingsBackendApple() -{ - delete m_registry, m_registry = nullptr; -} - -std::wstring CEngineSettingsBackendApple::GetModuleFilePath() const -{ - std::string path; - - std::wstring_convert> converter; - std::string module = converter.to_bytes(moduleName()); - - void* handle = ::dlopen(module.c_str(), RTLD_LAZY); - if (handle) - { - const int c = _dyld_image_count(); - for (int i = 0; i < c; ++i) - { - const char* image = _dyld_get_image_name(i); - const void* altHandle = dlopen(image, RTLD_LAZY); - if (handle == altHandle) - { - char absImage[PATH_MAX]; - realpath(image, absImage); - char *ext = rindex(absImage, '.'); - if (ext) - { - *ext = '\0'; - } - path.append(absImage); - path.append(".ini"); - break; - } - } - } - - return converter.from_bytes(path); -} - -bool CEngineSettingsBackendApple::GetModuleSpecificStringEntryUtf16(const char* key, CWCharBuffer wbuffer) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - std::wstring str; - if (!m_registry->getStrValue(moduleName(), wkey, str)) - { - return false; - } - - std::wcscpy(wbuffer.getPtr(), str.c_str()); - - return true; -} - -bool CEngineSettingsBackendApple::GetModuleSpecificIntEntry(const char* key, int& value) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - return m_registry->getIntValue(moduleName(), wkey, value); -} - -bool CEngineSettingsBackendApple::GetModuleSpecificBoolEntry(const char* key, bool& value) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - return m_registry->getBoolValue(moduleName(), wkey, value); -} - -bool CEngineSettingsBackendApple::SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - m_registry->setStrValue(moduleName(), wkey, str); - - return true; -} - -bool CEngineSettingsBackendApple::SetModuleSpecificIntEntry(const char* key, const int& value) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - m_registry->setIntValue(moduleName(), wkey, value); - - return true; -} - -bool CEngineSettingsBackendApple::SetModuleSpecificBoolEntry(const char* key, const bool& value) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - m_registry->setBoolValue(moduleName(), wkey, value); - - return true; -} - -bool CEngineSettingsBackendApple::GetInstalledBuildRootPathUtf16(const int index, CWCharBuffer name, CWCharBuffer path) -{ - return false; -} - -bool CEngineSettingsBackendApple::StoreEngineSettingsToRegistry() -{ - bool bRet = true; - wchar_t buffer[1024]; - - // ResourceCompiler Specific - if (parent()->GetValueByRef("RC_ShowWindow", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - m_registry->setBoolValue(REG_BASE_SETTING_KEY, L"RC_ShowWindow", b); - } - - if (parent()->GetValueByRef("RC_HideCustom", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - m_registry->setBoolValue(REG_BASE_SETTING_KEY, L"RC_HideCustom", b); - } - - if (parent()->GetValueByRef("RC_Parameters", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - m_registry->setStrValue(REG_BASE_SETTING_KEY, L"RC_Parameters", buffer); - } - - if (parent()->GetValueByRef("RC_EnableSourceControl", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - m_registry->setBoolValue(REG_BASE_SETTING_KEY, L"RC_EnableSourceControl", b); - } - - bRet &= m_registry->saveToFile(m_registryFilePath.c_str()); - return bRet; -} - -void CEngineSettingsBackendApple::LoadEngineSettingsFromRegistry() -{ - if (!m_registry->loadFromFile(m_registryFilePath.c_str())) - { - return; - } - - std::wstring wStrResult; - bool bResult; - - if (m_registry->getStrValue(REG_BASE_SETTING_KEY, L"RootPath", wStrResult)) - { - parent()->SetKey("ENG_RootPath", wStrResult.c_str()); - } - - // Engine Specific - if (m_registry->getStrValue(REG_BASE_SETTING_KEY, L"ENG_RootPath", wStrResult)) - { - parent()->SetKey("ENG_RootPath", wStrResult.c_str()); - } - - // ResourceCompiler Specific - if (m_registry->getBoolValue(REG_BASE_SETTING_KEY, L"RC_ShowWindow", bResult)) - { - parent()->SetKey("RC_ShowWindow", bResult); - } - if (m_registry->getBoolValue(REG_BASE_SETTING_KEY, L"RC_HideCustom", bResult)) - { - parent()->SetKey("RC_HideCustom", bResult); - } - if (m_registry->getStrValue(REG_BASE_SETTING_KEY, L"RC_Parameters", wStrResult)) - { - parent()->SetKey("RC_Parameters", wStrResult.c_str()); - } - if (m_registry->getBoolValue(REG_BASE_SETTING_KEY, L"RC_EnableSourceControl", bResult)) - { - parent()->SetKey("RC_EnableSourceControl", bResult); - } -} - -#endif // AZ_TRAIT_OS_PLATFORM_APPLE -#endif // CRY_ENABLE_RC_HELPER - diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackendApple.h b/Code/CryEngine/CryCommon/EngineSettingsBackendApple.h deleted file mode 100644 index efc5a12bed..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackendApple.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_CRYCOMMON_ENGINESETTINGSBACKENDAPPLE_H -#define CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDAPPLE_H -#pragma once - -#include "EngineSettingsBackend.h" - -#ifdef CRY_ENABLE_RC_HELPER - -class CEngineSettingsManager; -class SimpleRegistry; - -class CEngineSettingsBackendApple : public CEngineSettingsBackend -{ -public: - CEngineSettingsBackendApple(CEngineSettingsManager* parent, const wchar_t* moduleName = NULL); - ~CEngineSettingsBackendApple(); - - std::wstring GetModuleFilePath() const override; - - bool GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) override; - bool GetModuleSpecificIntEntry(const char* key, int& value) override; - bool GetModuleSpecificBoolEntry(const char* key, bool& value) override; - - bool SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) override; - bool SetModuleSpecificIntEntry(const char* key, const int& value) override; - bool SetModuleSpecificBoolEntry(const char* key, const bool& value) override; - - bool GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) override; - - void LoadEngineSettingsFromRegistry() override; - bool StoreEngineSettingsToRegistry() override; - -private: - SimpleRegistry *m_registry; - std::string m_registryFilePath; -}; - -#endif // CRY_ENABLE_RC_HELPER - -#endif // CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDAPPLE_H diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.cpp b/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.cpp deleted file mode 100644 index c2e9a67d57..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.cpp +++ /dev/null @@ -1,431 +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 "EngineSettingsBackendWin32.h" - -#ifdef CRY_ENABLE_RC_HELPER - -#include "AzCore/PlatformDef.h" - -#ifdef AZ_PLATFORM_WINDOWS - -#include "EngineSettingsManager.h" - -#include "platform.h" -#include - -#define REG_SOFTWARE L"Software\\" -#define REG_COMPANY_NAME L"Amazon\\" -#define REG_PRODUCT_NAME L"Open 3D Engine\\" -#define REG_SETTING L"Settings\\" -#define REG_BASE_SETTING_KEY REG_SOFTWARE REG_COMPANY_NAME REG_PRODUCT_NAME REG_SETTING - -EXTERN_C IMAGE_DOS_HEADER __ImageBase; - -using namespace SettingsManagerHelpers; - -static bool g_bWindowQuit; -static CEngineSettingsManager* g_pThis = 0; -static const unsigned int IDC_hEditRootPath = 100; -static const unsigned int IDC_hBtnBrowse = 101; - -namespace -{ - class RegKey - { - public: - RegKey(const wchar_t* key, bool writeable); - ~RegKey(); - void* pKey; - }; - - RegKey::RegKey(const wchar_t* key, bool writeable) - { - HKEY hKey; - LONG result; - if (writeable) - { - result = RegCreateKeyExW(HKEY_CURRENT_USER, key, 0, 0, 0, KEY_WRITE, 0, &hKey, 0); - } - else - { - result = RegOpenKeyExW(HKEY_CURRENT_USER, key, 0, KEY_READ, &hKey); - } - pKey = hKey; - } - - RegKey::~RegKey() - { - RegCloseKey((HKEY)pKey); - } -} - -CEngineSettingsBackendWin32::CEngineSettingsBackendWin32(CEngineSettingsManager* parent, const wchar_t* moduleName) - : CEngineSettingsBackend(parent, moduleName) -{ -} - -std::wstring CEngineSettingsBackendWin32::GetModuleFilePath() const -{ - wchar_t szFilename[_MAX_PATH]; - GetModuleFileNameW((HINSTANCE)&__ImageBase, szFilename, _MAX_PATH); - wchar_t drive[_MAX_DRIVE]; - wchar_t dir[_MAX_DIR]; - wchar_t fname[_MAX_FNAME]; - wchar_t ext[1] = L""; - _wsplitpath_s(szFilename, drive, dir, fname, ext); - _wmakepath_s(szFilename, drive, dir, fname, L"ini"); - return szFilename; -} - -bool CEngineSettingsBackendWin32::GetModuleSpecificStringEntryUtf16(const char* key, CWCharBuffer wbuffer) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), false); - if (!superKey.pKey) - { - wbuffer[0] = 0; - return false; - } - if (!GetRegValue(superKey.pKey, key, wbuffer)) - { - wbuffer[0] = 0; - return false; - } - - return true; -} - -bool CEngineSettingsBackendWin32::GetModuleSpecificIntEntry(const char* key, int& value) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), false); - if (!superKey.pKey) - { - return false; - } - if (!GetRegValue(superKey.pKey, key, value)) - { - value = 0; - return false; - } - - return true; -} - -bool CEngineSettingsBackendWin32::GetModuleSpecificBoolEntry(const char* key, bool& value) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), false); - if (!superKey.pKey) - { - return false; - } - if (!GetRegValue(superKey.pKey, key, value)) - { - value = false; - return false; - } - - return true; -} - -bool CEngineSettingsBackendWin32::SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), true); - if (superKey.pKey) - { - return SetRegValue(superKey.pKey, key, str); - } - return false; -} - -bool CEngineSettingsBackendWin32::SetModuleSpecificIntEntry(const char* key, const int& value) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), true); - if (superKey.pKey) - { - return SetRegValue(superKey.pKey, key, value); - } - return false; -} - -bool CEngineSettingsBackendWin32::SetModuleSpecificBoolEntry(const char* key, const bool& value) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), true); - if (superKey.pKey) - { - return SetRegValue(superKey.pKey, key, value); - } - return false; -} - -bool CEngineSettingsBackendWin32::GetInstalledBuildRootPathUtf16(const int index, CWCharBuffer name, CWCharBuffer path) -{ - RegKey key(REG_BASE_SETTING_KEY L"O3DEExport\\ProjectBuilds", false); - if (key.pKey) - { - DWORD type; - DWORD nameSizeInBytes = DWORD(name.getSizeInBytes()); - DWORD pathSizeInBytes = DWORD(path.getSizeInBytes()); - LONG result = RegEnumValueW((HKEY)key.pKey, index, name.getPtr(), &nameSizeInBytes, NULL, &type, (BYTE*)path.getPtr(), &pathSizeInBytes); - if (result == ERROR_SUCCESS) - { - return true; - } - } - return false; -} - -bool CEngineSettingsBackendWin32::StoreEngineSettingsToRegistry() -{ - // make sure the path in registry exists - { - RegKey key0(REG_SOFTWARE REG_COMPANY_NAME, true); - if (!key0.pKey) - { - RegKey software(REG_SOFTWARE, true); - HKEY hKey; - RegCreateKeyW((HKEY)software.pKey, REG_COMPANY_NAME, &hKey); - if (!hKey) - { - return false; - } - } - - RegKey key1(REG_SOFTWARE REG_COMPANY_NAME REG_PRODUCT_NAME, true); - if (!key1.pKey) - { - RegKey softwareCompany(REG_SOFTWARE REG_COMPANY_NAME, true); - HKEY hKey; - RegCreateKeyW((HKEY)softwareCompany.pKey, REG_COMPANY_NAME, &hKey); - if (!hKey) - { - return false; - } - } - - RegKey key2(REG_BASE_SETTING_KEY, true); - if (!key2.pKey) - { - RegKey softwareCompanyProduct(REG_SOFTWARE REG_COMPANY_NAME REG_PRODUCT_NAME, true); - HKEY hKey; - RegCreateKeyW((HKEY)key2.pKey, REG_SETTING, &hKey); - if (!hKey) - { - return false; - } - } - } - - bool bRet = true; - - RegKey key(REG_BASE_SETTING_KEY, true); - if (!key.pKey) - { - bRet = false; - } - else - { - wchar_t buffer[1024]; - - // ResourceCompiler Specific - - if (parent()->GetValueByRef("RC_ShowWindow", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - SetRegValue(key.pKey, "RC_ShowWindow", b); - } - - if (parent()->GetValueByRef("RC_HideCustom", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - SetRegValue(key.pKey, "RC_HideCustom", b); - } - - if (parent()->GetValueByRef("RC_Parameters", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - SetRegValue(key.pKey, "RC_Parameters", buffer); - } - - if (parent()->GetValueByRef("RC_EnableSourceControl", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - SetRegValue(key.pKey, "RC_EnableSourceControl", b); - } - } - - return bRet; -} - -void CEngineSettingsBackendWin32::LoadEngineSettingsFromRegistry() -{ - wchar_t buffer[1024]; - - bool bResult; - - // Engine Specific (Deprecated value) - RegKey key(REG_BASE_SETTING_KEY, false); - if (key.pKey) - { - if (GetRegValue(key.pKey, "RootPath", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - parent()->SetKey("ENG_RootPath", buffer); - } - - // Engine Specific - if (GetRegValue(key.pKey, "ENG_RootPath", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - parent()->SetKey("ENG_RootPath", buffer); - } - - // ResourceCompiler Specific - if (GetRegValue(key.pKey, "RC_ShowWindow", bResult)) - { - parent()->SetKey("RC_ShowWindow", bResult); - } - if (GetRegValue(key.pKey, "RC_HideCustom", bResult)) - { - parent()->SetKey("RC_HideCustom", bResult); - } - if (GetRegValue(key.pKey, "RC_Parameters", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - parent()->SetKey("RC_Parameters", buffer); - } - if (GetRegValue(key.pKey, "RC_EnableSourceControl", bResult)) - { - parent()->SetKey("RC_EnableSourceControl", bResult); - } - } -} - -bool CEngineSettingsBackendWin32::SetRegValue(void* key, const char* valueName, const wchar_t* value) -{ - CFixedString name; - name.appendAscii(valueName); - - size_t const sizeInBytes = (wcslen(value) + 1) * sizeof(value[0]); - return (ERROR_SUCCESS == RegSetValueExW((HKEY)key, name.c_str(), 0, REG_SZ, (BYTE*)value, DWORD(sizeInBytes))); -} - -bool CEngineSettingsBackendWin32::SetRegValue(void* key, const char* valueName, bool value) -{ - CFixedString name; - name.appendAscii(valueName); - - DWORD dwVal = value; - return (ERROR_SUCCESS == RegSetValueExW((HKEY)key, name.c_str(), 0, REG_DWORD, (BYTE*)&dwVal, sizeof(dwVal))); -} - -bool CEngineSettingsBackendWin32::SetRegValue(void* key, const char* valueName, int value) -{ - CFixedString name; - name.appendAscii(valueName); - - DWORD dwVal = value; - return (ERROR_SUCCESS == RegSetValueExW((HKEY)key, name.c_str(), 0, REG_DWORD, (BYTE*)&dwVal, sizeof(dwVal))); -} - -bool CEngineSettingsBackendWin32::GetRegValue(void* key, const char* valueName, CWCharBuffer wbuffer) -{ - if (wbuffer.getSizeInElements() <= 0) - { - return false; - } - - CFixedString name; - name.appendAscii(valueName); - - DWORD type; - DWORD sizeInBytes = DWORD(wbuffer.getSizeInBytes()); - if (ERROR_SUCCESS != RegQueryValueExW((HKEY)key, name.c_str(), NULL, &type, (BYTE*)wbuffer.getPtr(), &sizeInBytes)) - { - wbuffer[0] = 0; - return false; - } - - const size_t sizeInElements = sizeInBytes / sizeof(wbuffer[0]); - if (sizeInElements > wbuffer.getSizeInElements()) // paranoid check - { - wbuffer[0] = 0; - return false; - } - - // According to MSDN documentation for RegQueryValueEx(), strings returned by the function - // are not zero-terminated sometimes, so we need to terminate them by ourselves. - if (wbuffer[sizeInElements - 1] != 0) - { - if (sizeInElements >= wbuffer.getSizeInElements()) - { - // No space left to put terminating zero character - wbuffer[0] = 0; - return false; - } - wbuffer[sizeInElements] = 0; - } - - return true; -} - -bool CEngineSettingsBackendWin32::GetRegValue(void* key, const char* valueName, bool& value) -{ - CFixedString name; - name.appendAscii(valueName); - - // Open the appropriate registry key - DWORD type, dwVal = 0, size = sizeof(dwVal); - bool res = (ERROR_SUCCESS == RegQueryValueExW((HKEY)key, name.c_str(), NULL, &type, (BYTE*)&dwVal, &size)); - if (res) - { - value = (dwVal != 0); - } - else - { - wchar_t buffer[100]; - res = GetRegValue(key, valueName, CWCharBuffer(buffer, sizeof(buffer))); - if (res) - { - value = (wcscmp(buffer, L"true") == 0); - } - } - return res; -} - -bool CEngineSettingsBackendWin32::GetRegValue(void* key, const char* valueName, int& value) -{ - CFixedString name; - name.appendAscii(valueName); - - // Open the appropriate registry key - DWORD type, dwVal = 0, size = sizeof(dwVal); - - bool res = (ERROR_SUCCESS == RegQueryValueExW((HKEY)key, name.c_str(), NULL, &type, (BYTE*)&dwVal, &size)); - if (res) - { - value = dwVal; - } - - return res; -} - -#endif // AZ_PLATFORM_WINDOWS -#endif // CRY_ENABLE_RC_HELPER diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.h b/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.h deleted file mode 100644 index 47b4772ede..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.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. - * - */ -#ifndef CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDWIN32_H -#define CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDWIN32_H -#pragma once - -#include "EngineSettingsBackend.h" - -#ifdef CRY_ENABLE_RC_HELPER - -class CEngineSettingsManager; - -class CEngineSettingsBackendWin32 : public CEngineSettingsBackend -{ -public: - CEngineSettingsBackendWin32(CEngineSettingsManager* parent, const wchar_t* moduleName = NULL); - - std::wstring GetModuleFilePath() const override; - - bool GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) override; - bool GetModuleSpecificIntEntry(const char* key, int& value) override; - bool GetModuleSpecificBoolEntry(const char* key, bool& value) override; - - bool SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) override; - bool SetModuleSpecificIntEntry(const char* key, const int& value) override; - bool SetModuleSpecificBoolEntry(const char* key, const bool& value) override; - - bool GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) override; - - void LoadEngineSettingsFromRegistry() override; - bool StoreEngineSettingsToRegistry() override; - -protected: - bool SetRegValue(void* key, const char* valueName, const wchar_t* value); - bool SetRegValue(void* key, const char* valueName, bool value); - bool SetRegValue(void* key, const char* valueName, int value); - bool GetRegValue(void* key, const char* valueName, SettingsManagerHelpers::CWCharBuffer wbuffer); - bool GetRegValue(void* key, const char* valueName, bool& value); - bool GetRegValue(void* key, const char* valueName, int& value); -}; - -#endif // CRY_ENABLE_RC_HELPER - -#endif // CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDWIN32_H diff --git a/Code/CryEngine/CryCommon/EngineSettingsManager.cpp b/Code/CryEngine/CryCommon/EngineSettingsManager.cpp deleted file mode 100644 index 13ad568217..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsManager.cpp +++ /dev/null @@ -1,479 +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 "ProjectDefines.h" -#include "EngineSettingsManager.h" - -#if defined(CRY_ENABLE_RC_HELPER) - -#include // assert() -#include "EngineSettingsBackend.h" - -#include "AzCore/PlatformDef.h" -#include "platform.h" - -#if defined(AZ_PLATFORM_WINDOWS) -#include "EngineSettingsBackendWin32.h" -#include -#elif AZ_TRAIT_OS_PLATFORM_APPLE -#include "EngineSettingsBackendApple.h" -#endif - - -#include -#include - -#define INFOTEXT L"Please specify the directory of your CryENGINE installation (RootPath):" - - -using namespace SettingsManagerHelpers; - - -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -CEngineSettingsManager::CEngineSettingsManager(const wchar_t* moduleName, const wchar_t* iniFileName) - : m_hWndParent(0) - , m_backend(NULL) -{ - m_sModuleName.clear(); - -#if defined(AZ_PLATFORM_WINDOWS) - m_backend = new CEngineSettingsBackendWin32(this, moduleName); -#elif AZ_TRAIT_OS_PLATFORM_APPLE - m_backend = new CEngineSettingsBackendApple(this, moduleName); -#endif - assert(m_backend); - - // std initialization - RestoreDefaults(); - - // try to load content from INI file - if (moduleName != NULL) - { - m_sModuleName = moduleName; - - if (iniFileName == NULL) - { - // find INI filename located in module path - m_sModuleFileName = m_backend->GetModuleFilePath().c_str(); - } - else - { - m_sModuleFileName = iniFileName; - } - - if (LoadValuesFromConfigFile(m_sModuleFileName.c_str())) - { - m_bGetDataFromBackend = false; - return; - } - } - - m_bGetDataFromBackend = true; - - // load basic content from registry - LoadEngineSettingsFromRegistry(); -} - -////////////////////////////////////////////////////////////////////////// -CEngineSettingsManager::~CEngineSettingsManager() -{ - delete m_backend, m_backend = NULL; -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::RestoreDefaults() -{ - // Engine - SetKey("ENG_RootPath", L""); - - // RC - SetKey("RC_ShowWindow", false); - SetKey("RC_HideCustom", false); - SetKey("RC_Parameters", L""); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) -{ - if (wbuffer.getSizeInElements() <= 0) - { - return false; - } - - if (!m_bGetDataFromBackend) - { - if (!HasKey(key)) - { - wbuffer[0] = 0; - return false; - } - if (!GetValueByRef(key, wbuffer)) - { - wbuffer[0] = 0; - return false; - } - } - else - { - assert(m_backend); - return m_backend->GetModuleSpecificStringEntryUtf16(key, wbuffer); - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetModuleSpecificStringEntryUtf8(const char* key, SettingsManagerHelpers::CCharBuffer buffer) -{ - if (buffer.getSizeInElements() <= 0) - { - return false; - } - - wchar_t wBuffer[1024]; - - if (!GetModuleSpecificStringEntryUtf16(key, SettingsManagerHelpers::CWCharBuffer(wBuffer, sizeof(wBuffer)))) - { - buffer[0] = 0; - return false; - } - - SettingsManagerHelpers::ConvertUtf16ToUtf8(wBuffer, buffer); - - return true; -} - - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetModuleSpecificIntEntry(const char* key, int& value) -{ - value = 0; - - if (!m_bGetDataFromBackend) - { - if (!HasKey(key)) - { - return false; - } - if (!GetValueByRef(key, value)) - { - return false; - } - } - else - { - assert(m_backend); - return m_backend->GetModuleSpecificIntEntry(key, value); - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetModuleSpecificBoolEntry(const char* key, bool& value) -{ - value = false; - - if (!m_bGetDataFromBackend) - { - if (!HasKey(key)) - { - return false; - } - if (!GetValueByRef(key, value)) - { - return false; - } - } - else - { - assert(m_backend); - return m_backend->GetModuleSpecificBoolEntry(key, value); - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) -{ - SetKey(key, str); - if (!m_bGetDataFromBackend) - { - return StoreData(); - } - - assert(m_backend); - return m_backend->SetModuleSpecificStringEntryUtf16(key, str); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::SetModuleSpecificIntEntry(const char* key, const int& value) -{ - SetKey(key, value); - if (!m_bGetDataFromBackend) - { - return StoreData(); - } - - assert(m_backend); - return m_backend->SetModuleSpecificIntEntry(key, value); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::SetModuleSpecificBoolEntry(const char* key, const bool& value) -{ - SetKey(key, value); - if (!m_bGetDataFromBackend) - { - return StoreData(); - } - - assert(m_backend); - return m_backend->SetModuleSpecificBoolEntry(key, value); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::SetModuleSpecificStringEntryUtf8(const char* key, const char* str) -{ - wchar_t wbuffer[512]; - SettingsManagerHelpers::ConvertUtf8ToUtf16(str, SettingsManagerHelpers::CWCharBuffer(wbuffer, sizeof(wbuffer))); - - return SetModuleSpecificStringEntryUtf16(key, wbuffer); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::HasKey(const char* key) -{ - return m_keyValueArray.find(key) != 0; -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::SetKey(const char* key, const wchar_t* value) -{ - m_keyValueArray.set(key, value); -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::SetKey(const char* key, bool value) -{ - m_keyValueArray.set(key, (value ? L"true" : L"false")); -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::SetKey(const char* key, int value) -{ - m_keyValueArray.set(key, std::to_wstring(value).c_str()); -} - -bool CEngineSettingsManager::GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) -{ - assert(m_backend); - return m_backend->GetInstalledBuildRootPathUtf16(index, name, path); -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::SetParentDialog(size_t window) -{ - m_hWndParent = window; -} - - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::StoreData() -{ - if (m_bGetDataFromBackend) - { - bool res = StoreEngineSettingsToRegistry(); - - if (!res) - { -#ifdef AZ_PLATFORM_WINDOWS - MessageBoxA(reinterpret_cast(m_hWndParent), "Could not store data to registry.", "Error", MB_OK | MB_ICONERROR); -#endif - } - return res; - } - - // store data to INI file - - FILE* file; -#ifdef AZ_PLATFORM_WINDOWS - _wfopen_s(&file, m_sModuleFileName.c_str(), L"wb"); -#else - char fname[MAX_PATH]; - memset(fname, 0, MAX_PATH); - wcstombs(fname, m_sModuleFileName.c_str(), MAX_PATH); - file = fopen(fname, "wb"); -#endif - if (file == NULL) - { - return false; - } - - char buffer[2048]; - - for (size_t i = 0; i < m_keyValueArray.size(); ++i) - { - const SKeyValue& kv = m_keyValueArray[i]; - - fprintf_s(file, kv.key.c_str()); - fprintf_s(file, " = "); - - if (kv.value.length() > 0) - { - SettingsManagerHelpers::ConvertUtf16ToUtf8(kv.value.c_str(), SettingsManagerHelpers::CCharBuffer(buffer, sizeof(buffer))); - fprintf_s(file, "%s", buffer); - } - - fprintf_s(file, "\r\n"); - } - - fclose(file); - - return true; -} - - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::LoadValuesFromConfigFile(const wchar_t* szFileName) -{ - m_keyValueArray.clear(); - - // read file to memory - - FILE* file; -#ifdef AZ_PLATFORM_WINDOWS - _wfopen_s(&file, szFileName, L"rb"); -#else - char fname[MAX_PATH]; - memset(fname, 0, MAX_PATH); - wcstombs(fname, szFileName, MAX_PATH); - file = fopen(fname, "rb"); -#endif - if (file == NULL) - { - return false; - } - - fseek(file, 0, SEEK_END); - long size = ftell(file); - fseek(file, 0, SEEK_SET); - char* data = new char[size + 1]; - fread_s(data, size, 1, size, file); - fclose(file); - - wchar_t wBuffer[1024]; - - // parse file for root path - - int start = 0, end = 0; - while (end < size) - { - while (end < size && data[end] != '\n') - { - end++; - } - - memcpy(data, &data[start], end - start); - data[end - start] = 0; - start = end = end + 1; - - CFixedString line(data); - size_t equalsOfs; - for (equalsOfs = 0; equalsOfs < line.length(); ++equalsOfs) - { - if (line[equalsOfs] == '=') - { - break; - } - } - if (equalsOfs < line.length()) - { - CFixedString key; - CFixedString value; - - key.appendAscii(line.c_str(), equalsOfs); - key.trim(); - - SettingsManagerHelpers::ConvertUtf8ToUtf16(line.c_str() + equalsOfs + 1, SettingsManagerHelpers::CWCharBuffer(wBuffer, sizeof(wBuffer))); - value.append(wBuffer); - value.trim(); - - m_keyValueArray.set(key.c_str(), value.c_str()); - } - } - delete[] data; - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::StoreEngineSettingsToRegistry() -{ - assert(m_backend); - return m_backend->StoreEngineSettingsToRegistry(); -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::LoadEngineSettingsFromRegistry() -{ - assert(m_backend); - m_backend->LoadEngineSettingsFromRegistry(); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetValueByRef(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) const -{ - if (wbuffer.getSizeInElements() <= 0) - { - return false; - } - - const SKeyValue* p = m_keyValueArray.find(key); - if (!p || (p->value.length() + 1) > wbuffer.getSizeInElements()) - { - wbuffer[0] = 0; - return false; - } - azwcscpy(wbuffer.getPtr(), wbuffer.getSizeInElements(), p->value.c_str()); - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetValueByRef(const char* key, bool& value) const -{ - wchar_t buffer[100]; - if (!GetValueByRef(key, SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - return false; - } - value = (wcscmp(buffer, L"true") == 0); - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetValueByRef(const char* key, int& value) const -{ - wchar_t buffer[100]; - if (!GetValueByRef(key, SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - return false; - } - value = wcstol(buffer, 0, 10); - return true; -} - -#endif //(CRY_ENABLE_RC_HELPER) diff --git a/Code/CryEngine/CryCommon/EngineSettingsManager.h b/Code/CryEngine/CryCommon/EngineSettingsManager.h deleted file mode 100644 index 95216b3bf3..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsManager.h +++ /dev/null @@ -1,89 +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_ENGINESETTINGSMANAGER_H -#define CRYINCLUDE_CRYCOMMON_ENGINESETTINGSMANAGER_H -#pragma once - -#include "ProjectDefines.h" - -#if defined(CRY_ENABLE_RC_HELPER) - -#include "SettingsManagerHelpers.h" - -class CEngineSettingsBackend; - -////////////////////////////////////////////////////////////////////////// -// Manages storage and loading of all information for tools and CryENGINE, by either registry or an INI file. -// Information can be read and set by key-to-value functions. -// Specific information can be set by a dialog application called by this class. -// If the engine root path is not found, a fall-back dialog is opened. -class CEngineSettingsManager -{ -public: - // prepares CEngineSettingsManager to get requested information either from registry or an INI file, - // if existent as a file with name an directory equal to the module, or from registry. - CEngineSettingsManager(const wchar_t* moduleName = NULL, const wchar_t* iniFileName = NULL); - ~CEngineSettingsManager(); - - void RestoreDefaults(); - - // stores/loads user specific information for modules to/from registry or INI file - bool GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer); - bool GetModuleSpecificStringEntryUtf8(const char* key, SettingsManagerHelpers::CCharBuffer buffer); - bool GetModuleSpecificIntEntry(const char* key, int& value); - bool GetModuleSpecificBoolEntry(const char* key, bool& value); - - bool SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str); - bool SetModuleSpecificStringEntryUtf8(const char* key, const char* str); - bool SetModuleSpecificIntEntry(const char* key, const int& value); - bool SetModuleSpecificBoolEntry(const char* key, const bool& value); - - bool GetValueByRef(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) const; - bool GetValueByRef(const char* key, bool& value) const; - bool GetValueByRef(const char* key, int& value) const; - - void SetKey(const char* key, const wchar_t* value); - void SetKey(const char* key, bool value); - void SetKey(const char* key, int value); - - bool StoreData(); - - bool GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path); - - void SetParentDialog(size_t window); - -private: - bool HasKey(const char* key); - - void LoadEngineSettingsFromRegistry(); - bool StoreEngineSettingsToRegistry(); - - // parses a file and stores all flags in a private key-value-map - bool LoadValuesFromConfigFile(const wchar_t* szFileName); - -private: - CEngineSettingsBackend *m_backend; - - SettingsManagerHelpers::CFixedString m_sModuleName; // name to store key-value pairs of modules in (registry) or to identify INI file - SettingsManagerHelpers::CFixedString m_sModuleFileName; // used in case of data being loaded from INI file - bool m_bGetDataFromBackend; - SettingsManagerHelpers::CKeyValueArray<30> m_keyValueArray; - - void* m_hBtnBrowse; - size_t m_hWndParent; -}; - -#endif // CRY_ENABLE_RC_HELPER - -#endif // CRYINCLUDE_CRYCOMMON_ENGINESETTINGSMANAGER_H diff --git a/Code/CryEngine/CryCommon/IFlares.h b/Code/CryEngine/CryCommon/IFlares.h deleted file mode 100644 index d1626a83d9..0000000000 --- a/Code/CryEngine/CryCommon/IFlares.h +++ /dev/null @@ -1,228 +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_IFLARES_H -#define CRYINCLUDE_CRYCOMMON_IFLARES_H -#pragma once - -#include // <> required for Interfuscator -#include // <> required for Interfuscator -#include "smartptr.h" - -struct IShader; -class CCamera; - -class __MFPA -{ -}; -class __MFPB -{ -}; -#define MFP_SIZE_ENFORCE : public __MFPA, public __MFPB - -enum EFlareType -{ - eFT__Base__, - eFT_Root, - eFT_Group, - eFT_Ghost, - eFT_MultiGhosts, - eFT_Glow, - eFT_ChromaticRing, - eFT_IrisShafts, - eFT_CameraOrbs, - eFT_ImageSpaceShafts, - eFT_Streaks, - eFT_Reference, - eFT_Proxy, - eFT_Max -}; - -#define FLARE_LIBS_PATH "libs/flares/" -#define FLARE_EXPORT_FILE "LensFlareList.xml" -#define FLARE_EXPORT_FILE_VERSION "1" - -struct FlareInfo -{ - EFlareType type; - const char* name; -#if defined(FLARES_SUPPORT_EDITING) - const char* imagename; -#endif -}; - -#if defined(FLARES_SUPPORT_EDITING) -# define ADD_FLARE_INFO(type, name, imagename) {type, name, imagename} -#else -# define ADD_FLARE_INFO(type, name, imagename) {type, name} -#endif - -class FlareInfoArray -{ -public: - struct Props - { - const FlareInfo* p; - size_t size; - }; - - static const Props Get() - { - static const FlareInfo flareInfoArray[] = - { - ADD_FLARE_INFO(eFT__Base__, "__Base__", NULL), - ADD_FLARE_INFO(eFT_Root, "Root", NULL), - ADD_FLARE_INFO(eFT_Group, "Group", NULL), - ADD_FLARE_INFO(eFT_Ghost, "Ghost", "EngineAssets/Textures/flares/icons/ghost.dds"), - ADD_FLARE_INFO(eFT_MultiGhosts, "Multi Ghost", "EngineAssets/Textures/flares/icons/multi_ghost.dds"), - ADD_FLARE_INFO(eFT_Glow, "Glow", "EngineAssets/Textures/flares/icons/glow.dds"), - ADD_FLARE_INFO(eFT_ChromaticRing, "ChromaticRing", "EngineAssets/Textures/flares/icons/ring.dds"), - ADD_FLARE_INFO(eFT_IrisShafts, "IrisShafts", "EngineAssets/Textures/flares/icons/iris_shafts.dds"), - ADD_FLARE_INFO(eFT_CameraOrbs, "CameraOrbs", "EngineAssets/Textures/flares/icons/orbs.dds"), - ADD_FLARE_INFO(eFT_ImageSpaceShafts, "Vol Shafts", "EngineAssets/Textures/flares/icons/vol_shafts.dds"), - ADD_FLARE_INFO(eFT_Streaks, "Streaks", "EngineAssets/Textures/flares/icons/iris_shafts.dds") - }; - - Props ret; - ret.p = flareInfoArray; - ret.size = sizeof(flareInfoArray) / sizeof(flareInfoArray[0]); - return ret; - } - -private: - FlareInfoArray(); - ~FlareInfoArray(); -}; - -struct SLensFlareRenderParam -{ - SLensFlareRenderParam() - : pCamera(NULL) - , pShader(NULL) - { - } - ~SLensFlareRenderParam(){} - bool IsValid() const - { - return pCamera && pShader; - } - CCamera* pCamera; - IShader* pShader; -}; - -class ISoftOcclusionQuery -{ -public: - // - virtual ~ISoftOcclusionQuery() {} - - virtual void AddRef() = 0; - virtual void Release() = 0; - // -}; - -class IOpticsElementBase MFP_SIZE_ENFORCE -{ -public: - - IOpticsElementBase() - : m_nRefCount(0) - { - } - void AddRef() - { - CryInterlockedIncrement(&m_nRefCount); - } - void Release() - { - if (CryInterlockedDecrement(&m_nRefCount) <= 0) - { - delete this; - } - } - - // - virtual EFlareType GetType() = 0; - virtual bool IsGroup() const = 0; - virtual string GetName() const = 0; - virtual void SetName(const char* ch_name) = 0; - virtual void Load(IXmlNode* pNode) = 0; - - virtual IOpticsElementBase* GetParent() const = 0; - virtual ~IOpticsElementBase() { - } - - virtual bool IsEnabled() const = 0; - - virtual void AddElement(IOpticsElementBase* pElement) = 0; - virtual void InsertElement(int nPos, IOpticsElementBase* pElement) = 0; - virtual void Remove(int i) = 0; - virtual void RemoveAll() = 0; - virtual int GetElementCount() const = 0; - virtual IOpticsElementBase* GetElementAt(int i) const = 0; - - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - virtual void Invalidate() = 0; - - virtual void Render(SLensFlareRenderParam* pParam, const Vec3& vPos) = 0; - - virtual void SetOpticsReference([[maybe_unused]] IOpticsElementBase* pReference) {} - virtual IOpticsElementBase* GetOpticsReference() const { return NULL; } - // - -#if defined(FLARES_SUPPORT_EDITING) - virtual AZStd::vector GetEditorParamGroups() = 0; -#endif - - ///Basic Setters/////////////////////////////////////////////////////////////// - virtual void SetEnabled(bool enabled) { (void)enabled; } - virtual void SetSize(float size) { (void)size; } - virtual void SetPerspectiveFactor(float perspectiveFactor) { (void)perspectiveFactor; } - virtual void SetDistanceFadingFactor(float distanceFadingFactor) { (void)distanceFadingFactor; } - virtual void SetBrightness(float brightness) { (void)brightness; } - virtual void SetColor(ColorF color) { (void)color; } - virtual void SetMovement(Vec2 movement) { (void)movement; } - virtual void SetTransform(const Matrix33& xform) { (void)xform; } - virtual void SetOccBokehEnabled(bool occBokehEnabled) { (void)occBokehEnabled; } - virtual void SetOrbitAngle(float orbitAngle) { (void)orbitAngle; } - virtual void SetSensorSizeFactor(float sizeFactor) { (void)sizeFactor; } - virtual void SetSensorBrightnessFactor(float brightnessFactor) { (void)brightnessFactor; } - virtual void SetAutoRotation(bool autoRotation) { (void)autoRotation; } - virtual void SetAspectRatioCorrection(bool aspectRatioCorrection) { (void)aspectRatioCorrection; } - //////////////////////////////////////////////////////////////////////////////// - -private: - - volatile int m_nRefCount; -}; - -class IOpticsManager -{ -public: - // - virtual ~IOpticsManager(){} - virtual void Reset() = 0; - virtual IOpticsElementBase* Create(EFlareType type) const = 0; - virtual bool Load(const char* fullFlareName, int& nOutIndex, bool forceReload = false) = 0; - virtual bool Load(XmlNodeRef& rootNode, int& nOutIndex) = 0; - virtual IOpticsElementBase* GetOptics(int nIndex) = 0; - virtual bool AddOptics(IOpticsElementBase* pOptics, const char* name, int& nOutNewIndex, bool allowReplace = false) = 0; - virtual bool Rename(const char* fullFlareName, const char* newFullFlareName) = 0; - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - virtual void Invalidate() = 0; - // -}; - -typedef _smart_ptr IOpticsElementBasePtr; - -#endif // CRYINCLUDE_CRYCOMMON_IFLARES_H diff --git a/Code/CryEngine/CryCommon/IMaterialEffects.h b/Code/CryEngine/CryCommon/IMaterialEffects.h deleted file mode 100644 index 73e03a1d80..0000000000 --- a/Code/CryEngine/CryCommon/IMaterialEffects.h +++ /dev/null @@ -1,504 +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 to the Material Effects System - - -#ifndef CRYINCLUDE_CRYCOMMON_IMATERIALEFFECTS_H -#define CRYINCLUDE_CRYCOMMON_IMATERIALEFFECTS_H -#pragma once - -#if !defined(_RELEASE) - #define MATERIAL_EFFECTS_DEBUG -#endif - - -#include "CryFixedArray.h" - -struct IRenderNode; -struct ISurfaceType; - -////////////////////////////////////////////////////////////////////////// -enum EMFXPlayFlags -{ - eMFXPF_Disable_Delay = BIT(0), - eMFXPF_Audio = BIT(1), - eMFXPF_Decal = BIT(2), - eMFXPF_Particles = BIT(3), - eMFXPF_Deprecated0 = BIT(4), // formerly eMFXPF_Flowgraph - eMFXPF_ForceFeedback = BIT(5), - eMFXPF_All = (eMFXPF_Audio | eMFXPF_Decal | eMFXPF_Particles | eMFXPF_Deprecated0 | eMFXPF_ForceFeedback), -}; - -#define MFX_INVALID_ANGLE (gf_PI2 + 1) - -////////////////////////////////////////////////////////////////////////// -struct SMFXAudioEffectRtpc -{ - SMFXAudioEffectRtpc() - { - rtpcName = ""; - rtpcValue = 0.0f; - } - const char* rtpcName; - float rtpcValue; -}; - -////////////////////////////////////////////////////////////////////////// -struct SMFXRunTimeEffectParams -{ - static const int MAX_AUDIO_RTPCS = 4; - - SMFXRunTimeEffectParams() - : playSoundFP(false) - , playflags(eMFXPF_All) - , fLastTime(0.0f) - , srcSurfaceId(0) - , trgSurfaceId(0) - , srcRenderNode(0) - , trgRenderNode(0) - , partID(0) - , pos(ZERO) - , decalPos(ZERO) - , normal(0.0f, 0.0f, 1.0f) - , angle(MFX_INVALID_ANGLE) - , scale(1.0f) - , audioComponentOffset(ZERO) - , numAudioRtpcs(0) - , fDecalPlacementTestMaxSize(1000.f) - { - dir[0].Set(0.0f, 0.0f, -1.0f); - dir[1].Set(0.0f, 0.0f, 1.0f); - } - - bool AddAudioRtpc(const char* name, float val) - { - if (numAudioRtpcs < MAX_AUDIO_RTPCS) - { - audioRtpcs[numAudioRtpcs].rtpcName = name; - audioRtpcs[numAudioRtpcs].rtpcValue = val; - ++numAudioRtpcs; - return true; - } - return false; - } - - void ResetAudioRtpcs() - { - numAudioRtpcs = 0; - } - -public: - uint16 playSoundFP; // Sets 1p/3p audio switch - uint16 playflags; // See EMFXPlayFlags - float fLastTime; // Last time this effect was played - float fDecalPlacementTestMaxSize; - - int srcSurfaceId; - int trgSurfaceId; - IRenderNode* srcRenderNode; - IRenderNode* trgRenderNode; - int partID; - - Vec3 pos; - Vec3 decalPos; - Vec3 dir[2]; - Vec3 normal; - float angle; - float scale; - - // audio related - Vec3 audioComponentOffset; // in case of audio component, uses this offset - - SMFXAudioEffectRtpc audioRtpcs[MAX_AUDIO_RTPCS]; - uint32 numAudioRtpcs; -}; - -struct SMFXBreakageParams -{ - enum EBreakageRequestFlags - { - eBRF_Matrix = BIT(0), - eBRF_HitPos = BIT(1), - eBRF_HitImpulse = BIT(2), - eBRF_Velocity = BIT(3), - eBRF_ExplosionImpulse = BIT(4), - eBRF_Mass = BIT(5), - eBFR_Entity = BIT(6), - }; - - SMFXBreakageParams() - : m_flags(0) - , m_worldTM(IDENTITY) - , m_vHitPos(ZERO) - , m_vHitImpulse(IDENTITY) - , m_vVelocity(ZERO) - , m_fExplosionImpulse(1.0f) - , m_fMass(0.0f) - { - } - - - // Matrix - void SetMatrix(const Matrix34& worldTM) - { - m_worldTM = worldTM; - SetFlag(eBRF_Matrix); - } - - const Matrix34& GetMatrix() const - { - return m_worldTM; - } - - // HitPos - void SetHitPos(const Vec3& vHitPos) - { - m_vHitPos = vHitPos; - SetFlag(eBRF_HitPos); - } - - const Vec3& GetHitPos() const - { - return m_vHitPos; - } - - // HitImpulse - void SetHitImpulse(const Vec3& vHitImpulse) - { - m_vHitImpulse = vHitImpulse; - SetFlag(eBRF_HitImpulse); - } - - const Vec3& GetHitImpulse() const - { - return m_vHitImpulse; - } - - // Velocity - void SetVelocity(const Vec3& vVelocity) - { - m_vVelocity = vVelocity; - SetFlag(eBRF_Velocity); - } - - const Vec3& GetVelocity() const - { - return m_vVelocity; - } - - // Explosion Impulse - void SetExplosionImpulse(float fExplosionImpulse) - { - m_fExplosionImpulse = fExplosionImpulse; - SetFlag(eBRF_ExplosionImpulse); - } - - float GetExplosionImpulse() const - { - return m_fExplosionImpulse; - } - - // Mass - void SetMass(float fMass) - { - m_fMass = fMass; - SetFlag(eBRF_Mass); - } - - float GetMass() const - { - return m_fMass; - } - - // Checking for flags - bool CheckFlag(EBreakageRequestFlags flag) const - { - return (m_flags & flag) != 0; - } - -protected: - void SetFlag(EBreakageRequestFlags flag) - { - m_flags |= flag; - } - - void ClearFlag(EBreakageRequestFlags flag) - { - m_flags &= ~flag; - } - - uint32 m_flags; - Matrix34 m_worldTM; - Vec3 m_vHitPos; - Vec3 m_vHitImpulse; - Vec3 m_vVelocity; - float m_fExplosionImpulse; - float m_fMass; -}; - -class IMFXParticleParams -{ -public: - IMFXParticleParams() - : name(NULL) - , userdata(NULL) - , scale(1.0f) - { - } - - const char* name; - const char* userdata; - float scale; -}; - -class SMFXParticleListNode -{ -public: - static SMFXParticleListNode* Create(); - void Destroy(); - static void FreePool(); - - IMFXParticleParams m_particleParams; - SMFXParticleListNode* pNext; - -private: - SMFXParticleListNode() - { - pNext = NULL; - } - ~SMFXParticleListNode() {} -}; - -class IMFXAudioParams -{ - const static uint MAX_SWITCH_DATA_ELEMENTS = 4; - -public: - - struct SSwitchData - { - SSwitchData() - : switchName(NULL) - , switchStateName(NULL) - { - } - - const char* switchName; - const char* switchStateName; - }; - - IMFXAudioParams() - : triggerName(NULL) - { - } - const char* triggerName; - - CryFixedArray triggerSwitches; -}; - -class SMFXAudioListNode -{ -public: - static SMFXAudioListNode* Create(); - void Destroy(); - static void FreePool(); - - IMFXAudioParams m_audioParams; - SMFXAudioListNode* pNext; - -private: - SMFXAudioListNode() - : pNext(NULL) - { - } - - ~SMFXAudioListNode() - { - } -}; - -class IMFXDecalParams -{ -public: - IMFXDecalParams() - { - filename = 0; - material = 0; - minscale = 1.f; - maxscale = 1.f; - rotation = -1.f; - lifetime = 10.0f; - assemble = false; - forceedge = false; - } - const char* filename; - const char* material; - float minscale; - float maxscale; - float rotation; - float lifetime; - bool assemble; - bool forceedge; -}; - -class SMFXDecalListNode -{ -public: - static SMFXDecalListNode* Create(); - void Destroy(); - static void FreePool(); - - IMFXDecalParams m_decalParams; - SMFXDecalListNode* pNext; - -private: - SMFXDecalListNode() - { - pNext = 0; - } - ~SMFXDecalListNode() {} -}; - -class IMFXForceFeedbackParams -{ -public: - IMFXForceFeedbackParams() - : forceFeedbackEventName (NULL) - , intensityFallOffMinDistanceSqr(0.0f) - , intensityFallOffMaxDistanceSqr(0.0f) - { - } - - const char* forceFeedbackEventName; - float intensityFallOffMinDistanceSqr; - float intensityFallOffMaxDistanceSqr; -}; - -class SMFXForceFeedbackListNode -{ -public: - static SMFXForceFeedbackListNode* Create(); - void Destroy(); - static void FreePool(); - - IMFXForceFeedbackParams m_forceFeedbackParams; - SMFXForceFeedbackListNode* pNext; - -private: - SMFXForceFeedbackListNode() - : pNext(NULL) - { - } - ~SMFXForceFeedbackListNode() {} -}; - -struct SMFXResourceList; -typedef _smart_ptr SMFXResourceListPtr; - -struct SMFXResourceList -{ -public: - SMFXParticleListNode* m_particleList; - SMFXAudioListNode* m_audioList; - SMFXDecalListNode* m_decalList; - SMFXForceFeedbackListNode* m_forceFeedbackList; - - void AddRef() { ++m_refs; } - void Release() - { - if (--m_refs <= 0) - { - Destroy(); - } - } - - static SMFXResourceListPtr Create(); - static void FreePool(); - -private: - int m_refs; - - virtual void Destroy(); - - SMFXResourceList() - : m_refs(0) - { - m_particleList = 0; - m_audioList = 0; - m_decalList = 0; - m_forceFeedbackList = 0; - } - virtual ~SMFXResourceList() - { - while (m_particleList != 0) - { - SMFXParticleListNode* next = m_particleList->pNext; - m_particleList->Destroy(); - m_particleList = next; - } - while (m_audioList != 0) - { - SMFXAudioListNode* next = m_audioList->pNext; - m_audioList->Destroy(); - m_audioList = next; - } - while (m_decalList != 0) - { - SMFXDecalListNode* next = m_decalList->pNext; - m_decalList->Destroy(); - m_decalList = next; - } - while (m_forceFeedbackList != 0) - { - SMFXForceFeedbackListNode* next = m_forceFeedbackList->pNext; - m_forceFeedbackList->Destroy(); - m_forceFeedbackList = next; - } - } -}; - -typedef uint16 TMFXEffectId; -static const TMFXEffectId InvalidEffectId = 0; - -struct SMFXCustomParamValue -{ - float fValue; -}; - -////////////////////////////////////////////////////////////////////////// -struct IMaterialEffects -{ - // - virtual ~IMaterialEffects(){} - virtual void LoadFXLibraries() = 0; - virtual void Reset(bool bCleanup) = 0; - virtual void ClearDelayedEffects() = 0; - virtual TMFXEffectId GetEffectIdByName(const char* libName, const char* effectName) = 0; - virtual TMFXEffectId GetEffectId(int surfaceIndex1, int surfaceIndex2) = 0; - virtual TMFXEffectId GetEffectId(const char* customName, int surfaceIndex2) = 0; - virtual SMFXResourceListPtr GetResources(TMFXEffectId effectId) const = 0; - virtual void PreLoadAssets() = 0; - virtual bool ExecuteEffect(TMFXEffectId effectId, SMFXRunTimeEffectParams& runtimeParams) = 0; - virtual int GetDefaultSurfaceIndex() = 0; - virtual int GetDefaultCanopyIndex() = 0; - - virtual bool PlayBreakageEffect(ISurfaceType* pSurfaceType, const char* breakageType, const SMFXBreakageParams& mfxBreakageParams) = 0; - - virtual void SetCustomParameter(TMFXEffectId effectId, const char* customParameter, const SMFXCustomParamValue& customParameterValue) = 0; - - virtual void CompleteInit() = 0; - // -}; - -#endif // CRYINCLUDE_CRYCOMMON_IMATERIALEFFECTS_H diff --git a/Code/CryEngine/CryCommon/INotificationNetwork.h b/Code/CryEngine/CryCommon/INotificationNetwork.h deleted file mode 100644 index 9ad44b24ab..0000000000 --- a/Code/CryEngine/CryCommon/INotificationNetwork.h +++ /dev/null @@ -1,147 +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_INOTIFICATIONNETWORK_H -#define CRYINCLUDE_CRYCOMMON_INOTIFICATIONNETWORK_H -#pragma once - - -// Constants - -#define NN_CHANNEL_NAME_LENGTH_MAX 16 - -struct INotificationNetworkClient; - -// User Interfaces - -struct INotificationNetworkListener -{ - // - virtual ~INotificationNetworkListener(){} - // Called upon receiving data from the Channel the Listener is binded to. - virtual void OnNotificationNetworkReceive(const void* pBuffer, size_t length) = 0; - // -}; - -struct INotificationNetworkConnectionCallback -{ - // - virtual ~INotificationNetworkConnectionCallback(){} - virtual void OnConnect(INotificationNetworkClient* pClient, bool bSucceeded) = 0; - virtual void OnDisconnected(INotificationNetworkClient* pClient) = 0; - // -}; - -// Interfaces - -struct INotificationNetworkClient -{ - // - virtual ~INotificationNetworkClient(){} - virtual void Release() = 0; - - // Binds a Listener to the given Notification Channel. - // Each Listener can be binded only to one Channel, calling the method - // again with an already added Listener and a different Channel will rebind it. - // The Channel name cannot exceed NN_CHANNEL_NAME_LENGTH_MAX chars. - virtual bool ListenerBind(const char* channelName, INotificationNetworkListener* pListener) = 0; - - // If it exist, removes the given Listener form the Notification Network. - virtual bool ListenerRemove(INotificationNetworkListener* pListener) = 0; - - // Sends arbitrary data to the Notification Network the Client is connected to. - virtual bool Send(const char* channelName, const void* pBuffer, size_t length) = 0; - - // Checks if the current client is connected. - // Returns true if it is connected, false otherwise. - virtual bool IsConnected() = 0; - - // Checks if the connection attempt failed. - // Returns true if it failed to connect by any reason (such as timeout). - virtual bool IsFailedToConnect() const = 0; - - // Start the connection request for this particular client. - // Parameters: - // address - Is the host name or ipv4 (for now) address string to which - // we want to connect. - // port - Is the TCP port to which we want to connect. - // Remarks: Port 9432 is being used by the live preview already. - virtual bool Connect(const char* address, uint16 port) = 0; - - // Tries to register a callback listener object. - // A callback listener object will receive events from the client element, - // such as connection result information. - // Parameters: - // - pConnectionCallback - Is a pointer to an object implementing interface - // INotificationNetworkConnectionCallback which will be called when - // the events happen, such as connection, disconnection and failed attempt - // to connect. - // Return Value: - // - It will return true if registered the callback object successfully. - // - It will return false when there the callback object is already - // registered. - virtual bool RegisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback) = 0; - - // Tries to unregister a callback listener object. - // A callback listener object will receive events from the client element, - // such as connection result information. - // Parameters: - // - pConnectionCallback - Is a pointer to an object implementing interface - // INotificationNetworkConnectionCallback which will be called when - // the events happen, such as connection, disconnection and failed attempt - // to connect and that we want to unregister. - // Return Value: - // - It will return true if unregistered the callback object successfully. - // - It will return false when no object matching the one requested is found - // int the object. - virtual bool UnregisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback) = 0; - // -}; - -struct INotificationNetwork -{ - // - virtual ~INotificationNetwork(){} - - virtual void Release() = 0; - - // Creates a disconnected client. - virtual INotificationNetworkClient* CreateClient() = 0; - - // Attempts to connect to the Notification Network at the given address, - // returns a Client interface if communication is possible. - virtual INotificationNetworkClient* Connect(const char* address, uint16 port) = 0; - - // Returns the Connection count of the given Channel. If NULL is passed - // instead of a valid Channel name the total count of all Connections is - // returned. - virtual size_t GetConnectionCount(const char* channelName = NULL) = 0; - - // Has to be called from the main thread to process received notifications. - virtual void Update() = 0; - - // Binds a Listener to the given Notification Channel. - // Each Listener can be binded only to one Channel, calling the method - // again with an already added Listener and a different Channel will rebind it. - // The Channel name cannot exceed NN_CHANNEL_NAME_LENGTH_MAX chars. - virtual bool ListenerBind(const char* channelName, INotificationNetworkListener* pListener) = 0; - - // If it exist, removes the given Listener form the Notification Network. - virtual bool ListenerRemove(INotificationNetworkListener* pListener) = 0; - - // Sends arbitrary data to all the Connections listening to the given Channel. - virtual uint32 Send(const char* channel, const void* pBuffer, size_t length) = 0; - // -}; - -#endif // CRYINCLUDE_CRYCOMMON_INOTIFICATIONNETWORK_H diff --git a/Code/CryEngine/CryCommon/IRenderer.h b/Code/CryEngine/CryCommon/IRenderer.h index 94f8772e71..bb8f8fa572 100644 --- a/Code/CryEngine/CryCommon/IRenderer.h +++ b/Code/CryEngine/CryCommon/IRenderer.h @@ -16,12 +16,12 @@ #include "Cry_Geo.h" #include "Cry_Camera.h" #include "ITexture.h" -#include // <> required for Interfuscator +#include // <> required for Interfuscator +#include // <> required for Interfuscator +#include "smartptr.h" #include #include -#include "IResourceCompilerHelper.h" // for IResourceCompilerHelper::ERcCallResult - // forward declarations struct SRenderingPassInfo; struct SRTStack; @@ -95,7 +95,6 @@ struct IFFont; struct IFFont_RenderProxy; struct STextDrawContext; struct IRenderMesh; -class IOpticsManager; struct ShadowFrustumMGPUCache; struct IAsyncTextureCompileListener; struct IClipVolume; @@ -955,25 +954,6 @@ protected: virtual ~ITextureStreamListener() {} }; -#if defined(CRY_ENABLE_RC_HELPER) -//////////////////////////////////////////////////////////////////////////// -// Listener for asynchronous texture compilation. -// Connects the listener to the task-queue of pending compilation requests. -enum ERcExitCode; -struct IAsyncTextureCompileListener -{ -public: - virtual void OnCompilationStarted(const char* source, const char* target, int nPending) = 0; - virtual void OnCompilationFinished(const char* source, const char* target, IResourceCompilerHelper::ERcCallResult nReturnCode) = 0; - - virtual void OnCompilationQueueTriggered(int nPending) = 0; - virtual void OnCompilationQueueDepleted() = 0; - -protected: - virtual ~IAsyncTextureCompileListener() {} -}; -#endif - enum eDolbyVisionMode { eDVM_Disabled, @@ -1869,8 +1849,6 @@ struct IRenderer virtual SDepthTexture* CreateDepthSurface(int nWidth, int nHeight, bool shaderResourceView = false) = 0; virtual void DestroyDepthSurface(SDepthTexture* pDepthSurf) = 0; - virtual IOpticsElementBase* CreateOptics(EFlareType type) const = 0; - // Note: // Used for pausing timer related stuff. // Example: diff --git a/Code/CryEngine/CryCommon/IResourceCompilerHelper.cpp b/Code/CryEngine/CryCommon/IResourceCompilerHelper.cpp deleted file mode 100644 index 380c94e4c7..0000000000 --- a/Code/CryEngine/CryCommon/IResourceCompilerHelper.cpp +++ /dev/null @@ -1,378 +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 "IResourceCompilerHelper.h" - -#include -// DO NOT USE AZSTD. - -#include // std string used here. -#include -#include - -// the following block is for _mkdir on windows and mkdir on other platforms. -#if defined(_WIN32) -# include -#else -# include -# include -#endif - -namespace RCPathUtil -{ - const char* GetExt(const char* filepath) - { - const char* str = filepath; - size_t len = strlen(filepath); - for (const char* p = str + len - 1; p >= str; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - // we've reached a path separator - it means there's no extension in this name - return ""; - case '.': - // there's an extension in this file name - return p + 1; - } - } - return ""; - } - - const char* GetFile(const char* filepath) - { - const size_t len = strlen(filepath); - for (const char* p = filepath + len - 1; p >= filepath; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - return p + 1; - } - } - return filepath; - } - - - //! Replace extension for given file. - std::string RemoveExtension(const char* filepath) - { - std::string filepathstr = filepath; - const char* str = filepathstr.c_str(); - for (const char* p = str + filepathstr.length() - 1; p >= str; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - // we've reached a path separator - it means there's no extension in this name - return filepathstr; - case '.': - // there's an extension in this file name - filepathstr.erase(p - str); - return filepathstr; - } - } - // it seems the file name is a pure name, without path or extension - return filepathstr; - } - - std::string ReplaceExtension(const char* filepath, const char* ext) - { - std::string str = filepath; - if (ext != 0) - { - str = RemoveExtension(str.c_str()); - if (ext[0] != 0 && ext[0] != '.') - { - str += "."; - } - str += ext; - } - return str; - } - - std::string GetPath(const char* filepath) - { - std::string filepathstr = filepath; - const char* str = filepathstr.c_str(); - for (const char* p = str + filepathstr.length() - 1; p >= str; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - // we've reached a path separator - it means there's no extension in this name - return filepathstr.substr(0, p - str); - } - } - // it seems the file name is a pure name, without path - return ""; - } - - - ////////////////////////////////////////////////////////////////////////// - bool IsRelativePath(const char* p) - { - if (!p || !p[0]) - { - return true; - } - return p[0] != '/' && p[0] != '\\' && !strchr(p, ':'); - } -} - -const char* IResourceCompilerHelper::SourceImageFormatExts[NUM_SOURCE_IMAGE_TYPE] = { "tif", "bmp", "gif", "jpg", "jpeg", "jpe", "tga", "png" }; -const char* IResourceCompilerHelper::SourceImageFormatExtsWithDot[NUM_SOURCE_IMAGE_TYPE] = { ".tif", ".bmp", ".gif", ".jpg", ".jpeg", ".jpe", ".tga", ".png" }; -const char* IResourceCompilerHelper::EngineImageFormatExts[NUM_ENGINE_IMAGE_TYPE] = { "dds" }; -const char* IResourceCompilerHelper::EngineImageFormatExtsWithDot[NUM_ENGINE_IMAGE_TYPE] = { ".dds" }; - - -IResourceCompilerHelper::ERcCallResult IResourceCompilerHelper::ConvertResourceCompilerExitCodeToResultCode(int exitCode) -{ - switch (exitCode) - { - case eRcExitCode_Success: - case eRcExitCode_UserFixing: - return eRcCallResult_success; - - case eRcExitCode_Error: - return eRcCallResult_error; - - case eRcExitCode_FatalError: - return eRcCallResult_error; - case eRcExitCode_Crash: - return eRcCallResult_crash; - } - return eRcCallResult_error; -} - - -////////////////////////////////////////////////////////////////////////// -const char* IResourceCompilerHelper::GetCallResultDescription(IResourceCompilerHelper::ERcCallResult result) -{ - switch (result) - { - case eRcCallResult_success: - return "Success."; - case eRcCallResult_notFound: - return "ResourceCompiler executable was not found."; - case eRcCallResult_error: - return "ResourceCompiler exited with an error."; - case eRcCallResult_crash: - return "ResourceCompiler crashed! Please report this. Include source asset and this log in the report."; - default: - return "Unexpected failure in ResultCompilerHelper."; - } -} - -// Arguments: -// szFilePath - could be source or destination filename -void IResourceCompilerHelper::GetOutputFilename(const char* szFilePath, char* buffer, size_t bufferSizeInBytes) -{ - if (IResourceCompilerHelper::IsSourceImageFormatSupported(szFilePath)) - { - std::string newString = RCPathUtil::ReplaceExtension(szFilePath, "dds"); - azstrncpy(buffer, bufferSizeInBytes, newString.c_str(), bufferSizeInBytes - 1); - return; - } - - azstrncpy(buffer, bufferSizeInBytes, szFilePath, bufferSizeInBytes - 1); -} - -IResourceCompilerHelper::ERcCallResult IResourceCompilerHelper::InvokeResourceCompiler(const char* szSrcFilePath, const char* szDstFilePath, const bool bUserDialog) -{ - - const char* szDstFileName = RCPathUtil::GetFile(szDstFilePath); - std::string pathOnly = RCPathUtil::GetPath(szDstFilePath); - const int maxStringSize = 512; - char szRemoteCmdLine[maxStringSize] = { 0 }; - char szFullPathToSourceFile[maxStringSize] = { 0 }; - - if (RCPathUtil::IsRelativePath(szSrcFilePath)) - { - azstrcat(szFullPathToSourceFile, maxStringSize, "#ENGINEROOT#"); - azstrcat(szFullPathToSourceFile, maxStringSize, "\\"); - } - azstrcat(szFullPathToSourceFile, maxStringSize, szSrcFilePath); - - azstrcat(szRemoteCmdLine, maxStringSize, " /targetroot=\""); - azstrcat(szRemoteCmdLine, maxStringSize, pathOnly.c_str()); - azstrcat(szRemoteCmdLine, maxStringSize, "\""); - - azstrcat(szRemoteCmdLine, maxStringSize, " /overwritefilename=\""); - azstrcat(szRemoteCmdLine, maxStringSize, szDstFileName); - azstrcat(szRemoteCmdLine, maxStringSize, "\""); - - return CallResourceCompiler(szFullPathToSourceFile, szRemoteCmdLine, nullptr, true, false, !bUserDialog); -} - -unsigned int IResourceCompilerHelper::GetNumSourceImageFormats() -{ - return NUM_SOURCE_IMAGE_TYPE; -} - -const char* IResourceCompilerHelper::GetSourceImageFormat(unsigned int index, bool bWithDot) -{ - if (index >= GetNumSourceImageFormats()) - { - return nullptr; - } - - if (bWithDot) - { - return SourceImageFormatExtsWithDot[index]; - } - else - { - return SourceImageFormatExts[index]; - } -} - -unsigned int IResourceCompilerHelper::GetNumEngineImageFormats() -{ - return NUM_ENGINE_IMAGE_TYPE; -} - -const char* IResourceCompilerHelper::GetEngineImageFormat(unsigned int index, bool bWithDot) -{ - if (index >= GetNumEngineImageFormats()) - { - return nullptr; - } - - if (bWithDot) - { - return EngineImageFormatExtsWithDot[index]; - } - else - { - return EngineImageFormatExts[index]; - } -} - -bool IResourceCompilerHelper::IsSourceImageFormatSupported(const char* szFileNameOrExtension) -{ - if (!szFileNameOrExtension) // if this hits, might want to check the call site - { - return false; - } - - //check the string length - size_t len = strlen(szFileNameOrExtension); - if (len < 3)//no point in going on if the smallest valid ext is 3 characters - { - return false; - } - - //find the ext by starting at the last character and moving backward to first he first '.' - const char* szExtension = nullptr; - size_t cur = len - 1; - while (cur && !szExtension) - { - if (szFileNameOrExtension[cur] == '.') - { - szExtension = &szFileNameOrExtension[cur]; - } - cur--; - } - if (len - cur < 3)//no point in going on if the smallest valid ext is 3 characters - { - return false; - } - - //if we didn't find a '.' it could still be valid, they may not have - //passed it in. i.e. "dds" instead of ".dds" which is still valid - if (!szExtension) - { - //with no '.' the largest ext is currently 4 characters - //no point in going on if it is larger - if (len > 4) - { - return false; - } - - szExtension = szFileNameOrExtension; - } - - //loop over all the valid exts and see if it is one of them - for (unsigned int i = 0; i < GetNumSourceImageFormats(); ++i) - { - if (!azstricmp(szExtension, GetSourceImageFormat(i, szExtension[0] == '.'))) - { - return true; - } - } - - return false; -} - -bool IResourceCompilerHelper::IsGameImageFormatSupported(const char* szFileNameOrExtension) -{ - if (!szFileNameOrExtension) // if this hits, might want to check the call site - { - return false; - } - - //check the string length - size_t len = strlen(szFileNameOrExtension); - if (len < 3)//no point in going on if the smallest valid ext is 3 characters - { - return false; - } - - //find the ext by starting at the last character and moving backward to first he first '.' - const char* szExtension = nullptr; - size_t cur = len - 1; - while (cur && !szExtension) - { - if (szFileNameOrExtension[cur] == '.') - { - szExtension = &szFileNameOrExtension[cur]; - } - cur--; - } - if (len - cur < 3)//no point in going on if the smallest valid ext is 3 characters - { - return false; - } - - //if we didn't find a '.' it could still be valid, they may not have - //passed it in. i.e. "dds" instead of ".dds" which is still valid - if (!szExtension) - { - //with no '.' the largest ext is currently 4 characters - //no point in going on if it is larger - if (len > 4) - { - return false; - } - - szExtension = szFileNameOrExtension; - } - - //loop over all the valid exts and see if it is one of them - for (unsigned int i = 0; i < GetNumEngineImageFormats(); ++i) - { - if (!azstricmp(szExtension, GetEngineImageFormat(i, szExtension[0] == '.'))) - { - return true; - } - } - - return false; -} diff --git a/Code/CryEngine/CryCommon/IResourceCompilerHelper.h b/Code/CryEngine/CryCommon/IResourceCompilerHelper.h deleted file mode 100644 index 52f05b0c84..0000000000 --- a/Code/CryEngine/CryCommon/IResourceCompilerHelper.h +++ /dev/null @@ -1,167 +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_CRYCOMMON_IRESOURCECOMPILERHELPER_H -#define CRYINCLUDE_CRYCOMMON_IRESOURCECOMPILERHELPER_H - -#pragma once - -// DO NOT USE AZSTD - -#include - -// IResourceCompilerHelper exists to define an interface that allows -// remote or local compilation of resources through the "resource Compiler" executable -// in most tools it will be implemented as a local execution. However, in the engine -// it will be substituted for a remote RC invocation through the Asset Processor if -// that system is enabled (via con var and define) - -// DO NOT USE CRYSTRING or CRY ALLOCATORS HERE. This is used in maya plugins, that kind of thing. -// the following path utils are special versions of these functions which take pains -// to not use crystring. -// the functions in this interface must be cross platform. -namespace RCPathUtil -{ - // given a full path, return the extension (it will be a pointer into the existing string) - const char* GetExt(const char* filepath); - - // given a full path, return the file only (it will be a pointer into the existing string) - const char* GetFile(const char* filepath); - - // given a filepath, get only the path. - std::string GetPath(const char* filepath); - std::string ReplaceExtension(const char* filepath, const char* ext); - bool IsRelativePath(const char* p); -} - -class IResourceCompilerListener; - -enum ERcExitCode -{ - eRcExitCode_Success = 0, // must be 0 - eRcExitCode_Error = 1, - eRcExitCode_FatalError = 100, - eRcExitCode_Crash = 101, - eRcExitCode_UserFixing = 200, - eRcExitCode_Pending = 666, -}; - -/// A pure virtual interface to the RC Helper system -/// the RC helper system allows you to make requests to a remote process in order to process -/// an asset for you. -class IResourceCompilerHelper -{ -public: - virtual ~IResourceCompilerHelper() {} - - // defines the result of a call via this API to the RC system - enum ERcCallResult - { - eRcCallResult_success, // everything is OK - eRcCallResult_notFound, // the RC executable is not found - eRcCallResult_error, // the RC executable returned an error - eRcCallResult_crash, // the RC executable did not finish - }; - - // - // Arguments: - // szFileName null terminated ABSOLUTE file path or 0 can be used to test for rc.exe existence - // relative path needs to be relative to rc_plugins directory - // szAdditionalSettings - 0 or e.g. "/refresh" or "/refresh /xyz=56" - // - // this is a SYNCHRONOUS, BLOCKING call and will return once the process is complete - virtual ERcCallResult CallResourceCompiler( - const char* szFileName = 0, - const char* szAdditionalSettings = 0, - IResourceCompilerListener* listener = 0, - bool bMayShowWindow = true, - bool bSilent = false, - bool bNoUserDialog = false, - const wchar_t* szWorkingDirectory = 0, - const wchar_t* szRootPath = 0) = 0; - - // InvokeResourceCompiler - a utility that calls the above CallResourceCompiler function - // but generates appropriate settings so you don't have to specify each option. - // This is a BLOCKING call - // the srcFile can be relative to the project root or an absolute path - // the dstFilePath MUST be relative to the same folder as the Src File path - // this will output dstFilePath in the same folder as srcFile. - virtual ERcCallResult InvokeResourceCompiler(const char* szSrcFilePath, const char* szDstFilePath, const bool bUserDialog); - - // --------------------- utility functions --------------------------------- - - // given a RC.EXE process exit code like 101, convert it to the above ERcCallResult - ERcCallResult ConvertResourceCompilerExitCodeToResultCode(int exitCode); - - // given a ERcCallResult, convert it to a simple english string for debugging. - static const char* GetCallResultDescription(ERcCallResult result); - - // given a filename such as "blah.tif" convert it to the appropriate output name "blah.dds" for example - static void GetOutputFilename(const char* szFilePath, char* buffer, size_t bufferSizeInBytes); - - ////////////////////////////////////////////////////////////////////////// - - enum SourceImageTypes - { - SOURCE_IMAGE_TYPE_TIF, - SOURCE_IMAGE_TYPE_BMP, - SOURCE_IMAGE_TYPE_GIF, - SOURCE_IMAGE_TYPE_JPG, - SOURCE_IMAGE_TYPE_JPEG, - SOURCE_IMAGE_TYPE_JPE, - SOURCE_IMAGE_TYPE_TGA, - SOURCE_IMAGE_TYPE_PNG, - NUM_SOURCE_IMAGE_TYPE - }; - - enum EngineImageTypes - { - ENGINE_IMAGE_TYPE_DDS, - NUM_ENGINE_IMAGE_TYPE - }; - -private: - static const char* SourceImageFormatExts[NUM_SOURCE_IMAGE_TYPE]; - static const char* SourceImageFormatExtsWithDot[NUM_SOURCE_IMAGE_TYPE]; - static const char* EngineImageFormatExts[NUM_ENGINE_IMAGE_TYPE]; - static const char* EngineImageFormatExtsWithDot[NUM_ENGINE_IMAGE_TYPE]; - -public: - static unsigned int GetNumSourceImageFormats(); - static const char* GetSourceImageFormat(unsigned int index, bool bWithDot); - - static unsigned int GetNumEngineImageFormats(); - static const char* GetEngineImageFormat(unsigned int index, bool bWithDot); - - static bool IsSourceImageFormatSupported(const char* szExtension); - static bool IsGameImageFormatSupported(const char* szExtension); -}; - -//////////////////////////////////////////////////////////////////////////// -// Listener for synchronous resource-compilation. -// Connects the listener to the output of the RC process. -class IResourceCompilerListener -{ -public: - // FbxImportDialog relies on this enum being in the order from most verbose to least verbose - enum MessageSeverity - { - MessageSeverity_Debug = 0, - MessageSeverity_Info, - MessageSeverity_Warning, - MessageSeverity_Error - }; - - virtual void OnRCMessage(MessageSeverity /*severity*/, const char* /*text*/) {} - virtual ~IResourceCompilerListener() {} -}; - -#endif // CRYINCLUDE_CRYCOMMON_IRESOURCECOMPILERHELPER_H diff --git a/Code/CryEngine/CryCommon/IShader.h b/Code/CryEngine/CryCommon/IShader.h index a87144a8c2..5f5209992e 100644 --- a/Code/CryEngine/CryCommon/IShader.h +++ b/Code/CryEngine/CryCommon/IShader.h @@ -24,7 +24,9 @@ #endif #include "smartptr.h" -#include // <> required for Interfuscator +#include // <> required for Interfuscator +#include // <> required for Interfuscator +#include "smartptr.h" #include "VertexFormats.h" #include #include @@ -2828,7 +2830,6 @@ struct SRenderLight m_ObjMatrix.SetIdentity(); m_BaseObjMatrix.SetIdentity(); m_sName = ""; - m_pSoftOccQuery = NULL; m_pLightAnim = NULL; m_fAreaWidth = 1; m_fAreaHeight = 1; @@ -2884,11 +2885,6 @@ struct SRenderLight return m_pLightImage ? m_pLightImage : NULL; } - IOpticsElementBase* GetLensOpticsElement() const - { - return m_pLensOpticsElement; - } - void SetOpticsParams(const SOpticsInstanceParameters& params) { m_opticsParams = params; @@ -2899,24 +2895,6 @@ struct SRenderLight return m_opticsParams; } - void SetLensOpticsElement(IOpticsElementBase* pOptics) - { - if (m_pLensOpticsElement == pOptics) - { - return; - } - if (pOptics && pOptics->GetType() != eFT_Root) - { - return; - } - SAFE_RELEASE(m_pLensOpticsElement); - m_pLensOpticsElement = pOptics; - if (m_pLensOpticsElement) - { - m_pLensOpticsElement->AddRef(); - } - } - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const { /*LATER*/} void AcquireResources() @@ -2937,14 +2915,6 @@ struct SRenderLight { m_pSpecularCubemap->AddRef(); } - if (m_pLensOpticsElement) - { - m_pLensOpticsElement->AddRef(); - } - if (m_pSoftOccQuery) - { - m_pSoftOccQuery->AddRef(); - } if (m_pLightAnim) { m_pLightAnim->AddRef(); @@ -2961,8 +2931,6 @@ struct SRenderLight SAFE_RELEASE(m_pLightImage); SAFE_RELEASE(m_pDiffuseCubemap); SAFE_RELEASE(m_pSpecularCubemap); - SAFE_RELEASE(m_pLensOpticsElement); - SAFE_RELEASE(m_pSoftOccQuery); SAFE_RELEASE(m_pLightAnim); SAFE_RELEASE(m_pLightAttenMap); } @@ -3046,8 +3014,6 @@ struct SRenderLight const char* m_sName; // Optional name of the light source. SShaderItem m_Shader; // Shader item CRenderObject* m_pObject[MAX_RECURSION_LEVELS]; // Object for light coronas and light flares. - IOpticsElementBase* m_pLensOpticsElement; // Optics element for this shader instance - ISoftOcclusionQuery* m_pSoftOccQuery; ILightAnimWrapper* m_pLightAnim; Matrix34 m_BaseObjMatrix; @@ -3146,9 +3112,7 @@ public: m_fShadowSlopeBias = dl.m_fShadowSlopeBias; m_fShadowResolutionScale = dl.m_fShadowResolutionScale; m_fHDRDynamic = dl.m_fHDRDynamic; - m_pLensOpticsElement = dl.m_pLensOpticsElement; m_LensOpticsFrustumAngle = dl.m_LensOpticsFrustumAngle; - m_pSoftOccQuery = dl.m_pSoftOccQuery; m_fLightFrustumAngle = dl.m_fLightFrustumAngle; m_fProjectorNearPlane = dl.m_fProjectorNearPlane; m_Flags = dl.m_Flags; diff --git a/Code/CryEngine/CryCommon/ISoftCodeMgr.h b/Code/CryEngine/CryCommon/ISoftCodeMgr.h deleted file mode 100644 index b3cef7e1f0..0000000000 --- a/Code/CryEngine/CryCommon/ISoftCodeMgr.h +++ /dev/null @@ -1,276 +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 to manage SoftCode module loading and patching - - -#ifndef CRYINCLUDE_CRYCOMMON_ISOFTCODEMGR_H -#define CRYINCLUDE_CRYCOMMON_ISOFTCODEMGR_H -#pragma once - - -// Provides the generic interface for exchanging member values between SoftCode modules, -struct IExchangeValue -{ - // - virtual ~IExchangeValue() {} - - // Allocates a new IExchangeValue with the underlying type - virtual IExchangeValue* Clone() const = 0; - // Returns the size of the underlying type (to check compatibility) - virtual size_t GetSizeOf() const = 0; - // -}; - -template -struct ExchangeValue - : public IExchangeValue -{ - ExchangeValue(T& value) - : m_value(value) - {} - - virtual IExchangeValue* Clone() const { return new ExchangeValue(*this); } - virtual size_t GetSizeOf() const { return sizeof(m_value); } - - T m_value; -}; - -template -struct ExchangeArray - : public IExchangeValue -{ - ExchangeArray(T* pArr) - { - for (size_t i = 0; i < S; ++i) - { - m_array[i] = pArr[i]; - } - } - - virtual IExchangeValue* Clone() const { return new ExchangeArray(*this); } - virtual size_t GetSizeOf() const { return sizeof(m_array); } - - T m_array[S]; -}; - -/* - This is a non-intrusive support function for types where default construction does no initialization. - SoftCoding relies on default construction to initialize object state correctly. - For most types this works as expected but for some types (typically things like vectors or matrices) - default initialization would be too costly and is therefore not implemented. - This function allows a specialized implementation to be used for such types that will perform - initialization on the newly constructed instance. For example: - - inline void DefaultInitialize(Matrix34& matrix) - { - matrix.SetIdentity(); - } -*/ -template -void DefaultInitialize(T& t) -{ - t = T(); -} - -// Vector support -template -struct Vec2_tpl; -template -struct Vec3_tpl; -template -void DefaultInitialize(Vec2_tpl& vec) { vec.zero(); } -template -void DefaultInitialize(Vec3_tpl& vec) { vec.zero(); } - -// Matrix support -template -struct Matrix33_tpl; -template -struct Matrix34_tpl; -template -struct Matrix44_tpl; - -template -void DefaultInitialize(Matrix33_tpl& matrix) { matrix.SetIdentity(); } -template -void DefaultInitialize(Matrix34_tpl& matrix) { matrix.SetIdentity(); } -template -void DefaultInitialize(Matrix44_tpl& matrix) { matrix.SetIdentity(); } - -// Quat support -template -struct Quat_tpl; -template -void DefaultInitialize(Quat_tpl& quat) { quat.SetIdentity(); } - -// Interface for performing an exchange of instance data -struct IExchanger -{ - // - virtual ~IExchanger() {} - - // True if data is being read from instance members - virtual bool IsLoading() const = 0; - - virtual size_t InstanceCount() const = 0; - - virtual bool BeginInstance(void* pInstance) = 0; - virtual bool SetValue(const char* name, IExchangeValue& value) = 0; - virtual IExchangeValue* GetValue(const char* name, void* pTarget, size_t targetSize) = 0; - // - - template - void Visit(const char* name, T& instance); - - template - void Visit(const char* name, T (&arr)[S]); -}; - -template -void IExchanger::Visit(const char* name, T& value) -{ - if (IsLoading()) - { - IExchangeValue* pValue = GetValue(name, &value, sizeof(value)); - if (pValue) - { - ExchangeValue* pTypedValue = static_cast*>(pValue); - value = pTypedValue->m_value; - } - } - else // Saving - { - // If this member is stored - if (SetValue(name, ExchangeValue(value))) - { - // Set the original value to the default state (to allow safe destruction) - DefaultInitialize(value); - } - } -} - -template -void IExchanger::Visit(const char* name, T (&arr)[S]) -{ - if (IsLoading()) - { - IExchangeValue* pValue = GetValue(name, &arr, sizeof(arr)); - if (pValue) - { - ExchangeArray* pTypedArray = static_cast*>(pValue); - // TODO: Accommodate array resizing? Complex however... - for (size_t i = 0; i < S; ++i) - { - arr[i] = pTypedArray->m_array[i]; - } - } - } - else // Saving - { - // If this member is stored - if (SetValue(name, ExchangeArray(arr))) - { - T defaultValue; - DefaultInitialize(defaultValue); - - // Set the original value to the default value (to allow safe destruction) - for (size_t i = 0; i < S; ++i) - { - arr[i] = defaultValue; - } - } - } -} - -struct InstanceTracker; - -struct ITypeRegistrar -{ - // - virtual ~ITypeRegistrar() {} - - virtual const char* GetName() const = 0; - - // Creates an instance of the type - virtual void* CreateInstance() = 0; - // - -#ifdef SOFTCODE_ENABLED - // How many active instances exist of this type? - virtual size_t InstanceCount() const = 0; - // Used to remove a tracked instance from the Registrar - virtual void RemoveInstance(InstanceTracker* pTracker) = 0; - // Exchanges the instance state with the given exchanger data set - virtual bool ExchangeInstances(IExchanger& exchanger) = 0; - // Destroys all tracked instances of this type - virtual bool DestroyInstances() = 0; - // Returns true if pInstance is of this type (linear search) - virtual bool HasInstance(void* pInstance) const = 0; -#endif -}; - -struct ITypeLibrary -{ - // - virtual ~ITypeLibrary() {} - - virtual const char* GetName() = 0; - virtual void* CreateInstanceVoid(const char* typeName) = 0; - // - -#ifdef SOFTCODE_ENABLED - virtual void SetOverride(ITypeLibrary* pOverrideLib) = 0; - - // Fills in the supplied type list if large enough, and sets count to number of types - virtual size_t GetTypes(ITypeRegistrar** ppRegistrar, size_t& count) const = 0; -#endif -}; - -struct ISoftCodeListener -{ - // - virtual ~ISoftCodeListener() {} - - // Called when an instance is replaced to allow managing systems to fixup pointers - virtual void InstanceReplaced(void* pOldInstance, void* pNewInstance) = 0; - // -}; - -/// Interface for ... -struct ISoftCodeMgr -{ - // - virtual ~ISoftCodeMgr() {} - - // Used to register built-in libraries on first use - virtual void RegisterLibrary(ITypeLibrary* pLib) = 0; - - // Loads any new SoftCode modules - virtual void LoadNewModules() = 0; - - virtual void AddListener(const char* libraryName, ISoftCodeListener* pListener, const char* listenerName) = 0; - virtual void RemoveListener(const char* libraryName, ISoftCodeListener* pListener) = 0; - - // To be called regularly to poll for library updates - virtual void PollForNewModules() = 0; - - // Stops thread execution until a new SoftCode instance is available - virtual void* WaitForUpdate(void* pInstance) = 0; - - /// Frees this instance from memory - //virtual void Release() = 0; - // -}; - -#endif // CRYINCLUDE_CRYCOMMON_ISOFTCODEMGR_H diff --git a/Code/CryEngine/CryCommon/IStreamEngine.h b/Code/CryEngine/CryCommon/IStreamEngine.h index f325eec389..0536e1f486 100644 --- a/Code/CryEngine/CryCommon/IStreamEngine.h +++ b/Code/CryEngine/CryCommon/IStreamEngine.h @@ -34,7 +34,6 @@ #include #include "smartptr.h" -#include // <> required for Interfuscator #include "CryThread.h" #include "IStreamEngineDefs.h" diff --git a/Code/CryEngine/CryCommon/ISystem.h b/Code/CryEngine/CryCommon/ISystem.h index 86c2b57464..4c6bd73b61 100644 --- a/Code/CryEngine/CryCommon/ISystem.h +++ b/Code/CryEngine/CryCommon/ISystem.h @@ -49,19 +49,15 @@ #include // <> required for Interfuscator #include "CryVersion.h" #include "smartptr.h" -#include // <> required for Interfuscator #include // shared_ptr #include struct ISystem; struct ILog; -struct IProfileLogSystem; namespace AZ::IO { struct IArchive; } -struct IKeyboard; -struct IMouse; struct IConsole; struct IRemoteConsole; struct IRenderer; @@ -79,29 +75,21 @@ struct SFileVersion; struct INameTable; struct ILevelSystem; struct IViewSystem; -struct IMaterialEffects; -class IOpticsManager; class ICrySizer; class IXMLBinarySerializer; struct IReadWriteXMLSink; -struct IThreadTaskManager; struct IResourceManager; struct ITextModeConsole; struct IAVI_Reader; class CPNoise3; -struct IVisualLog; struct ILocalizationManager; -struct ISoftCodeMgr; struct IZLibCompressor; struct IZLibDecompressor; struct ILZ4Decompressor; class IZStdDecompressor; struct IOutputPrintSink; -struct IThreadManager; struct IWindowMessageHandler; struct IImageHandler; -class IResourceCompilerHelper; -class ILmbrAWS; namespace AZ { @@ -111,12 +99,6 @@ namespace AZ } } -class IResourceCompilerHelper; - -namespace Serialization { - struct IArchiveHost; -} - typedef void* WIN_HWND; class CCamera; @@ -124,39 +106,13 @@ struct CLoadingTimeProfiler; class ICmdLine; -struct INotificationNetwork; class ILyShine; -namespace JobManager { - struct IJobManager; -} - -#define PROC_MENU 1 -#define PROC_3DENGINE 2 - -// Summary: -// IDs for script userdata typing. -// Remarks: -// Maybe they should be moved into the game.dll . -//##@{ -#define USER_DATA_SOUND 1 -#define USER_DATA_TEXTURE 2 -#define USER_DATA_OBJECT 3 -#define USER_DATA_LIGHT 4 -#define USER_DATA_BONEHANDLER 5 -#define USER_DATA_POINTER 6 -//##@} - enum ESystemUpdateFlags { - ESYSUPDATE_IGNORE_PHYSICS = 0x0002, // Summary: // Special update mode for editor. - ESYSUPDATE_EDITOR = 0x0004, - ESYSUPDATE_MULTIPLAYER = 0x0008, - ESYSUPDATE_EDITOR_AI_PHYSICS = 0x0010, - ESYSUPDATE_EDITOR_ONLY = 0x0020, - ESYSUPDATE_UPDATE_VIEW_ONLY = 0x0040 + ESYSUPDATE_EDITOR = 0x0004 }; // Description: @@ -189,29 +145,6 @@ enum ESystemConfigPlatform END_CONFIG_PLATFORM_ENUM, // MUST BE LAST VALUE. USED FOR ERROR CHECKING. }; -enum ESubsystem -{ - ESubsys_3DEngine = 0, - ESubsys_AI = 1, - ESubsys_Physics = 2, - ESubsys_Renderer = 3, - ESubsys_Script = 4 -}; - -// Summary: -// Collates cycles taken per update. -struct sUpdateTimes -{ - uint32 PhysYields; - uint64 SysUpdateTime; - uint64 PhysStepTime; - uint64 RenderTime; - //extended yimes info - uint64 physWaitTime; - uint64 streamingWaitTime; - uint64 animationWaitTime; -}; - enum ESystemGlobalState { ESYSTEM_GLOBAL_STATE_UNKNOWN, @@ -568,33 +501,6 @@ struct IErrorObserver // }; -enum ESystemProtectedFunctions -{ - eProtectedFunc_Save = 0, - eProtectedFunc_Load = 1, - eProtectedFuncsLast = 10, -}; - -struct SCvarsDefault -{ - SCvarsDefault() - { - sz_r_DriverDef = NULL; - } - - const char* sz_r_DriverDef; -}; - -#if defined(CVARS_WHITELIST) -struct ICVarsWhitelist -{ - // - virtual ~ICVarsWhitelist() {}; - virtual bool IsWhiteListed(const string& command, bool silent) = 0; - // -}; -#endif // defined(CVARS_WHITELIST) - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION ISYSTEM_H_SECTION_3 #include AZ_RESTRICTED_FILE(ISystem_h) @@ -616,9 +522,6 @@ struct SSystemInitParams { void* hInstance; // void* hWnd; // - void* hWndForInputSystem; // the HWND for the input devices, distinct from the hWnd, which the rendering system overrides anyways - - bool remoteResourceCompiler; ILog* pLog; // You can specify your own ILog to be used by System. ILogCallback* pLogCallback; // You can specify your own ILogCallback to be added on log creation (used by Editor). @@ -633,33 +536,14 @@ struct SSystemInitParams bool bPreview; // When running in Preview mode (Minimal initialization). bool bTestMode; // When running in Automated testing mode. bool bDedicatedServer; // When running a dedicated server. - bool bExecuteCommandLine; // can be switched of to suppress the feature or do it later during the initialization. - bool bSkipFont; // Don't load CryFont.dll bool bSkipConsole; // Don't create console - bool bSkipNetwork; // Don't create Network - bool bSkipWebsocketServer; // Don't create the WebSocket server - bool bMinimal; // Don't load banks - bool bTesting; // CryUnit - bool bNoRandom; //use fixed generator init/seed bool bUnattendedMode; // When running as part of a build on build-machines: Prevent popping up of any dialog bool bSkipMovie; // Don't load movie - bool bSkipAnimation; // Don't load animation bool bToolMode; // System is running inside a tool. Will not create USER directory or anything else that the game needs to do - bool bSkipPhysics; // Don't initialize CryPhysics. - ISystem* pSystem; // Pointer to existing ISystem interface, it will be reused if not NULL. - typedef void* (*ProtectedFunction)(void* param1, void* param2); - ProtectedFunction pProtectedFunctions[eProtectedFuncsLast]; // Protected functions. - - SCvarsDefault* pCvarsDefault; // to override the default value of some cvar - -#if defined(CVARS_WHITELIST) - ICVarsWhitelist* pCVarsWhitelist; // CVars whitelist callback -#endif // defined(CVARS_WHITELIST) - SharedEnvironmentInstance* pSharedEnvironment; // Summary: @@ -668,16 +552,10 @@ struct SSystemInitParams { hInstance = NULL; hWnd = NULL; - hWndForInputSystem = NULL; - - remoteResourceCompiler = false; pLog = NULL; pLogCallback = NULL; pUserCallback = NULL; -#if defined(CVARS_WHITELIST) - pCVarsWhitelist = NULL; -#endif // defined(CVARS_WHITELIST) sLogFileName = NULL; autoBackupLogs = true; pValidator = NULL; @@ -688,32 +566,13 @@ struct SSystemInitParams bPreview = false; bTestMode = false; bDedicatedServer = false; - bExecuteCommandLine = true; - bExecuteCommandLine = true; - bSkipFont = false; bSkipConsole = false; - bSkipNetwork = false; -#if defined(WIN32) || defined(WIN64) - // create websocket server by default. bear in mind that USE_HTTP_WEBSOCKETS is not defined in release. - bSkipWebsocketServer = false; -#else - // CTCPStreamSocket only seems to fully support Win32 and 64 - bSkipWebsocketServer = true; -#endif - bMinimal = false; - bTesting = false; - bNoRandom = false; bUnattendedMode = false; bSkipMovie = false; - bSkipAnimation = false; bToolMode = false; - bSkipPhysics = false; pSystem = NULL; - memset(pProtectedFunctions, 0, sizeof(pProtectedFunctions)); - pCvarsDefault = NULL; - pSharedEnvironment = nullptr; } }; @@ -782,8 +641,6 @@ struct SSystemGlobalEnvironment { AZ::IO::IArchive* pCryPak; AZ::IO::FileIOBase* pFileIO; - IProfileLogSystem* pProfileLogSystem; - IOpticsManager* pOpticsManager; ITimer* pTimer; ICryFont* pCryFont; ::IConsole* pConsole; @@ -791,81 +648,27 @@ struct SSystemGlobalEnvironment ILog* pLog; IMovieSystem* pMovieSystem; INameTable* pNameTable; - IVisualLog* pVisualLog; IRenderer* pRenderer; - IMaterialEffects* pMaterialEffects; - ISoftCodeMgr* pSoftCodeMgr; ILyShine* pLyShine; - IResourceCompilerHelper* pResourceCompilerHelper; SharedEnvironmentInstance* pSharedEnvironment; - IThreadManager* pThreadManager; #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION ISYSTEM_H_SECTION_4 #include AZ_RESTRICTED_FILE(ISystem_h) #endif - ISystemScheduler* pSystemScheduler; - threadID mMainThreadId; //The main thread ID is used in multiple systems so should be stored globally - ////////////////////////////////////////////////////////////////////////// - uint32 nMainFrameID; - - ////////////////////////////////////////////////////////////////////////// - const char* szCmdLine; // Startup command line. - - ////////////////////////////////////////////////////////////////////////// - // Generic debug string which can be easily updated by any system and output by the debug handler - enum - { - MAX_DEBUG_STRING_LENGTH = 128 - }; - char szDebugStatus[MAX_DEBUG_STRING_LENGTH]; - - ////////////////////////////////////////////////////////////////////////// - // Used to tell if this is a server/multiplayer instance - bool bServer; - bool bMultiplayer; - bool bHostMigrating; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // Indicate Editor status. - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// // Used by CRY_ASSERT bool bIgnoreAllAsserts; bool bNoAssertDialog; - bool bTesting; ////////////////////////////////////////////////////////////////////////// - bool bNoRandomSeed; - - SPlatformInfo pi; - - // Protected functions. - SSystemInitParams::ProtectedFunction pProtectedFunctions[eProtectedFuncsLast]; // Protected functions. - - ////////////////////////////////////////////////////////////////////////// - // Flag to able to print out of memory conditon - bool bIsOutOfMemory; - bool bIsOutOfVideoMemory; - bool bToolMode; int retCode = 0; - ILINE const bool IsClient() const - { -#if defined(CONSOLE) - return true; -#else - return bClient; -#endif - } - ILINE const bool IsDedicated() const { #if defined(CONSOLE) @@ -895,11 +698,6 @@ struct SSystemGlobalEnvironment { bDedicated = isDedicated; } - - ILINE void SetIsClient(bool isClient) - { - bClient = isClient; - } #endif //this way the compiler can strip out code for consoles @@ -939,26 +737,6 @@ struct SSystemGlobalEnvironment #endif } - ILINE const bool IsFMVPlaying() const - { - return m_isFMVPlaying; - } - - ILINE void SetFMVIsPlaying(const bool isPlaying) - { - m_isFMVPlaying = isPlaying; - } - - ILINE const bool IsCutscenePlaying() const - { - return m_isCutscenePlaying; - } - - ILINE void SetCutsceneIsPlaying(const bool isPlaying) - { - m_isCutscenePlaying = isPlaying; - } - ILINE bool IsInToolMode() const { return bToolMode; @@ -969,35 +747,17 @@ struct SSystemGlobalEnvironment bToolMode = bNewToolMode; } - ILINE void SetDynamicMergedMeshGenerationEnabled(bool mmgenEnable) - { - m_bDynamicMergedMeshGenerationEnabled = mmgenEnable; - } - - ILINE const bool IsDynamicMergedMeshGenerationEnabled() const - { - return m_bDynamicMergedMeshGenerationEnabled; - } - #if !defined(CONSOLE) private: - bool bClient; bool bEditor; // Engine is running under editor. bool bEditorGameMode; // Engine is in editor game mode. bool bEditorSimulationMode; // Engine is in editor simulation mode. bool bDedicated; // Engine is in dedicated #endif - bool m_isFMVPlaying; - bool m_isCutscenePlaying; - bool m_bDynamicMergedMeshGenerationEnabled; - public: SSystemGlobalEnvironment() - : pSystemScheduler(nullptr) - , szCmdLine("") - , bToolMode(false) - , m_bDynamicMergedMeshGenerationEnabled(false) + : bToolMode(false) { }; }; @@ -1035,37 +795,11 @@ struct IProfilingSystem // Initialize and dispatch all engine's subsystems. struct ISystem { - struct ILoadingProgressListener - { - // - virtual ~ILoadingProgressListener() {} - virtual void OnLoadingProgress(int steps) = 0; - // - }; - -#ifndef _RELEASE - enum LevelLoadOrigin - { - eLLO_Unknown, - eLLO_NewLevel, - eLLO_Level2Level, - eLLO_Resumed, - eLLO_MapCmd, - }; - - struct ICheckpointData - { - int m_totalLoads; - LevelLoadOrigin m_loadOrigin; - }; -#endif - // virtual ~ISystem() {} // Summary: // Releases ISystem. virtual void Release() = 0; - virtual ILoadConfigurationEntrySink* GetCVarsWhiteListConfigSink() const = 0; // will return NULL if no whitelisting // Summary: // Returns pointer to the global environment structure. @@ -1094,9 +828,6 @@ struct ISystem virtual void DoWorkDuringOcclusionChecks() = 0; virtual bool NeedDoWorkDuringOcclusionChecks() = 0; - //! Update screen and call some important tick functions during loading. - virtual void SynchronousLoadingTick(const char* pFunc, int line) = 0; - // Summary: // Returns the current used memory. virtual uint32 GetUsedMemory() = 0; @@ -1170,7 +901,6 @@ struct ISystem virtual IZLibDecompressor* GetIZLibDecompressor() = 0; virtual ILZ4Decompressor* GetLZ4Decompressor() = 0; virtual IZStdDecompressor* GetZStdDecompressor() = 0; - virtual INotificationNetwork* GetINotificationNetwork() = 0; virtual IViewSystem* GetIViewSystem() = 0; virtual ILevelSystem* GetILevelSystem() = 0; virtual INameTable* GetINameTable() = 0; @@ -1187,24 +917,10 @@ struct ISystem // Returns: // Can be NULL, because it only exists when running through the editor, not in pure game mode. virtual IResourceManager* GetIResourceManager() = 0; - virtual IThreadTaskManager* GetIThreadTaskManager() = 0; virtual IProfilingSystem* GetIProfilingSystem() = 0; virtual ISystemEventDispatcher* GetISystemEventDispatcher() = 0; - virtual IVisualLog* GetIVisualLog() = 0; virtual ITimer* GetITimer() = 0; - virtual IThreadManager* GetIThreadManager() = 0; - - virtual void SetLoadingProgressListener(ILoadingProgressListener* pListener) = 0; - virtual ISystem::ILoadingProgressListener* GetLoadingProgressListener() const = 0; - - // Summary: - // Game is created after System init, so has to be set explicitly. - virtual void SetIMaterialEffects(IMaterialEffects* pMaterialEffects) = 0; - virtual void SetIOpticsManager(IOpticsManager* pOpticsManager) = 0; - virtual void SetIVisualLog(IVisualLog* pVisualLog) = 0; - - //virtual const char *GetGamePath()=0; virtual void DebugStats(bool checkpoint, bool leaks) = 0; virtual void DumpWinHeaps() = 0; @@ -1219,7 +935,6 @@ struct ISystem virtual bool WasInDevMode() const = 0; virtual bool IsDevMode() const = 0; virtual bool IsMODValid(const char* szMODName) const = 0; - virtual bool IsMinimalMode() const = 0; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// @@ -1334,12 +1049,6 @@ struct ISystem // Detects and set optimal spec. virtual void AutoDetectSpec(bool detectResolution) = 0; - // Summary: - // Thread management for subsystems - // Return Value: - // Non-0 if the state was indeed changed, 0 if already in that state. - virtual int SetThreadState(ESubsystem subsys, bool bActive) = 0; - // Summary: // Query if system is now paused. // Pause flag is set when calling system update with pause mode. @@ -1406,14 +1115,6 @@ struct ISystem // Get log index of the currently running Open 3D Engine application. (0 = first instance, 1 = second instance, etc) virtual int GetApplicationLogInstance(const char* logFilePath) = 0; - // Summary: - // Retrieves the current stats for systems to update the respective time taken - virtual sUpdateTimes& GetCurrentUpdateTimeStats() = 0; - - // Summary: - // Retrieves the array of update times and the number of entries - virtual const sUpdateTimes* GetUpdateTimeStats(uint32&, uint32&) = 0; - // Summary: // Clear all currently logged and drawn on screen error messages virtual void ClearErrorMessages() = 0; @@ -1458,17 +1159,6 @@ struct ISystem virtual void AsyncMemcpy(void* dst, const void* src, size_t size, int nFlags, volatile int* sync) = 0; // - -#if defined(CVARS_WHITELIST) - virtual ICVarsWhitelist* GetCVarsWhiteList() const = 0; -#endif // defined(CVARS_WHITELIST) - -#ifndef _RELEASE - virtual void GetCheckpointData(ICheckpointData& data) = 0; - virtual void IncreaseCheckpointLoadCount() = 0; - virtual void SetLoadOrigin(LevelLoadOrigin origin) = 0; -#endif - #if !defined(_RELEASE) virtual bool IsSavingResourceList() const = 0; #endif @@ -1513,11 +1203,6 @@ struct ISystem using CrySystemNotificationBus = AZ::EBus; }; -//JAT - this is a very important function for the dedicated server - it lets us run >1000 players per piece of server hardware -//JAT - this saves us lots of money on the dedicated server hardware -#define SYNCHRONOUS_LOADING_TICK() do { if (gEnv && gEnv->pSystem) {gEnv->pSystem->SynchronousLoadingTick(__FUNC__, __LINE__); } \ -} while (0) - #if defined(USE_DISK_PROFILER) struct DiskOperationInfo @@ -1594,7 +1279,7 @@ typedef ISystem* (*PFNCREATESYSTEMINTERFACE)(SSystemInitParams& initParams); ////////////////////////////////////////////////////////////////////////// // Global environment variable. ////////////////////////////////////////////////////////////////////////// -extern SC_API SSystemGlobalEnvironment* gEnv; +extern SSystemGlobalEnvironment* gEnv; // Summary: @@ -1613,11 +1298,6 @@ inline ISystem* GetISystem() } return systemInterface; }; - -inline ISystemScheduler* GetISystemScheduler(void) -{ - return gEnv->pSystemScheduler; -}; ////////////////////////////////////////////////////////////////////////// // Description: @@ -1640,7 +1320,6 @@ void* GetDetachEnvironmentSymbol(); extern bool g_bProfilerEnabled; -extern int g_iTraceAllocations; // Summary: // Interface of the DLL. diff --git a/Code/CryEngine/CryCommon/ISystemScheduler.h b/Code/CryEngine/CryCommon/ISystemScheduler.h deleted file mode 100644 index 9280eb2ea6..0000000000 --- a/Code/CryEngine/CryCommon/ISystemScheduler.h +++ /dev/null @@ -1,63 +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_ISYSTEMSCHEDULER_H -#define CRYINCLUDE_CRYCOMMON_ISYSTEMSCHEDULER_H -#pragma once - -#if defined(__cplusplus) -#define SLICE_AND_SLEEP() do { if (GetISystemScheduler()) { GetISystemScheduler()->SliceAndSleep(__FUNC__, __LINE__); } \ -} while (0) -#define SLICE_SCOPE_DEFINE() CSliceLoadingMonitor sliceScope -#else -extern void SliceAndSleep(const char* pFunc, int line); -#define SLICE_AND_SLEEP() SliceAndSleep(__FILE__, __LINE__) -#endif - -struct ISystemScheduler -{ - virtual ~ISystemScheduler(){} - - // - // Map load slicing functionality support - virtual void SliceAndSleep(const char* sliceName, int line) = 0; - virtual void SliceLoadingBegin() = 0; - virtual void SliceLoadingEnd() = 0; - - virtual void SchedulingSleepIfNeeded(void) = 0; - // -}; - -ISystemScheduler* GetISystemScheduler(void); - -class CSliceLoadingMonitor -{ -public: - CSliceLoadingMonitor() - { - if (GetISystemScheduler()) - { - GetISystemScheduler()->SliceLoadingBegin(); - } - } - - ~CSliceLoadingMonitor() - { - if (GetISystemScheduler()) - { - GetISystemScheduler()->SliceLoadingEnd(); - } - } -}; - -#endif // CRYINCLUDE_CRYCOMMON_ISYSTEMSCHEDULER_H diff --git a/Code/CryEngine/CryCommon/IThreadManager.h b/Code/CryEngine/CryCommon/IThreadManager.h deleted file mode 100644 index 448e3eec16..0000000000 --- a/Code/CryEngine/CryCommon/IThreadManager.h +++ /dev/null @@ -1,111 +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 - -class IThreadConfigManager; - -enum EJoinMode -{ - eJM_TryJoin, - eJM_Join, -}; - -class IThread -{ -public: - // - virtual ~IThread() - { - } - - //! Entry functions for code executed on thread. - virtual void ThreadEntry() = 0; - // -}; - -enum EFPE_Severity -{ - eFPE_None, //!< No Floating Point Exceptions. - eFPE_Basic, //!< Invalid operation, Div by 0. - eFPE_All, //!< Invalid operation, Div by 0, Denormalized operand, Overflow, Underflow, Inexact. - eFPE_LastEntry -}; - -//temp disable CRY DX12 -//#define SCOPED_ENABLE_FLOAT_EXCEPTIONS(eFPESeverity) CScopedFloatingPointException scopedSetFloatExceptionMask(eFPESeverity) -//#define SCOPED_DISABLE_FLOAT_EXCEPTIONS() CScopedFloatingPointException scopedSetFloatExceptionMask(eFPE_None) - -struct IThreadManager -{ -public: - // - virtual ~IThreadManager() - { - } - - //! Get thread config manager. - virtual IThreadConfigManager* GetThreadConfigManager() = 0; - - //! Spawn a new thread and apply thread config settings at thread beginning. - virtual bool SpawnThread(IThread* pThread, const char* sThreadName, ...) = 0; - - //! Wait on another thread to exit (Blocking). - //! Use eJM_TryJoin if you cannot be sure that the target thread is awake. - //! \retval true if target thread has not been started yet or has already exited. - //! \retval false if target thread is still running and therefore not in a state to exit. - virtual bool JoinThread(IThread* pThreadTask, EJoinMode joinStatus) = 0; - - //! Register 3rd party thread with the thread manager. - //! Applies thread config for thread if found. - //! \param pThreadHandle If NULL, the current thread handle will be used. - virtual bool RegisterThirdPartyThread(void* pThreadHandle, const char* sThreadName, ...) = 0; - - //! Unregister 3rd party thread with the thread manager. - virtual bool UnRegisterThirdPartyThread(const char* sThreadName, ...) = 0; - - //! Get Thread Name. - //! Returns "" if thread not found. - virtual const char* GetThreadName(threadID nThreadId) = 0; - - //! Get ThreadID. - virtual threadID GetThreadId(const char* sThreadName, ...) = 0; - - //! Execute function for each other thread but this one. - typedef void (* ThreadModifFunction)(threadID nThreadId, void* pData); - virtual void ForEachOtherThread(IThreadManager::ThreadModifFunction fpThreadModiFunction, void* pFuncData = 0) = 0; - - virtual void EnableFloatExceptions(EFPE_Severity eFPESeverity, threadID nThreadId = 0) = 0; - virtual void EnableFloatExceptionsForEachOtherThread(EFPE_Severity eFPESeverity) = 0; - - virtual uint GetFloatingPointExceptionMask() = 0; - virtual void SetFloatingPointExceptionMask(uint nMask) = 0; - // -}; -/*TEMP DISABLE CRY DX12 -class CScopedFloatingPointException -{ -public: - CScopedFloatingPointException(EFPE_Severity eFPESeverity) - { - oldMask = gEnv->pThreadManager->GetFloatingPointExceptionMask(); - gEnv->pThreadManager->EnableFloatExceptions(eFPESeverity); - } - ~CScopedFloatingPointException() - { - gEnv->pThreadManager->SetFloatingPointExceptionMask(oldMask); - } -private: - uint oldMask; -}; -*/ diff --git a/Code/CryEngine/CryCommon/IThreadTask.h b/Code/CryEngine/CryCommon/IThreadTask.h deleted file mode 100644 index d4a565fcff..0000000000 --- a/Code/CryEngine/CryCommon/IThreadTask.h +++ /dev/null @@ -1,166 +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 "BitFiddling.h" - -#ifndef CRYINCLUDE_CRYCOMMON_ITHREADTASK_H -#define CRYINCLUDE_CRYCOMMON_ITHREADTASK_H -#pragma once - -#include - -// forward declarations -struct SThreadTaskInfo; - -enum EThreadTaskFlags -{ - THREAD_TASK_BLOCKING = BIT(0), // Blocking tasks will be allocated on their own thread. - THREAD_TASK_ASSIGN_TO_POOL = BIT(1), // Task can be assigned to any thread in the group of threads -}; - -class IThreadTask_Thread -{ -public: - // - virtual ~IThreadTask_Thread() {}; - virtual void AddTask(SThreadTaskInfo* pTaskInfo) = 0; - virtual void RemoveTask(SThreadTaskInfo* pTaskInfo) = 0; - virtual void RemoveAllTasks() = 0; - virtual void SingleUpdate() = 0; - // -}; - -typedef int ThreadPoolHandle; - -struct SThreadTaskParams -{ - uint32 nFlags; // Task flags. @see ETaskFlags - union - { - int nPreferedThread; // Preferred Thread index (0,1,2,3...) - ThreadPoolHandle nThreadsGroupId; // Id of group of threads(useful only if THREAD_TASK_ASSIGN_TO_POOL is set) - }; - int16 nPriorityOff; // If THREAD_TASK_BLOCKING, this will adjust the priority of the thread - int16 nStackSizeKB; // If THREAD_TASK_BLOCKING, this will adjust the stack size of the thread - const char* name; // Name for this task (thread for the blocking task will be named using this string) - - SThreadTaskParams() - : nFlags(0) - , nPreferedThread(-1) - , nPriorityOff(0) - , name("") - , nStackSizeKB(SIMPLE_THREAD_STACK_SIZE_KB) {} -}; - -////////////////////////////////////////////////////////////////////////// -// Tasks must implement this interface. -////////////////////////////////////////////////////////////////////////// -struct IThreadTask -{ - // - // The function to be called on every update for non bocking tasks. - // Or will be called only once for the blocking threads. - virtual void OnUpdate() = 0; - - // Called to indicate that this task must quit. - // Warning! can be called from different thread then OnUpdate call. - virtual void Stop() = 0; - - // Returns task info - virtual struct SThreadTaskInfo* GetTaskInfo() = 0; - - virtual ~IThreadTask() {} - // -}; - -struct SThreadTaskInfo - : public CMultiThreadRefCount -{ - IThreadTask_Thread* m_pThread; - IThreadTask* m_pTask; - SThreadTaskParams m_params; - - SThreadTaskInfo() - : m_pThread(NULL) - , m_pTask(NULL) { m_params.nFlags = 0; m_params.nPreferedThread = -1; } -}; - -// Might be changed to uint64 etc in the future -typedef uint32 ThreadPoolAffinityMask; -#define INVALID_AFFINITY 0 - -////////////////////////////////////////////////////////////////////////// -// Description of thread pool to create -////////////////////////////////////////////////////////////////////////// -struct ThreadPoolDesc -{ - ThreadPoolAffinityMask AffinityMask; // number of bits means number of threads. affinity overlapping is prohibited - string sPoolName; - int32 nThreadPriority; - int32 nThreadStackSizeKB; - - ThreadPoolDesc() - : AffinityMask(INVALID_AFFINITY) - , sPoolName("UnnamedPool") - , nThreadPriority(-1) - , nThreadStackSizeKB(-1) { } - - ILINE bool CreateThread(ThreadPoolAffinityMask affinityMask) - { - if (this->AffinityMask & affinityMask) - { - return false; - } - - this->AffinityMask |= affinityMask; - return true; - } - - ILINE uint32 GetThreadCount() const - { - return CountBits(AffinityMask); - } -}; - -////////////////////////////////////////////////////////////////////////// -// Task manager. -////////////////////////////////////////////////////////////////////////// -struct IThreadTaskManager -{ - // - virtual ~IThreadTaskManager(){} - // Register new task to the manager. - virtual void RegisterTask(IThreadTask* pTask, const SThreadTaskParams& options) = 0; - virtual void UnregisterTask(IThreadTask* pTask) = 0; - - // Limit number of threads to this amount. - virtual void SetMaxThreadCount(int nMaxThreads) = 0; - - // Create a pool of threads - virtual ThreadPoolHandle CreateThreadsPool(const ThreadPoolDesc& desc) = 0; - virtual const bool DestroyThreadsPool(const ThreadPoolHandle& handle) = 0; - virtual const bool GetThreadsPoolDesc(const ThreadPoolHandle handle, ThreadPoolDesc* pDesc) const = 0; - virtual const bool SetThreadsPoolAffinity(const ThreadPoolHandle handle, const ThreadPoolAffinityMask AffinityMask) = 0; - - virtual void SetThreadName(threadID dwThreadId, const char* sThreadName) = 0; - virtual const char* GetThreadName(threadID dwThreadId) = 0; - - // Return thread handle by thread name - virtual threadID GetThreadByName(const char* sThreadName) = 0; - - // if bMark=true the calling thread will dump its stack during crashes - virtual void MarkThisThreadForDebugging(const char* name, bool bDump) = 0; - // -}; - -#endif // CRYINCLUDE_CRYCOMMON_ITHREADTASK_H diff --git a/Code/CryEngine/CryCommon/Mocks/IRendererMock.h b/Code/CryEngine/CryCommon/Mocks/IRendererMock.h index 7b0b7b76a2..74d072c48c 100644 --- a/Code/CryEngine/CryCommon/Mocks/IRendererMock.h +++ b/Code/CryEngine/CryCommon/Mocks/IRendererMock.h @@ -585,8 +585,6 @@ public: SDepthTexture * (int, int, bool)); MOCK_METHOD1(DestroyDepthSurface, void(SDepthTexture * pDepthSurf)); - MOCK_CONST_METHOD1(CreateOptics, - IOpticsElementBase * (EFlareType type)); MOCK_METHOD1(PauseTimer, void(bool bPause)); MOCK_METHOD0(CreateShaderPublicParams, diff --git a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h index 1e28937764..cfe150c1df 100644 --- a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h +++ b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h @@ -23,8 +23,6 @@ class SystemMock public: MOCK_METHOD0(Release, void()); - MOCK_CONST_METHOD0(GetCVarsWhiteListConfigSink, - ILoadConfigurationEntrySink * ()); MOCK_METHOD0(GetGlobalEnvironment, SSystemGlobalEnvironment * ()); MOCK_METHOD2(UpdatePreTickBus, @@ -37,8 +35,6 @@ public: void()); MOCK_METHOD0(NeedDoWorkDuringOcclusionChecks, bool()); - MOCK_METHOD2(SynchronousLoadingTick, - void(const char* pFunc, int line)); MOCK_METHOD0(RenderStatistics, void()); MOCK_METHOD0(GetUsedMemory, @@ -84,8 +80,6 @@ public: ILZ4Decompressor * ()); MOCK_METHOD0(GetZStdDecompressor, IZStdDecompressor * ()); - MOCK_METHOD0(GetINotificationNetwork, - INotificationNetwork * ()); MOCK_METHOD0(GetIViewSystem, IViewSystem * ()); MOCK_METHOD0(GetILevelSystem, @@ -116,28 +110,12 @@ public: IRemoteConsole * ()); MOCK_METHOD0(GetIResourceManager, IResourceManager * ()); - MOCK_METHOD0(GetIThreadTaskManager, - IThreadTaskManager * ()); MOCK_METHOD0(GetIProfilingSystem, IProfilingSystem * ()); MOCK_METHOD0(GetISystemEventDispatcher, ISystemEventDispatcher * ()); - MOCK_METHOD0(GetIVisualLog, - IVisualLog * ()); MOCK_METHOD0(GetITimer, ITimer * ()); - MOCK_METHOD0(GetIThreadManager, - IThreadManager * ()); - MOCK_METHOD1(SetLoadingProgressListener, - void(ILoadingProgressListener * pListener)); - MOCK_CONST_METHOD0(GetLoadingProgressListener, - ISystem::ILoadingProgressListener * ()); - MOCK_METHOD1(SetIMaterialEffects, - void(IMaterialEffects * pMaterialEffects)); - MOCK_METHOD1(SetIOpticsManager, - void(IOpticsManager * pOpticsManager)); - MOCK_METHOD1(SetIVisualLog, - void(IVisualLog * pVisualLog)); MOCK_METHOD2(DebugStats, void(bool checkpoint, bool leaks)); MOCK_METHOD0(DumpWinHeaps, @@ -154,8 +132,6 @@ public: bool()); MOCK_CONST_METHOD1(IsMODValid, bool(const char* szMODName)); - MOCK_CONST_METHOD0(IsMinimalMode, - bool()); MOCK_METHOD3(CreateXmlNode, XmlNodeRef(const char*, bool, bool)); MOCK_METHOD4(LoadXmlFromBuffer, @@ -209,8 +185,6 @@ public: void(ESystemConfigPlatform platform)); MOCK_METHOD1(AutoDetectSpec, void(bool detectResolution)); - MOCK_METHOD2(SetThreadState, - int(ESubsystem subsys, bool bActive)); MOCK_CONST_METHOD0(IsPaused, bool()); MOCK_METHOD0(GetLocalizationManager, @@ -239,10 +213,6 @@ public: int()); MOCK_METHOD1(GetApplicationLogInstance, int(const char* logFilePath)); - MOCK_METHOD0(GetCurrentUpdateTimeStats, - sUpdateTimes & ()); - MOCK_METHOD2(GetUpdateTimeStats, - const sUpdateTimes * (uint32 &, uint32 &)); MOCK_METHOD0(ClearErrorMessages, void()); MOCK_METHOD2(debug_GetCallStack, @@ -260,20 +230,6 @@ public: MOCK_METHOD5(AsyncMemcpy, void(void* dst, const void* src, size_t size, int nFlags, volatile int* sync)); -#if defined(CVARS_WHITELIST) - MOCK_CONST_METHOD0(GetCVarsWhiteList, - ICVarsWhitelist * ()); -#endif - -#ifndef _RELEASE - MOCK_METHOD1(GetCheckpointData, - void(ICheckpointData & data)); - MOCK_METHOD0(IncreaseCheckpointLoadCount, - void()); - MOCK_METHOD1(SetLoadOrigin, - void(LevelLoadOrigin origin)); -#endif - #if !defined(_RELEASE) MOCK_CONST_METHOD0(IsSavingResourceList, bool()); diff --git a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_enginesettings_mac_files.cmake b/Code/CryEngine/CryCommon/Platform/Mac/crycommon_enginesettings_mac_files.cmake deleted file mode 100644 index f862be24f6..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_enginesettings_mac_files.cmake +++ /dev/null @@ -1,15 +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 - ../../EngineSettingsBackendApple.cpp - ../../EngineSettingsBackendApple.h -) diff --git a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_enginesettings_windows_files.cmake b/Code/CryEngine/CryCommon/Platform/Windows/crycommon_enginesettings_windows_files.cmake deleted file mode 100644 index db9fd5b464..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_enginesettings_windows_files.cmake +++ /dev/null @@ -1,15 +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 - ../../EngineSettingsBackendWin32.cpp - ../../EngineSettingsBackendWin32.h -) diff --git a/Code/CryEngine/CryCommon/ProfileLog.h b/Code/CryEngine/CryCommon/ProfileLog.h deleted file mode 100644 index fbde619166..0000000000 --- a/Code/CryEngine/CryCommon/ProfileLog.h +++ /dev/null @@ -1,70 +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_PROFILELOG_H -#define CRYINCLUDE_CRYCOMMON_PROFILELOG_H -#pragma once - - -#include // <> required for Interfuscator -#include // <> required for Interfuscator - -struct ILogElement -{ - virtual ~ILogElement(){} - virtual ILogElement* Log (const char* name, const char* message) = 0; - virtual ILogElement* SetTime (float time) = 0; - virtual void Flush (stack_string& indent) = 0; -}; - -struct IProfileLogSystem -{ - virtual ~IProfileLogSystem(){} - virtual ILogElement* Log (const char* name, const char* msg) = 0; - virtual void SetTime (ILogElement* pElement, float time) = 0; - virtual void Release () = 0; -}; - -struct SHierProfileLogItem -{ - SHierProfileLogItem(const char* name, const char* msg, int inbDoLog) - : m_pLogElement(NULL) - , m_bDoLog(inbDoLog) - { - if (m_bDoLog) - { - m_pLogElement = gEnv->pProfileLogSystem->Log(name, msg); - m_startTime = gEnv->pTimer->GetAsyncTime(); - } - } - ~SHierProfileLogItem() - { - if (m_bDoLog) - { - CTimeValue endTime = gEnv->pTimer->GetAsyncTime(); - gEnv->pProfileLogSystem->SetTime(m_pLogElement, (endTime - m_startTime).GetMilliSeconds()); - } - } - -private: - int m_bDoLog; - CTimeValue m_startTime; - ILogElement* m_pLogElement; -}; - -#define HPROFILE_BEGIN(msg1, msg2, doLog) { SHierProfileLogItem __hier_profile_uniq_var_in_this_scope__(msg1, msg2, doLog); -#define HPROFILE_END() } - -#define HPROFILE(msg1, msg2, doLog) SHierProfileLogItem __hier_profile_uniq_var_in_this_scope__(msg1, msg2, doLog); - -#endif // CRYINCLUDE_CRYCOMMON_PROFILELOG_H diff --git a/Code/CryEngine/CryCommon/ProjectDefines.h b/Code/CryEngine/CryCommon/ProjectDefines.h index f82861d6e0..67ae58a324 100644 --- a/Code/CryEngine/CryCommon/ProjectDefines.h +++ b/Code/CryEngine/CryCommon/ProjectDefines.h @@ -78,9 +78,6 @@ typedef uint32 vtx_idx; #if defined(WIN32) || defined(WIN64) || LOG_CONST_CVAR_ACCESS #define RELEASE_LOGGING -//#if defined(_RELEASE) -//#define CVARS_WHITELIST -//#endif // defined(_RELEASE) #endif #if defined(_RELEASE) && !defined(RELEASE_LOGGING) @@ -181,32 +178,6 @@ typedef uint32 vtx_idx; #define SHADER_REFLECT_TEXTURE_SLOTS 0 #endif -#if (defined(WIN32) || defined(WIN64) || defined(AZ_PLATFORM_MAC)) && (!defined(AZ_MONOLITHIC_BUILD) || defined(RESOURCE_COMPILER)) -#define CRY_ENABLE_RC_HELPER 1 -#endif - -#if !defined(_RELEASE) && PROJECTDEFINES_H_TRAIT_ENABLE_SOFTCODE_SYSTEM - #define SOFTCODE_SYSTEM_ENABLED -#endif - -// Is SoftCoding enabled for this module? Usually set by the SoftCode AddIn in conjunction with a SoftCode.props file. -#ifdef SOFTCODE_ENABLED - -// Is this current compilation unit part of a SOFTCODE build? - #ifdef SOFTCODE -// Import any SC functions from the host module - #define SC_API __declspec(dllimport) - #else -// Export any SC functions from the host module - #define SC_API __declspec(dllexport) - #endif - -#else // SoftCode disabled - - #define SC_API - -#endif - // these enable and disable certain net features to give compatibility between PCs and consoles / profile and performance builds #define PC_CONSOLE_NET_COMPATIBLE 0 #define PROFILE_PERFORMANCE_NET_COMPATIBLE 0 @@ -292,10 +263,6 @@ typedef uint32 vtx_idx; # define ENABLE_LOADING_PROFILER // requires AZ_PROFILE_TELEMETRY to also be defined #endif -#if defined(SOFTCODE_ENABLED) - #error "SoftCode currently relies on CryMemoryManager being enabled. Either build without SoftCode support, or enable CryMemoryManager." -#endif - #if PROJECTDEFINES_H_TRAIT_USE_GPU_PARTICLES && !defined(NULL_RENDERER) #define GPU_PARTICLES 1 #else diff --git a/Code/CryEngine/CryCommon/ResourceCompilerHelper.cpp b/Code/CryEngine/CryCommon/ResourceCompilerHelper.cpp deleted file mode 100644 index 33373f7460..0000000000 --- a/Code/CryEngine/CryCommon/ResourceCompilerHelper.cpp +++ /dev/null @@ -1,639 +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 "ProjectDefines.h" - -#if defined(CRY_ENABLE_RC_HELPER) - -#include "ResourceCompilerHelper.h" -#include "EngineSettingsManager.h" - -// When complining CryTiffPlugin the mayaAssert.h is included that defined -// Assert as _Assert. This wreaks havoc with AZ_Assert since under the covers -// it calls AzCore::Debug::Trace::Assert, which gets transformed bo -// Trace::_Assert, which does not exist. Gotta love macros. Undefine Assert -// before we include semaphore so that it can compile correctly -#if defined(Assert) -#undef Assert -#endif - -#include -#include -#include -#include -#include - -#if defined(AZ_PLATFORM_WINDOWS) -#include -#include // ShellExecuteW() -#endif - -#if AZ_TRAIT_OS_PLATFORM_APPLE -#include "AppleSpecific.h" -#include -#else -#undef RC_EXECUTABLE -#define RC_EXECUTABLE "rc.exe" -#endif - -#include -#include // lawsonn - we use std::string internally -#include - -namespace -{ - class LineStreamBuffer - { - public: - template - LineStreamBuffer(T* object, void (T::* method)(const char* line)) - : m_charCount(0) - , m_bTruncated(false) - { - m_target = new Target(object, method); - } - - ~LineStreamBuffer() - { - Flush(); - delete m_target; - } - - void HandleText(const char* text, int length) - { - const char* pos = text; - while (pos - text < length) - { - const char* start = pos; - - while (pos - text < length && *pos != '\n' && *pos != '\r') - { - ++pos; - } - - size_t n = pos - start; - if (m_charCount + n > kMaxCharCount) - { - n = kMaxCharCount - m_charCount; - m_bTruncated = true; - } - memcpy(&m_buffer[m_charCount], start, n); - m_charCount += n; - - if (pos - text < length) - { - Flush(); - while (pos - text < length && (*pos == '\n' || *pos == '\r')) - { - ++pos; - } - } - } - } - - void Flush() - { - if (m_charCount > 0) - { - m_buffer[m_charCount] = 0; - m_target->Call(m_buffer); - m_charCount = 0; - } - } - - bool IsTruncated() const - { - return m_bTruncated; - } - - private: - struct ITarget - { - virtual ~ITarget() {} - virtual void Call(const char* line) = 0; - }; - template - struct Target - : public ITarget - { - public: - Target(T* object, void (T::* method)(const char* line)) - : object(object) - , method(method) {} - virtual void Call(const char* line) - { - (object->*method)(line); - } - private: - T* object; - void (T::* method)(const char* line); - }; - - ITarget* m_target; - size_t m_charCount; - static const size_t kMaxCharCount = 2047; - char m_buffer[kMaxCharCount + 1]; - bool m_bTruncated; - }; - -#if !defined(AZ_PLATFORM_WINDOWS) - void MessageBoxW(int, const wchar_t* header, const wchar_t* message, unsigned long) - { -#if AZ_TRAIT_OS_PLATFORM_APPLE - CFStringEncoding encoding = (CFByteOrderLittleEndian == CFByteOrderGetCurrent()) ? - kCFStringEncodingUTF32LE : kCFStringEncodingUTF32BE; - CFStringRef header_ref = CFStringCreateWithBytes(nullptr, reinterpret_cast(header), wcslen(header) * sizeof(wchar_t), encoding, false); - CFStringRef message_ref = CFStringCreateWithBytes(nullptr, reinterpret_cast(message), wcslen(message) * sizeof(wchar_t), encoding, false); - - CFOptionFlags result; //result code from the message box - - CFUserNotificationDisplayAlert(0, kCFUserNotificationStopAlertLevel, 0, 0, 0, header_ref, message_ref, 0, 0, 0, &result); - - CFRelease(header_ref); - CFRelease(message_ref); -#endif - } -#endif -} - -namespace -{ - class RcLock - { - public: - RcLock() - : m_cs(0u, 1u) - { - m_cs.release(); - } - ~RcLock() - { - } - - void Lock() - { - m_cs.acquire(); - } - void Unlock() - { - m_cs.release(); - } - - private: - AZStd::semaphore m_cs; - }; - - - template - class RcAutoLock - { - public: - RcAutoLock(LockClass& lock) - : m_lock(lock) - { - m_lock.Lock(); - } - ~RcAutoLock() - { - m_lock.Unlock(); - } - - private: - RcAutoLock(); - RcAutoLock(const RcAutoLock&); - RcAutoLock& operator =(const RcAutoLock&); - - private: - LockClass& m_lock; - }; - - - HANDLE s_rcProcessHandle = 0; - RcLock s_rcProcessHandleLock; -} - -////////////////////////////////////////////////////////////////////////// -static void ShowMessageBoxRcNotFound([[maybe_unused]] const wchar_t* const szCmdLine, [[maybe_unused]] const wchar_t* const szDir) -{ - SettingsManagerHelpers::CFixedString tmp; - - tmp.append(L"The resource compiler (RC.EXE) was not found."); - MessageBoxW(0, tmp.c_str(), L"Error", MB_ICONERROR | MB_OK); -} - - -////////////////////////////////////////////////////////////////////////// -namespace -{ - class ResourceCompilerLineHandler - { - public: - ResourceCompilerLineHandler(IResourceCompilerListener* listener) - : m_listener(listener) - { - } - - void HandleLine(const char* line) - { - if (!m_listener || !line) - { - return; - } - - // check the first three characters to see if it's a warning or error. - bool bHasPrefix; - IResourceCompilerListener::MessageSeverity severity; - if ((line[0] == 'E') && (line[1] == ':') && (line[2] == ' ')) - { - bHasPrefix = true; - severity = IResourceCompilerListener::MessageSeverity_Error; - line += 3; // skip the prefix - } - else if ((line[0] == 'W') && (line[1] == ':') && (line[2] == ' ')) - { - bHasPrefix = true; - severity = IResourceCompilerListener::MessageSeverity_Warning; - line += 3; // skip the prefix - } - else if ((line[0] == ' ') && (line[1] == ' ') && (line[2] == ' ')) - { - bHasPrefix = true; - severity = IResourceCompilerListener::MessageSeverity_Info; - line += 3; // skip the prefix - } - else - { - bHasPrefix = false; - severity = IResourceCompilerListener::MessageSeverity_Info; - } - - if (bHasPrefix) - { - // skip thread info "%d>", if present - { - const char* p = line; - while (*p == ' ') - { - ++p; - } - if (isdigit(*p)) - { - while (isdigit(*p)) - { - ++p; - } - if (*p == '>') - { - line = p + 1; - } - } - } - - // skip time info "%d:%d", if present - { - const char* p = line; - while (*p == ' ') - { - ++p; - } - if (isdigit(*p)) - { - while (isdigit(*p)) - { - ++p; - } - if (*p == ':') - { - ++p; - if (isdigit(*p)) - { - while (isdigit(*p)) - { - ++p; - } - while (*p == ' ') - { - ++p; - } - line = p; - } - } - } - } - } - - m_listener->OnRCMessage(severity, line); - } - - private: - IResourceCompilerListener* m_listener; - }; - - // we now support macros like #ENGINEROOT# in the string: - void replaceAllInStringInPlace(std::string& inOut, const char* findValue, const char* replaceValue) - { - if (!findValue) - { - return; - } - - if (!replaceValue) - { - return; - } - - std::string::size_type pos = std::string::npos; - std::string::size_type replaceLen = strlen(findValue); - - while ((pos = inOut.find(findValue)) != std::string::npos) - { - inOut.replace(pos, replaceLen, replaceValue); - } - } - - // given a string that contains macros (like #ENGINEROOT#), eliminate the macros and replace them with the real data. - // note that in the 'remote' implementation, these macros are sent to the remote RC. It can then expand them for its own environment - // but in a local RC, these macros are expanded by the local environment. - void expandMacros(const char* inputString, char* outputString, std::size_t bufferSize) - { - if (!inputString) - { - return; - } - - if (!outputString) - { - return; - } - - AZStd::string_view rootFolder; - AZ::ComponentApplicationBus::BroadcastResult(rootFolder, &AZ::ComponentApplicationRequests::GetAppRoot); - - std::string finalString(inputString); - const AZStd::string rootFolderStr = rootFolder.data(); - replaceAllInStringInPlace(finalString, "#ENGINEROOT#", rootFolderStr.c_str()); - // put additional replacements here. - - azstrcpy(outputString, bufferSize, finalString.c_str()); - } -} - -////////////////////////////////////////////////////////////////////////// -IResourceCompilerHelper::ERcCallResult CResourceCompilerHelper::CallResourceCompiler( - const char* szFileName, - const char* szAdditionalSettings, - IResourceCompilerListener* listener, - bool bMayShowWindow, - bool bSilent, - bool bNoUserDialog, - const wchar_t* szWorkingDirectory, - [[maybe_unused]] const wchar_t* szRootPath) -{ -#if defined(AZ_PLATFORM_WINDOWS) - HANDLE hChildStdOutRd = INVALID_HANDLE_VALUE, hChildStdOutWr = INVALID_HANDLE_VALUE; - HANDLE hChildStdInRd = INVALID_HANDLE_VALUE, hChildStdInWr = INVALID_HANDLE_VALUE; - PROCESS_INFORMATION pi; -#else - FILE* hChildStdOutRd; -#endif - - { - RcAutoLock lock(s_rcProcessHandleLock); - - // make command for execution - SettingsManagerHelpers::CFixedString wRemoteCmdLine; - - - if (!szAdditionalSettings) - { - szAdditionalSettings = ""; - } - - // expand the additioanl settings. - char szActualFileName[512] = {0}; - char szActualAdditionalSettings[512] = {0}; - - expandMacros(szFileName, szActualFileName, 512); - expandMacros(szAdditionalSettings, szActualAdditionalSettings, 512); - - CSettingsManagerTools smTools = CSettingsManagerTools(); // moved this line to after macro expansion to avoid multiple of these existing at once. - - AZStd::string_view exeFolderName; - AZ::ComponentApplicationBus::BroadcastResult(exeFolderName, &AZ::ComponentApplicationRequests::GetExecutableFolder); - - wchar_t szRegSettingsBuffer[1024]; - smTools.GetEngineSettingsManager()->GetValueByRef("RC_Parameters", SettingsManagerHelpers::CWCharBuffer(szRegSettingsBuffer, sizeof(szRegSettingsBuffer))); - bool enableSourceControl = true; - smTools.GetEngineSettingsManager()->GetValueByRef("RC_EnableSourceControl", enableSourceControl); - - wRemoteCmdLine.appendAscii("\""); - wRemoteCmdLine.appendAscii(exeFolderName.data(), exeFolderName.size()); - wRemoteCmdLine.appendAscii("/"); - wRemoteCmdLine.appendAscii(RC_EXECUTABLE); - wRemoteCmdLine.appendAscii("\""); - - if (!enableSourceControl) - { - wRemoteCmdLine.appendAscii(" -nosourcecontrol "); - } - - if (!szFileName) - { - wRemoteCmdLine.appendAscii(" -userdialog=0 "); - wRemoteCmdLine.appendAscii(szActualAdditionalSettings); - wRemoteCmdLine.appendAscii(" "); - wRemoteCmdLine.append(szRegSettingsBuffer); - } - else - { - wRemoteCmdLine.appendAscii(" \""); - wRemoteCmdLine.appendAscii(szActualFileName); - wRemoteCmdLine.appendAscii("\""); - wRemoteCmdLine.appendAscii(bNoUserDialog ? " -userdialog=0 " : " -userdialog=1 "); - wRemoteCmdLine.appendAscii(szActualAdditionalSettings); - wRemoteCmdLine.appendAscii(" "); - wRemoteCmdLine.append(szRegSettingsBuffer); - } - - // Create a pipe to read the stdout of the RC. - SECURITY_ATTRIBUTES saAttr; - if (listener) - { -#if defined(AZ_PLATFORM_WINDOWS) - ZeroMemory(&saAttr, sizeof(saAttr)); - saAttr.bInheritHandle = TRUE; - saAttr.lpSecurityDescriptor = 0; - CreatePipe(&hChildStdOutRd, &hChildStdOutWr, &saAttr, 0); - SetHandleInformation(hChildStdOutRd, HANDLE_FLAG_INHERIT, 0); // Need to do this according to MSDN - CreatePipe(&hChildStdInRd, &hChildStdInWr, &saAttr, 0); - SetHandleInformation(hChildStdInWr, HANDLE_FLAG_INHERIT, 0); // Need to do this according to MSDN -#endif - } - -#if defined(AZ_PLATFORM_WINDOWS) - STARTUPINFOW si; - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - si.dwX = 100; - si.dwY = 100; - if (listener) - { - si.hStdError = hChildStdOutWr; - si.hStdOutput = hChildStdOutWr; - si.hStdInput = hChildStdInRd; - si.dwFlags = STARTF_USEPOSITION | STARTF_USESTDHANDLES; - } - else - { - si.dwFlags = STARTF_USEPOSITION; - } - - ZeroMemory(&pi, sizeof(pi)); -#endif - - bool bShowWindow; - if (bMayShowWindow) - { - wchar_t buffer[20]; - smTools.GetEngineSettingsManager()->GetValueByRef("ShowWindow", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))); - bShowWindow = (wcscmp(buffer, L"true") == 0); - } - else - { - bShowWindow = false; - } - -#if defined(AZ_PLATFORM_WINDOWS) - const wchar_t* szStartingDirectory = szWorkingDirectory; - if (!szStartingDirectory) - { - char currentDirectory[MAX_PATH]; - AZ::Utils::GetExecutableDirectory(currentDirectory, MAX_PATH); - SettingsManagerHelpers::CFixedString wCurrentDirectory; - wCurrentDirectory.appendAscii(currentDirectory); - szStartingDirectory = wCurrentDirectory.c_str(); - } - - - if (!CreateProcessW( - NULL, // No module name (use command line). - const_cast(wRemoteCmdLine.c_str()), // Command line. - NULL, // Process handle not inheritable. - NULL, // Thread handle not inheritable. - TRUE, // Set handle inheritance to TRUE. - bShowWindow ? 0 : CREATE_NO_WINDOW, // creation flags. - NULL, // Use parent's environment block. - szStartingDirectory, // Set starting directory. - &si, // Pointer to STARTUPINFO structure. - &pi)) // Pointer to PROCESS_INFORMATION structure. - { - // The following code block is commented out instead of being deleted - // because it's good to have at hand for a debugging session. - #if 0 - const size_t charsInMessageBuffer = 32768; // msdn about FormatMessage(): "The output buffer cannot be larger than 64K bytes." - wchar_t szMessageBuffer[charsInMessageBuffer] = L""; - FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, szMessageBuffer, charsInMessageBuffer, NULL); - GetCurrentDirectoryW(charsInMessageBuffer, szMessageBuffer); - #endif - - if (!bSilent) - { - ShowMessageBoxRcNotFound(wRemoteCmdLine.c_str(), szStartingDirectory); - } - - return eRcCallResult_notFound; - } - - s_rcProcessHandle = pi.hProcess; -#else - int fd = open(".", O_RDONLY); - char remoteCmdLineUtf8[MAX_PATH * 8]; - char workingDirectory[MAX_PATH * 8]; - ConvertUtf16ToUtf8(wRemoteCmdLine.c_str(), SettingsManagerHelpers::CCharBuffer(remoteCmdLineUtf8, MAX_PATH * 8)); - if (szWorkingDirectory) - { - ConvertUtf16ToUtf8(szWorkingDirectory, SettingsManagerHelpers::CCharBuffer(workingDirectory, MAX_PATH * 8)); - chdir(workingDirectory); - } - hChildStdOutRd = popen(remoteCmdLineUtf8, "r"); - fchdir(fd); - if (hChildStdOutRd == nullptr) - { - if (!bSilent) - { - ShowMessageBoxRcNotFound(wRemoteCmdLine.c_str(), szWorkingDirectory); - } - return eRcCallResult_notFound; - } -#endif - } - - bool bFailedToReadOutput = false; - - if (listener) - { -#if defined(AZ_PLATFORM_WINDOWS) - // Close the pipe that writes to the child process, since we don't actually have any input for it. - CloseHandle(hChildStdInWr); - - // Read all the output from the child process. - CloseHandle(hChildStdOutWr); -#endif - ResourceCompilerLineHandler lineHandler(listener); - LineStreamBuffer lineBuffer(&lineHandler, &ResourceCompilerLineHandler::HandleLine); - for (;; ) - { - char buffer[2048]; - DWORD bytesRead; -#if defined(AZ_PLATFORM_WINDOWS) - if (!ReadFile(hChildStdOutRd, buffer, sizeof(buffer), &bytesRead, NULL) || (bytesRead == 0)) -#else - if (fgets(buffer, sizeof(buffer), hChildStdOutRd) == nullptr || (bytesRead = strlen(buffer) == 0)) -#endif - { - break; - } - lineBuffer.HandleText(buffer, bytesRead); - } - - bFailedToReadOutput = lineBuffer.IsTruncated(); - } - -#if defined(AZ_PLATFORM_WINDOWS) - // Wait until child process exits. - WaitForSingleObject(pi.hProcess, INFINITE); -#else - DWORD exitCode = pclose(hChildStdOutRd); -#endif - -#if defined(AZ_PLATFORM_WINDOWS) - RcAutoLock lock(s_rcProcessHandleLock); - s_rcProcessHandle = 0; - - DWORD exitCode = eRcExitCode_Error; - if (bFailedToReadOutput || GetExitCodeProcess(pi.hProcess, &exitCode) == 0) - { - exitCode = eRcExitCode_Error; - } - - // Close process and thread handles. - CloseHandle(pi.hProcess); - CloseHandle(pi.hThread); -#endif - - return ConvertResourceCompilerExitCodeToResultCode(exitCode); -} - - -#endif //(CRY_ENABLE_RC_HELPER) diff --git a/Code/CryEngine/CryCommon/ResourceCompilerHelper.h b/Code/CryEngine/CryCommon/ResourceCompilerHelper.h deleted file mode 100644 index 913d72f642..0000000000 --- a/Code/CryEngine/CryCommon/ResourceCompilerHelper.h +++ /dev/null @@ -1,46 +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_RESOURCECOMPILERHELPER_H -#define CRYINCLUDE_CRYCOMMON_RESOURCECOMPILERHELPER_H - -#pragma once - -#if defined(CRY_ENABLE_RC_HELPER) - -#include "IResourceCompilerHelper.h" - -////////////////////////////////////////////////////////////////////////// -// Provides settings and functions to make calls to RC. -// calls RC locally. only works on windows, does not exist on other platforms -// note: You shouldn't be calling this directly -// instead, you should be calling it via the IResourceCompilerHelper interface. -// since it may be replaced with a custom RC for your platform or a remote invocation -class CResourceCompilerHelper - : public IResourceCompilerHelper -{ -public: - virtual ERcCallResult CallResourceCompiler( - const char* szFileName = 0, - const char* szAdditionalSettings = 0, - IResourceCompilerListener* listener = 0, - bool bMayShowWindow = true, - bool bSilent = false, - bool bNoUserDialog = false, - const wchar_t* szWorkingDirectory = 0, - const wchar_t* szRootPath = 0) override; -}; - -#endif // CRY_ENABLE_RC_HELPER - -#endif // CRYINCLUDE_CRYCOMMON_RESOURCECOMPILERHELPER_H diff --git a/Code/CryEngine/CryCommon/SettingsManagerHelpers.cpp b/Code/CryEngine/CryCommon/SettingsManagerHelpers.cpp deleted file mode 100644 index 9746b00574..0000000000 --- a/Code/CryEngine/CryCommon/SettingsManagerHelpers.cpp +++ /dev/null @@ -1,325 +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 "ProjectDefines.h" - -#if defined(CRY_ENABLE_RC_HELPER) - -#include "SettingsManagerHelpers.h" -#include "EngineSettingsManager.h" - -#include -#include -#include - -#include -#include - -#if defined(AZ_PLATFORM_WINDOWS) -#include -#include //ShellExecuteW() -#pragma comment(lib, "Shell32.lib") -#endif -#if AZ_TRAIT_OS_PLATFORM_APPLE -#include "AppleSpecific.h" -#endif - -bool SettingsManagerHelpers::Utf16ContainsAsciiOnly(const wchar_t* wstr) -{ - while (*wstr) - { - if (*wstr > 127 || *wstr < 0) - { - return false; - } - ++wstr; - } - return true; -} - - -void SettingsManagerHelpers::ConvertUtf16ToUtf8(const wchar_t* src, CCharBuffer dst) -{ - if (dst.getSizeInElements() <= 0) - { - return; - } - - if (src[0] == 0) - { - dst[0] = 0; - } - else - { - const std::codecvt& utf8Utf16Facet = std::use_facet>(std::locale()); - std::mbstate_t mb{}; - const wchar_t* from_next; - char* to_next; - std::codecvt_base::result result = utf8Utf16Facet.out(mb, src, src + wcslen(src), from_next, dst.getPtr(), dst.getPtr() + dst.getSizeInElements(), to_next); - if (result != std::codecvt_base::ok) - { - dst[0] = 0; - } - else - { - to_next = 0; - } - } -} - - -void SettingsManagerHelpers::ConvertUtf8ToUtf16(const char* src, CWCharBuffer dst) -{ - if (dst.getSizeInElements() <= 0) - { - return; - } - - if (src[0] == 0) - { - dst[0] = 0; - } - else - { - const std::codecvt& utf8Utf16Facet = std::use_facet>(std::locale()); - std::mbstate_t mb{}; - const char* from_next; - wchar_t* to_next; - std::codecvt_base::result result = utf8Utf16Facet.in(mb, src, src + strlen(src), from_next, dst.getPtr(), dst.getPtr() + dst.getSizeInElements(), to_next); - if (result != std::codecvt_base::ok) - { - dst[0] = 0; - } - else - { - to_next = 0; - } - } -} - - -void SettingsManagerHelpers::GetAsciiFilename(const wchar_t* wfilename, CCharBuffer buffer) -{ - if (buffer.getSizeInElements() <= 0) - { - return; - } - - if (wfilename[0] == 0) - { - buffer[0] = 0; - return; - } - - if (Utf16ContainsAsciiOnly(wfilename)) - { - ConvertUtf16ToUtf8(wfilename, buffer); - return; - } - -#if defined(AZ_PLATFORM_WINDOWS) - // The path is non-ASCII unicode, so let's resort to short filenames (they are always ASCII-only, I hope) - wchar_t shortW[MAX_PATH]; - const int bufferCharCount = sizeof(shortW) / sizeof(shortW[0]); - const int charCount = GetShortPathNameW(wfilename, shortW, bufferCharCount); - if (charCount <= 0 || charCount >= bufferCharCount) - { - buffer[0] = 0; - return; - } - - shortW[charCount] = 0; - if (!Utf16ContainsAsciiOnly(shortW)) - { - buffer[0] = 0; - return; - } - - ConvertUtf16ToUtf8(shortW, buffer); -#else - buffer[0] = 0; -#endif -} - - -////////////////////////////////////////////////////////////////////////// -CSettingsManagerTools::CSettingsManagerTools(const wchar_t* szModuleName) -{ - m_pSettingsManager = new CEngineSettingsManager(szModuleName); -} - -////////////////////////////////////////////////////////////////////////// -CSettingsManagerTools::~CSettingsManagerTools() -{ - delete m_pSettingsManager; -} - -////////////////////////////////////////////////////////////////////////// -bool CSettingsManagerTools::GetInstalledBuildPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) -{ - return m_pSettingsManager->GetInstalledBuildRootPathUtf16(index, name, path); -} - - -bool CSettingsManagerTools::GetInstalledBuildPathAscii(const int index, SettingsManagerHelpers::CCharBuffer name, SettingsManagerHelpers::CCharBuffer path) -{ - wchar_t wName[MAX_PATH]; - wchar_t wPath[MAX_PATH]; - if (GetInstalledBuildPathUtf16(index, SettingsManagerHelpers::CWCharBuffer(wName, sizeof(wName)), SettingsManagerHelpers::CWCharBuffer(wPath, sizeof(wPath)))) - { - SettingsManagerHelpers::GetAsciiFilename(wName, name); - SettingsManagerHelpers::GetAsciiFilename(wPath, path); - return true; - } - return false; -} - - - -////////////////////////////////////////////////////////////////////////// -static bool FileExists(const wchar_t* filename) -{ -#if defined(AZ_PLATFORM_WINDOWS) - const DWORD dwAttrib = GetFileAttributesW(filename); - return dwAttrib != INVALID_FILE_ATTRIBUTES && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY); -#else - char utf8Filename[MAX_PATH]; - SettingsManagerHelpers::ConvertUtf16ToUtf8(filename, SettingsManagerHelpers::CCharBuffer(utf8Filename, sizeof(utf8Filename))); - struct stat buffer; - return (stat(utf8Filename, &buffer) == 0); -#endif -} - - -////////////////////////////////////////////////////////////////////////// -void CSettingsManagerTools::GetEditorExecutable(SettingsManagerHelpers::CWCharBuffer wbuffer) -{ - if (wbuffer.getSizeInElements() <= 0) - { - return; - } - - AZStd::string_view exePath; - AZ::ComponentApplicationBus::BroadcastResult(exePath, &AZ::ComponentApplicationRequests::GetExecutableFolder); - - SettingsManagerHelpers::CFixedString editorExe; - editorExe = wbuffer.getPtr(); - editorExe.appendAscii(exePath.data(), exePath.size()); - - if (editorExe.length() <= 0) - { - wbuffer[0] = 0; - return; - } - - bool bFound = false; - if (Is64bitWindows()) - { - const size_t len = editorExe.length(); - editorExe.appendAscii("/Editor.exe"); - bFound = FileExists(editorExe.c_str()); - if (!bFound) - { - editorExe.setLength(len); - } - } - - const size_t sizeToCopy = (editorExe.length() + 1) * sizeof(wbuffer[0]); - if (!bFound || sizeToCopy > wbuffer.getSizeInBytes()) - { - wbuffer[0] = 0; - } - else - { - memcpy(wbuffer.getPtr(), editorExe.c_str(), sizeToCopy); - } -} - - -////////////////////////////////////////////////////////////////////////// -bool CSettingsManagerTools::CallEditor(void** pEditorWindow, [[maybe_unused]] void* hParent, const char* pWindowName, const char* pFlag) -{ -#if !defined(AZ_PLATFORM_WINDOWS) - AZ_Assert(false, "CSettingsManagerTools::CallEditor is not supported on this platform!"); - return false; -#else - HWND window = ::FindWindowA(NULL, pWindowName); - if (window) - { - *pEditorWindow = window; - return true; - } - else - { - *pEditorWindow = 0; - - wchar_t buffer[512] = { L'\0' }; - GetEditorExecutable(SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))); - - SettingsManagerHelpers::CFixedString wFlags; - SettingsManagerHelpers::ConvertUtf8ToUtf16(pFlag, wFlags.getBuffer()); - wFlags.setLength(wcslen(wFlags.c_str())); - - if (buffer[0] != '\0') - { - INT_PTR hIns = (INT_PTR)ShellExecuteW(NULL, L"open", buffer, wFlags.c_str(), NULL, SW_SHOWNORMAL); - if (hIns > 32) - { - return true; - } - else - { - MessageBoxA(0, "Editor.exe was not found.\n\nPlease verify CryENGINE root path.", "Error", MB_ICONERROR | MB_OK); - } - } - } - - return false; -#endif -} - -////////////////////////////////////////////////////////////////////////// -// Modified version of -// http://msdn.microsoft.com/en-us/library/windows/desktop/ms684139(v=vs.85).aspx -bool CSettingsManagerTools::Is64bitWindows() -{ -#if defined(_WIN64) - // 64-bit programs run only on 64-bit Windows - return true; -#elif !defined(AZ_PLATFORM_WINDOWS) - return false; -#else - // 32-bit programs run on both 32-bit and 64-bit Windows - static bool bWin64 = false; - static bool bOnce = true; - if (bOnce) - { - typedef BOOL (WINAPI * LPFN_ISWOW64PROCESS)(HANDLE, PBOOL); - LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandleA("kernel32"), "IsWow64Process"); - if (fnIsWow64Process != NULL) - { - BOOL itIsWow64Process = FALSE; - if (fnIsWow64Process(GetCurrentProcess(), &itIsWow64Process)) - { - bWin64 = (itIsWow64Process == TRUE); - } - } - bOnce = false; - } - return bWin64; -#endif -} - -#endif // #if defined(CRY_ENABLE_RC_HELPER) - -// eof diff --git a/Code/CryEngine/CryCommon/SettingsManagerHelpers.h b/Code/CryEngine/CryCommon/SettingsManagerHelpers.h deleted file mode 100644 index e05d2b97aa..0000000000 --- a/Code/CryEngine/CryCommon/SettingsManagerHelpers.h +++ /dev/null @@ -1,491 +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_SETTINGSMANAGERHELPERS_H -#define CRYINCLUDE_CRYCOMMON_SETTINGSMANAGERHELPERS_H -#pragma once - -#include "ProjectDefines.h" -#include // memcpy -#include // std::min - - -namespace SettingsManagerHelpers -{ - namespace Utils - { - inline size_t strlen(const char* p) - { - return p ? ::strlen(p) : 0; - } - - inline size_t strcmp(const char* p0, const char* p1) - { - return ::strcmp(p0, p1); - } - - - inline size_t strlen(const wchar_t* p) - { - return p ? ::wcslen(p) : 0; - } - - inline size_t strcmp(const wchar_t* p0, const wchar_t* p1) - { - return ::wcscmp(p0, p1); - } - } - - // The function copies characters from src to dst one by one until any of - // the following conditions is met: - // 1) the end of the destination buffer (minus one character) is reached - // 2) the end of the source buffer is reached - // 3) zero character is found in the source buffer - // - // When any of 1), 2), 3) happens, the function writes the terminating zero - // character to the destination buffer and return. - // - // The function guarantees writing the terminating zero character to the - // destination buffer (if the buffer can fit at least one character). - // - // The function returns false when a null pointer is passed or when - // clamping happened (i.e. when the end of the destination buffer is - // reached but the source has some characters left). - inline bool strcpy_with_clamp(char* const dst, size_t const dst_size_in_bytes, const char* const src, size_t const src_size_in_bytes = (size_t)-1) - { - if (!dst || dst_size_in_bytes < sizeof(char)) - { - return false; - } - - if (!src || src_size_in_bytes < sizeof(char)) - { - dst[0] = 0; - return src != 0; // we return true for non-null src without characters - } - - const size_t src_n = src_size_in_bytes; - const size_t n = (std::min)(dst_size_in_bytes - 1, src_n); - - for (size_t i = 0; i < n; ++i) - { - dst[i] = src[i]; - if (!src[i]) - { - return true; - } - } - - dst[n] = 0; - return n >= src_n || src[n] == 0; - } - - - template - class CBuffer - { - public: - typedef T element_type; - - private: - element_type* m_ptr; - size_t m_sizeInBytes; - - public: - CBuffer(element_type* ptr, size_t sizeInBytes) - : m_ptr(ptr) - , m_sizeInBytes(ptr ? sizeInBytes : 0) - { - } - - const element_type* getPtr() const - { - return m_ptr; - } - - element_type* getPtr() - { - return m_ptr; - } - - size_t getSizeInElements() const - { - return m_sizeInBytes / sizeof(element_type); - } - - size_t getSizeInBytes() const - { - return m_sizeInBytes; - } - - const element_type& operator[](size_t pos) const - { - return m_ptr[pos]; - } - - element_type& operator[](size_t pos) - { - return m_ptr[pos]; - } - }; - - typedef CBuffer CCharBuffer; - typedef CBuffer CWCharBuffer; - - - template - class CFixedString - { - public: - typedef T char_type; - static const size_t npos = ~size_t(0); - private: - size_t m_count; // # chars (not counting trailing zero) - char_type m_buffer[CAPACITY + 1]; // '+ 1' is for trailing zero - - public: - CFixedString() - { - clear(); - } - - CFixedString(const char_type* p) - { - set(p); - } - - CFixedString& operator=(const char_type* p) - { - set(p); - return *this; - } - - CFixedString& operator=(const CFixedString& s) - { - if (&s != this) - { - set(s.m_buffer, s.m_count); - } - return *this; - } - - CBuffer getBuffer() - { - return CBuffer(m_buffer, (CAPACITY + 1) * sizeof(char_type)); - } - - char_type operator[](const size_t i) const - { - return m_buffer[i]; - } - - const char_type* c_str() const - { - return &m_buffer[0]; - } - - const size_t length() const - { - return m_count; - } - - void clear() - { - m_count = 0; - m_buffer[m_count] = 0; - } - - void setLength(size_t n) - { - m_count = (n <= CAPACITY) ? n : CAPACITY; - m_buffer[m_count] = 0; - } - - char_type* ptr() - { - return &m_buffer[0]; - } - - CFixedString substr(size_t pos = 0, size_t n = npos) const - { - CFixedString s; - if (pos < m_count && n > 0) - { - if (n > m_count || pos + n > m_count) - { - n = m_count - pos; - } - s.set(&m_buffer[pos], n); - } - return s; - } - - void set(const char_type* p, size_t n) - { - if (p == 0 || n <= 0) - { - m_count = 0; - } - else - { - m_count = (n > CAPACITY) ? CAPACITY : n; - // memmove() is used because p may point to m_buffer - memmove(m_buffer, p, m_count * sizeof(*p)); - } - m_buffer[m_count] = 0; - } - - void set(const char_type* p) - { - if (p && p[0]) - { - set(p, Utils::strlen(p)); - } - else - { - clear(); - } - } - - void append(const char_type* p, size_t n) - { - if (p && n > 0) - { - if (n > CAPACITY || m_count + n > CAPACITY) - { - // assert(0); - n = CAPACITY - m_count; - } - if (n > 0) - { - memcpy(&m_buffer[m_count], p, n * sizeof(*p)); - m_count += n; - m_buffer[m_count] = 0; - } - } - } - - void append(const char_type* p) - { - if (p && p[0]) - { - append(p, Utils::strlen(p)); - } - } - - void appendAscii(const char* p, size_t n) - { - if (p && n > 0) - { - if (n > CAPACITY || m_count + n > CAPACITY) - { - // assert(0); - n = CAPACITY - m_count; - } - if (n > 0) - { - for (size_t i = 0; i < n; ++i) - { - m_buffer[m_count + i] = p[i]; - } - m_count += n; - m_buffer[m_count] = 0; - } - } - } - - void appendAscii(const char* p) - { - if (p && p[0]) - { - appendAscii(p, Utils::strlen(p)); - } - } - - bool equals(const char_type* p) const - { - return (p == 0 || p[0] == 0) - ? (m_count == 0) - : (Utils::strcmp(m_buffer, p) == 0); - } - - void trim() - { - size_t begin = 0; - while (begin < m_count && (m_buffer[begin] == ' ' || m_buffer[begin] == '\r' || m_buffer[begin] == '\t' || m_buffer[begin] == '\n')) - { - ++begin; - } - - if (begin >= m_count) - { - clear(); - return; - } - - size_t end = m_count - 1; - while (end > begin && (m_buffer[begin] == ' ' || m_buffer[begin] == '\r' || m_buffer[begin] == '\t' || m_buffer[begin] == '\n')) - { - --end; - } - - m_count = end + 1; - m_buffer[m_count] = 0; - - if (begin > 0) - { - set(&m_buffer[begin], m_count - begin); - } - } - }; - - - struct SKeyValue - { - CFixedString key; - CFixedString value; - }; - - - template - class CKeyValueArray - { - private: - size_t count; - SKeyValue data[CAPACITY]; - - public: - CKeyValueArray() - : count(0) - { - } - - size_t size() const - { - return count; - } - - const SKeyValue& operator[](size_t i) const - { - return data[i]; - } - - void clear() - { - count = 0; - } - - const SKeyValue* find(const char* key) const - { - for (size_t i = 0; i < count; ++i) - { - if (data[i].key.equals(key)) - { - return &data[i]; - } - } - return 0; - } - - SKeyValue* find(const char* key) - { - for (size_t i = 0; i < count; ++i) - { - if (data[i].key.equals(key)) - { - return &data[i]; - } - } - return 0; - } - - SKeyValue* set(const char* key, const wchar_t* value) - { - SKeyValue* p = find(key); - if (!p) - { - if (count >= CAPACITY) - { - return 0; - } - p = &data[count++]; - p->key = key; - } - p->value = value; - return p; - } - }; - - -#if defined(CRY_ENABLE_RC_HELPER) - - bool Utf16ContainsAsciiOnly(const wchar_t* wstr); - - void ConvertUtf16ToUtf8(const wchar_t* src, CCharBuffer dst); - - void ConvertUtf8ToUtf16(const char* src, CWCharBuffer dst); - - template - void AddPathSeparator(CFixedString& wstr) - { - if (wstr.length() <= 0) - { - return; - } - - if (wstr[wstr.length() - 1] == L'/' || wstr[wstr.length() - 1] == L'\\') - { - return; - } - - wstr.appendAscii("/"); - } - - void GetAsciiFilename(const wchar_t* wfilename, CCharBuffer buffer); - -#endif // #if defined(CRY_ENABLE_RC_HELPER) -} // namespace SettingsManagerHelpers - - -#if defined(CRY_ENABLE_RC_HELPER) - -////////////////////////////////////////////////////////////////////////// -// Provides settings and functions to make calls to RC. -class CEngineSettingsManager; -class CSettingsManagerTools -{ -public: - CSettingsManagerTools(const wchar_t* szModuleName = 0); - ~CSettingsManagerTools(); - -private: - CEngineSettingsManager* m_pSettingsManager; - -public: - CEngineSettingsManager* GetEngineSettingsManager() - { - return m_pSettingsManager; - } - - bool GetInstalledBuildPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path); - bool GetInstalledBuildPathAscii(const int index, SettingsManagerHelpers::CCharBuffer name, SettingsManagerHelpers::CCharBuffer path); - - void GetEditorExecutable(SettingsManagerHelpers::CWCharBuffer wbuffer); - bool CallEditor(void** pEditorWindow, void* hParent, const char* pWndName, const char* pFlag); - - static bool Is64bitWindows(); -}; - -#endif // #if defined(CRY_ENABLE_RC_HELPER) - -#endif // CRYINCLUDE_CRYCOMMON_SETTINGSMANAGERHELPERS_H diff --git a/Code/CryEngine/CryCommon/crycommon_enginesettings_files.cmake b/Code/CryEngine/CryCommon/crycommon_enginesettings_files.cmake deleted file mode 100644 index 0fbd223d21..0000000000 --- a/Code/CryEngine/CryCommon/crycommon_enginesettings_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 - ProjectDefines.h - SettingsManagerHelpers.cpp - SettingsManagerHelpers.h - EngineSettingsManager.cpp - EngineSettingsManager.h - EngineSettingsBackend.cpp - EngineSettingsBackend.h - ResourceCompilerHelper.cpp - ResourceCompilerHelper.h -) - -# Remove files that cause #define collisions on Mac due to multiple inclusions of 'AppleSpecific.h' and include orders -set(SKIP_UNITY_BUILD_INCLUSION_FILES - SettingsManagerHelpers.cpp -) diff --git a/Code/CryEngine/CryCommon/crycommon_files.cmake b/Code/CryEngine/CryCommon/crycommon_files.cmake index ca95802fd9..77b51825f1 100644 --- a/Code/CryEngine/CryCommon/crycommon_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_files.cmake @@ -22,7 +22,6 @@ set(FILES IConsole.h IEntityRenderState.h IEntityRenderState_info.cpp - IFlares.h IFont.h IFunctorBase.h IFuncVariable.h @@ -40,12 +39,10 @@ set(FILES ILog.h ILZ4Decompressor.h IMaterial.h - IMaterialEffects.h IMemory.h IMeshBaking.h IMiniLog.h IMovieSystem.h - INotificationNetwork.h IPhysics.h IPhysicsDebugRenderer.h IPostEffectGroup.h @@ -55,12 +52,10 @@ set(FILES IRenderer.h IRenderMesh.h IResourceCollector.h - IResourceCompilerHelper.h IResourceManager.h ISerialize.h IShader.h IShader_info.h - ISoftCodeMgr.h ISplines.h IStatObj.h StatObjBus.h @@ -69,11 +64,8 @@ set(FILES IStreamEngineDefs.h ISurfaceType.h ISystem.h - ISystemScheduler.h ITextModeConsole.h ITexture.h - IThreadManager.h - IThreadTask.h ITimer.h IValidator.h IVideoRenderer.h @@ -108,7 +100,6 @@ set(FILES MaterialUtils.h MTPseudoRandom.cpp CryTypeInfo.cpp - IResourceCompilerHelper.cpp BaseTypes.h CompileTimeAssert.h CryThreadSafeWorkerContainer.h @@ -170,7 +161,6 @@ set(FILES PoolAllocator.h primitives.h primitives_info.h - ProfileLog.h ProjectDefines.h Range.h RenderContextConfig.h diff --git a/Code/CryEngine/CryCommon/physinterface.h b/Code/CryEngine/CryCommon/physinterface.h index 036f7e29ab..dd787d48b7 100644 --- a/Code/CryEngine/CryCommon/physinterface.h +++ b/Code/CryEngine/CryCommon/physinterface.h @@ -3244,7 +3244,6 @@ struct PhysicsVars int nBodiesLargeGroup; int bBreakOnValidation; int bLogActiveObjects; - int bMultiplayer; int bProfileEntities; int bProfileFunx; int bProfileGroups; diff --git a/Code/CryEngine/CryCommon/platform_impl.cpp b/Code/CryEngine/CryCommon/platform_impl.cpp index 142f07e5e7..885ea2984d 100644 --- a/Code/CryEngine/CryCommon/platform_impl.cpp +++ b/Code/CryEngine/CryCommon/platform_impl.cpp @@ -33,7 +33,7 @@ #define PLATFORM_IMPL_H_SECTION_VIRTUAL_ALLOCATORS 7 #endif -SC_API struct SSystemGlobalEnvironment* gEnv = nullptr; +struct SSystemGlobalEnvironment* gEnv = nullptr; // Traits #if defined(AZ_RESTRICTED_PLATFORM) @@ -147,7 +147,6 @@ void* GetDetachEnvironmentSymbol() #endif // !defined(SOFTCODE) bool g_bProfilerEnabled = false; -int g_iTraceAllocations = 0; ////////////////////////////////////////////////////////////////////////// // global random number generator used by cry_random functions diff --git a/Code/CryEngine/CrySystem/AutoDetectSpec.cpp b/Code/CryEngine/CrySystem/AutoDetectSpec.cpp index 31eee85d90..aa344684e3 100644 --- a/Code/CryEngine/CrySystem/AutoDetectSpec.cpp +++ b/Code/CryEngine/CrySystem/AutoDetectSpec.cpp @@ -1044,11 +1044,9 @@ void CSystem::AutoDetectSpec(const bool detectResolution) unsigned int numSysCores(1), numProcCores(1); Win32SysInspect::GetNumCPUCores(numSysCores, numProcCores); CryLogAlways("--- Number of available cores: %d (out of %d)", numProcCores, numSysCores); - const int numLogicalProcs = gEnv->pi.numLogicalProcessors; - CryLogAlways("--- Number of logical processors: %d", numLogicalProcs); // get CPU rating - const int cpuRating = numLogicalProcs >= 8 ? 3 : (numLogicalProcs >= 6 ? 2 : 1); + const int cpuRating = numProcCores >= 4 ? 3 : (numProcCores >= 3 ? 2 : 1); // get GPU info unsigned int gpuVendorId(0), gpuDeviceId(0), totVidMem(0); diff --git a/Code/CryEngine/CrySystem/CMakeLists.txt b/Code/CryEngine/CrySystem/CMakeLists.txt index 1a5593e5d8..3261526e8e 100644 --- a/Code/CryEngine/CrySystem/CMakeLists.txt +++ b/Code/CryEngine/CrySystem/CMakeLists.txt @@ -89,7 +89,6 @@ ly_add_target( Legacy::CrySystem.Static AZ::AzCore Legacy::CryCommon - Legacy::CryCommon.EngineSettings.Static ) ################################################################################ @@ -109,7 +108,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) PRIVATE AZ::AzTest Legacy::CryCommon - Legacy::CryCommon.EngineSettings.Static Legacy::CrySystem.Static AZ::AzFramework ) diff --git a/Code/CryEngine/CrySystem/ConsoleBatchFile.cpp b/Code/CryEngine/CrySystem/ConsoleBatchFile.cpp index 946edb9b64..b6eced4df3 100644 --- a/Code/CryEngine/CrySystem/ConsoleBatchFile.cpp +++ b/Code/CryEngine/CrySystem/ConsoleBatchFile.cpp @@ -87,14 +87,6 @@ bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) filename = PathUtil::ReplaceExtension(filename, "cfg"); } -#if defined(CVARS_WHITELIST) - bool ignoreWhitelist = true; - if (_stricmp(sFilename, "autoexec.cfg") == 0) - { - ignoreWhitelist = false; - } -#endif // defined(CVARS_WHITELIST) - ////////////////////////////////////////////////////////////////////////// CCryFile file; @@ -179,18 +171,9 @@ bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) continue; } -#if defined(CVARS_WHITELIST) - if (ignoreWhitelist || (gEnv->pSystem->GetCVarsWhiteList() && gEnv->pSystem->GetCVarsWhiteList()->IsWhiteListed(strLine, false))) -#endif // defined(CVARS_WHITELIST) { m_pConsole->ExecuteString(strLine); } -#if defined(CVARS_WHITELIST) - else if (gEnv->IsDedicated()) - { - gEnv->pSystem->GetILog()->LogError("Failed to execute command: '%s' as it is not whitelisted\n", strLine.c_str()); - } -#endif // defined(CVARS_WHITELIST) } // See above // ((CXConsole*)m_pConsole)->SetStatus(bConsoleStatus); diff --git a/Code/CryEngine/CrySystem/CrySystem_precompiled.h b/Code/CryEngine/CrySystem/CrySystem_precompiled.h index b446199b4e..1fab2d4ce1 100644 --- a/Code/CryEngine/CrySystem/CrySystem_precompiled.h +++ b/Code/CryEngine/CrySystem/CrySystem_precompiled.h @@ -117,7 +117,6 @@ struct IRenderer; struct ISystem; struct ITimer; struct IFFont; -struct IKeyboard; struct ICVar; struct IConsole; struct IProcess; diff --git a/Code/CryEngine/CrySystem/CryThreadUtil_pthread.h b/Code/CryEngine/CrySystem/CryThreadUtil_pthread.h deleted file mode 100644 index 4c920898f0..0000000000 --- a/Code/CryEngine/CrySystem/CryThreadUtil_pthread.h +++ /dev/null @@ -1,259 +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. - -////////////////////////////////////////////////////////////////////////// -// NOTE: INTERNAL HEADER NOT FOR PUBLIC USE -// This header should only be include by SystemThreading.cpp only -// It provides an interface for PThread intrinsics -// It's only client should be CThreadManager which should manage all thread interaction -#if !defined(INCLUDED_FROM_SYSTEM_THREADING_CPP) -# error "CRYTEK INTERNAL HEADER. ONLY INCLUDE FROM SYSTEMTHRADING.CPP." -#endif -////////////////////////////////////////////////////////////////////////// - -#define DEFAULT_THREAD_STACK_SIZE_KB 0 -#define CRY_PTHREAD_THREAD_NAME_MAX 16 - -////////////////////////////////////////////////////////////////////////// -// THREAD CREATION AND MANAGMENT -////////////////////////////////////////////////////////////////////////// -namespace CryThreadUtil -{ - // Define type for platform specific thread handle - typedef pthread_t TThreadHandle; - - struct SThreadCreationDesc - { - // Define platform specific thread entry function functor type - typedef void* (* EntryFunc)(void*); - - const char* szThreadName; - EntryFunc fpEntryFunc; - void* pArgList; - uint32 nStackSizeInBytes; - }; - - ////////////////////////////////////////////////////////////////////////// - TThreadHandle CryGetCurrentThreadHandle() - { - return (TThreadHandle)pthread_self(); - } - - ////////////////////////////////////////////////////////////////////////// - // Note: Handle must be closed lated via CryCloseThreadHandle() - TThreadHandle CryDuplicateThreadHandle(const TThreadHandle& hThreadHandle) - { - // Do not do anything - // If you add a new platform which duplicates handles make sure to mirror the change in CryCloseThreadHandle(..) - return hThreadHandle; - } - - ////////////////////////////////////////////////////////////////////////// - void CryCloseThreadHandle(TThreadHandle& hThreadHandle) - { - pthread_detach(hThreadHandle); - } - - ////////////////////////////////////////////////////////////////////////// - threadID CryGetCurrentThreadId() - { - return threadID(pthread_self()); - } - - ////////////////////////////////////////////////////////////////////////// - threadID CryGetThreadId(TThreadHandle hThreadHandle) - { - return threadID(hThreadHandle); - } - - ////////////////////////////////////////////////////////////////////////// - // Note: On OSX the thread name can only be set by the thread itself. - void CrySetThreadName(TThreadHandle pThreadHandle, const char* sThreadName) - { - char threadName[CRY_PTHREAD_THREAD_NAME_MAX]; - if (!cry_strcpy(threadName, sThreadName)) - { - CryLog(" CrySetThreadName: input thread name '%s' truncated to '%s'", sThreadName, threadName); - } -#if AZ_TRAIT_OS_PLATFORM_APPLE - // On OSX the thread name can only be set by the thread itself. - assert(pthread_equal(pthread_self(), (pthread_t )pThreadHandle)); - - if (pthread_setname_np(threadName) != 0) -#else - if (pthread_setname_np(pThreadHandle, threadName) != 0) -#endif - { - switch (errno) - { - case ERANGE: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadName: Unable to rename thread \"%s\". Error Msg: \"Name to long. Exceeds %d bytes.\"", sThreadName, CRY_PTHREAD_THREAD_NAME_MAX); - break; - default: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadName: Unsupported error code: %i", errno); - break; - } - } - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadAffinityMask(TThreadHandle pThreadHandle, DWORD dwAffinityMask) - { -#if defined(AZ_PLATFORM_ANDROID) - // Not supported on ANDROID - // Alternative solution - // Watch out that android will clear the mask after a core has been switched off hence loosing the affinity mask setting! - // http://stackoverflow.com/questions/16319725/android-set-thread-affinity -#elif AZ_TRAIT_OS_PLATFORM_APPLE -# pragma message "Warning: CrySetThreadAffinityMask not implemented for platform" - // Implementation details can be found here - // https://developer.apple.com/library/mac/releasenotes/Performance/RN-AffinityAPI/ -#else - cpu_set_t cpu_mask; - CPU_ZERO(&cpu_mask); - for (int cpu = 0; cpu < sizeof(cpu_mask) * 8; ++cpu) - { - if (dwAffinityMask & (1 << cpu)) - { - CPU_SET(cpu, &cpu_mask); - } - } - - if (sched_setaffinity(0, sizeof(cpu_mask), &cpu_mask) != 0) - { - switch (errno) - { - case EFAULT: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadAffinityMask: Supplied memory address was invalid."); - break; - case EINVAL: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadAffinityMask: The affinity bit mask [%u] contains no processors that are currently physically on the system and permitted to the process .", dwAffinityMask); - break; - case EPERM: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadAffinityMask: The calling process does not have appropriate privileges. Mask [%u].", dwAffinityMask); - break; - case ESRCH: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadAffinityMask: The process whose ID is pid could not be found."); - break; - default: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadAffinityMask: Unsupported error code: %i", errno); - break; - } - } -#endif - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadPriority(TThreadHandle pThreadHandle, DWORD dwPriority) - { - int policy; - struct sched_param param; - - pthread_getschedparam(pThreadHandle, &policy, ¶m); - param.sched_priority = sched_get_priority_max(dwPriority); - pthread_setschedparam(pThreadHandle, policy, ¶m); - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadPriorityBoost(TThreadHandle pThreadHandle, bool bEnabled) - { - // Not supported - } - - ////////////////////////////////////////////////////////////////////////// - bool CryCreateThread(TThreadHandle* pThreadHandle, const SThreadCreationDesc& threadDesc) - { - uint32 nStackSize = threadDesc.nStackSizeInBytes != 0 ? threadDesc.nStackSizeInBytes : DEFAULT_THREAD_STACK_SIZE_KB * 1024; - - assert(pThreadHandle != reinterpret_cast(THREADID_NULL)); - pthread_attr_t threadAttr; - sched_param schedParam; - pthread_attr_init(&threadAttr); - pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_JOINABLE); - pthread_attr_setstacksize(&threadAttr, nStackSize); - - const int err = pthread_create( - pThreadHandle, - &threadAttr, - threadDesc.fpEntryFunc, - threadDesc.pArgList); - - // Handle error on thread creation - switch (err) - { - case 0: - // No error - break; - case EAGAIN: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to create thread \"%s\". Error Msg: \"Insufficient resources to create another thread, or a system-imposed limit on the number of threads was encountered.\"", threadDesc.szThreadName); - return false; - case EINVAL: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to create thread \"%s\". Error Msg: \"Invalid attribute setting for thread creation.\"", threadDesc.szThreadName); - return false; - case EPERM: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to create thread \"%s\". Error Msg: \"No permission to set the scheduling policy and parameters specified in attribute setting\"", threadDesc.szThreadName); - return false; - default: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to create thread \"%s\". Unknown error message. Error code %i", threadDesc.szThreadName, err); - break; - } - - // Print info to log - CryComment(": New thread \"%s\" | StackSize: %u(KB)", threadDesc.szThreadName, threadDesc.nStackSizeInBytes / 1024); - return true; - } - - ////////////////////////////////////////////////////////////////////////// - void CryThreadExitCall() - { - // Notes on: pthread_exit - // A thread that was create with pthread_create implicitly calls pthread_exit when the thread returns from its start routine (the function that was first called after a thread was created). - // pthread_exit(NULL); - } -} - - -////////////////////////////////////////////////////////////////////////// -// FLOATING POINT EXCEPTIONS -////////////////////////////////////////////////////////////////////////// -namespace CryThreadUtil -{ - /////////////////////////////////////////////////////////////////////////// - void EnableFloatExceptions(EFPE_Severity eFPESeverity) - { - // TODO: - // Not implemented - // for potential implementation see http://linux.die.net/man/3/feenableexcept - } - - ////////////////////////////////////////////////////////////////////////// - void EnableFloatExceptions(threadID nThreadId, EFPE_Severity eFPESeverity) - { - // TODO: - // Not implemented - // for potential implementation see http://linux.die.net/man/3/feenableexcept - } - - ////////////////////////////////////////////////////////////////////////// - uint GetFloatingPointExceptionMask() - { - // Not implemented - return ~0; - } - - ////////////////////////////////////////////////////////////////////////// - void SetFloatingPointExceptionMask(uint nMask) - { - // Not implemented - } -} diff --git a/Code/CryEngine/CrySystem/CryThreadUtil_win32_thread.h b/Code/CryEngine/CrySystem/CryThreadUtil_win32_thread.h deleted file mode 100644 index e5c7510feb..0000000000 --- a/Code/CryEngine/CrySystem/CryThreadUtil_win32_thread.h +++ /dev/null @@ -1,432 +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. - -////////////////////////////////////////////////////////////////////////// -// NOTE: INTERNAL HEADER NOT FOR PUBLIC USE -// This header should only be include by SystemThreading.cpp only -// It provides an interface for WinApi intrinsics -// It's only client should be CThreadManager which should manage all thread interaction - -#pragma once - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define CRYTHREADUTIL_WIN32_THREAD_H_SECTION_1 1 -#define CRYTHREADUTIL_WIN32_THREAD_H_SECTION_2 2 -#endif - -#if !defined(INCLUDED_FROM_SYSTEM_THREADING_CPP) -# error "CRYTEK INTERNAL HEADER. ONLY INCLUDE FROM SYSTEMTHRADING.CPP." -#endif -////////////////////////////////////////////////////////////////////////// - -#define DEFAULT_THREAD_STACK_SIZE_KB 0 - -// Returns the last Win32 error, in string format. Returns an empty string if there is no error. -static string GetLastErrorAsString() -{ - // Get the error message, if any. - DWORD errorMessageID = GetLastError(); - if (errorMessageID == 0) - { - return ""; - } - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION CRYTHREADUTIL_WIN32_THREAD_H_SECTION_1 -#include AZ_RESTRICTED_FILE(CryThreadUtil_win32_thread_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - LPSTR messageBuffer = nullptr; - size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), messageBuffer, 0, NULL); - - string message(messageBuffer, size); - - // Free the buffer. - LocalFree(messageBuffer); - - return message; -#endif -} - -////////////////////////////////////////////////////////////////////////// -// THREAD CREATION AND MANAGMENT -////////////////////////////////////////////////////////////////////////// -namespace CryThreadUtil -{ - // Define type for platform specific thread handle - typedef THREAD_HANDLE TThreadHandle; - - struct SThreadCreationDesc - { - // Define platform specific thread entry function functor type - typedef unsigned int(_stdcall * EntryFunc)(void*); - - const char* szThreadName; - EntryFunc fpEntryFunc; - void* pArgList; - uint32 nStackSizeInBytes; - }; - - ////////////////////////////////////////////////////////////////////////// - TThreadHandle CryGetCurrentThreadHandle() - { - return GetCurrentThread(); // most likely returns pseudo handle (0xfffffffe) - } - - ////////////////////////////////////////////////////////////////////////// - // Note: Handle must be closed lated via CryCloseThreadHandle() - TThreadHandle CryDuplicateThreadHandle(const TThreadHandle& hThreadHandle) - { - // NOTES: - // GetCurrentThread() may return a psydo handle to the current thread - // to avoid going into the slower kernel mode. - // Hence the handle is useless when being used from an other thread. - // - GetCurrentThread() -> 0xfffffffe - // - GetCurrentProcess() -> 0xffffffff - - HANDLE hRealHandle = 0; - DuplicateHandle(GetCurrentProcess(), // Source Process Handle. - hThreadHandle, // Source Handle to dup. - GetCurrentProcess(), // Target Process Handle. - &hRealHandle, // Target Handle pointer. - 0, // Options flag. - TRUE, // Inheritable flag - DUPLICATE_SAME_ACCESS); // Options - - return (TThreadHandle)hRealHandle; - } - - ////////////////////////////////////////////////////////////////////////// - void CryCloseThreadHandle(TThreadHandle& hThreadHandle) - { - if (hThreadHandle) - { - CloseHandle(hThreadHandle); - } - } - - ////////////////////////////////////////////////////////////////////////// - threadID CryGetCurrentThreadId() - { - return GetCurrentThreadId(); - } - - ////////////////////////////////////////////////////////////////////////// - threadID CryGetThreadId(TThreadHandle hThreadHandle) - { - return GetThreadId(hThreadHandle); - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadName(TThreadHandle pThreadHandle, const char* sThreadName) - { - const DWORD MS_VC_EXCEPTION = 0x406D1388; - - struct SThreadNameDesc - { - DWORD dwType; // Must be 0x1000. - LPCSTR szName; // Pointer to name (in user addr space). - DWORD dwThreadID; // Thread ID (-1=caller thread). - DWORD dwFlags; // Reserved for future use, must be zero. - }; - - SThreadNameDesc info; - info.dwType = 0x1000; - info.szName = sThreadName; - info.dwThreadID = GetThreadId(pThreadHandle); - info.dwFlags = 0; -AZ_PUSH_DISABLE_WARNING(6312 6322, "-Wunknown-warning-option") - // warning C6312: Possible infinite loop: use of the constant EXCEPTION_CONTINUE_EXECUTION in the exception-filter expression of a try-except - // warning C6322: empty _except block - __try - { - // Raise exception to set thread name for attached debugger - RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(DWORD), (ULONG_PTR*)&info); - } - __except (GetExceptionCode() == MS_VC_EXCEPTION ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER) - { - } -AZ_POP_DISABLE_WARNING - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadAffinityMask(TThreadHandle pThreadHandle, DWORD dwAffinityMask) - { - SetThreadAffinityMask(pThreadHandle, dwAffinityMask); - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadPriority(TThreadHandle pThreadHandle, DWORD dwPriority) - { - if (!SetThreadPriority(pThreadHandle, dwPriority)) - { - string errMsg = GetLastErrorAsString(); - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to set thread priority. System Error Msg: \"%s\"", errMsg.c_str()); - return; - } - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadPriorityBoost(TThreadHandle pThreadHandle, bool bEnabled) - { - SetThreadPriorityBoost(pThreadHandle, !bEnabled); - } - - ////////////////////////////////////////////////////////////////////////// - bool CryCreateThread(TThreadHandle* pThreadHandle, const SThreadCreationDesc& threadDesc) - { - const uint32 nStackSize = threadDesc.nStackSizeInBytes != 0 ? threadDesc.nStackSizeInBytes : DEFAULT_THREAD_STACK_SIZE_KB * 1024; - - // Create thread - unsigned int threadId = 0; -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION CRYTHREADUTIL_WIN32_THREAD_H_SECTION_2 -#include AZ_RESTRICTED_FILE(CryThreadUtil_win32_thread_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - *pThreadHandle = (void*)_beginthreadex(NULL, nStackSize, threadDesc.fpEntryFunc, threadDesc.pArgList, CREATE_SUSPENDED, &threadId); -#endif - - if (!(*pThreadHandle)) - { - string errMsg = GetLastErrorAsString(); - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to create thread \"%s\". System Error Msg: \"%s\"", threadDesc.szThreadName, errMsg.c_str()); - return false; - } - - // Start thread - ResumeThread(*pThreadHandle); - - // Print info to log - CryComment(": New thread \"%s\" | StackSize: %u(KB)", threadDesc.szThreadName, threadDesc.nStackSizeInBytes / 1024); - return true; - } - - ////////////////////////////////////////////////////////////////////////// - void CryThreadExitCall() - { - // Note on: ExitThread() (from MSDN) - // ExitThread is the preferred method of exiting a thread in C code. - // However, in C++ code, the thread is exited before any destructor can be called or any other automatic cleanup can be performed. - // Therefore, in C++ code, you should return from your thread function. - } -} - -////////////////////////////////////////////////////////////////////////// -// FLOATING POINT EXCEPTIONS -////////////////////////////////////////////////////////////////////////// -namespace CryThreadUtil -{ - /////////////////////////////////////////////////////////////////////////// - void EnableFloatExceptions([[maybe_unused]] EFPE_Severity eFPESeverity) - { -AZ_PUSH_DISABLE_WARNING(4996, "-Wunknown-warning-option") - - // Optimization - // Enable DAZ/FZ - // Denormals Are Zeros - // Flush-to-Zero - _controlfp(_DN_FLUSH, _MCW_DN); - _mm_setcsr(_mm_getcsr() | _MM_FLUSH_ZERO_ON); - -#ifndef _RELEASE - if (eFPESeverity == eFPE_None) - { - // mask all floating exceptions off. - _controlfp(_MCW_EM, _MCW_EM); - _mm_setcsr(_mm_getcsr() | _MM_MASK_MASK); - } - else - { - // Clear pending exceptions - _fpreset(); - - if (eFPESeverity == eFPE_Basic) - { - // Enable: - // - _EM_ZERODIVIDE - // - _EM_INVALID - // - // Disable: - // - _EM_DENORMAL - // - _EM_OVERFLOW - // - _EM_UNDERFLOW - // - _EM_INEXACT - - _controlfp(_EM_INEXACT | _EM_DENORMAL | _EM_UNDERFLOW | _EM_OVERFLOW, _MCW_EM); - _mm_setcsr((_mm_getcsr() & ~_MM_MASK_MASK) | (_MM_MASK_DENORM | _MM_MASK_INEXACT | _MM_MASK_UNDERFLOW | _MM_MASK_OVERFLOW)); - - //_mm_setcsr(_mm_getcsr() & ~0x280); - } - - if (eFPESeverity == eFPE_All) - { - // Enable: - // - _EM_ZERODIVIDE - // - _EM_INVALID - // - _EM_UNDERFLOW - // - _EM_OVERFLOW - // - // Disable: - // - _EM_INEXACT - // - _EM_DENORMAL - - _controlfp(_EM_INEXACT | _EM_DENORMAL, _MCW_EM); - _mm_setcsr((_mm_getcsr() & ~_MM_MASK_MASK) | (_MM_MASK_INEXACT | _MM_MASK_DENORM)); - } - } -#endif // _RELEASE - -AZ_POP_DISABLE_WARNING -} - - ////////////////////////////////////////////////////////////////////////// - void EnableFloatExceptions(threadID nThreadId, EFPE_Severity eFPESeverity) - { - if (eFPESeverity >= eFPE_LastEntry) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Floating Point Exception (FPE) severity is out of range. (%i)", eFPESeverity); - } - - // Check if the thread ID matches the current thread - if (nThreadId == 0 || nThreadId == CryGetCurrentThreadId()) - { - EnableFloatExceptions(eFPESeverity); - return; - } - - HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, true, nThreadId); - - if (hThread == 0) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Unable to open thread. %p", hThread); - return; - } - - SuspendThread(hThread); - - CONTEXT ctx; - memset(&ctx, 0, sizeof(ctx)); - ctx.ContextFlags = CONTEXT_ALL; - if (GetThreadContext(hThread, &ctx) == 0) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Unable to get thread context"); - ResumeThread(hThread); - CloseHandle(hThread); - return; - } - -#ifdef PLATFORM_64BIT - ////////////////////////////////////////////////////////////////////////// - // Note: - // DO NOT USE ctx.FltSave.MxCsr ... SetThreadContext() will copy the value of ctx.MxCsr into it - ////////////////////////////////////////////////////////////////////////// - DWORD& floatMxCsr = ctx.MxCsr; // Hold FPE Mask and Status for MMX (SSE) floating point registers - WORD& floatControlWord = ctx.FltSave.ControlWord; // Hold FPE Mask for floating point registers - #ifndef _RELEASE - WORD& floatStatuslWord = ctx.FltSave.StatusWord; // Holds FPE Status for floating point registers - #endif -#else - DWORD& floatMxCsr = *(DWORD*)(&ctx.ExtendedRegisters[24]); // Hold FPE Mask and Status for MMX (SSE) floating point registers - DWORD& floatControlWord = ctx.FloatSave.ControlWord; // Hold FPE Mask for floating point registers - DWORD& floatStatuslWord = ctx.FloatSave.StatusWord; // Holds FPE Status for floating point registers -#endif - - // Flush-To-Zero Mode - // Two conditions must be met for FTZ processing to occur: - // - The FTZ bit (bit 15) in the MXCSR register must be masked (value = 1). - // - The underflow exception (bit 11) needs to be masked (value = 1). - - // Set flush mode to zero mode - floatControlWord = (floatControlWord & ~_MCW_DN) | _DN_FLUSH; - floatMxCsr = (floatMxCsr & ~_MM_FLUSH_ZERO_MASK) | (_MM_FLUSH_ZERO_ON); - -#ifndef _RELEASE - - // Reset FPE bits - floatControlWord = floatControlWord | _MCW_EM; - floatMxCsr = floatMxCsr | _MM_MASK_MASK; - - // Clear pending exceptions - floatStatuslWord = floatStatuslWord & ~(_SW_INEXACT | _SW_UNDERFLOW | _SW_OVERFLOW | _SW_ZERODIVIDE | _SW_INVALID | _SW_DENORMAL); - floatMxCsr = floatMxCsr & ~(_MM_EXCEPT_INEXACT | _MM_EXCEPT_UNDERFLOW | _MM_EXCEPT_OVERFLOW | _MM_EXCEPT_DIV_ZERO | _MM_EXCEPT_INVALID | _MM_EXCEPT_DENORM); - - if (eFPESeverity == eFPE_Basic) - { - // Enable: - // - _EM_ZERODIVIDE - // - _EM_INVALID - // - // Disable: - // - _EM_DENORMAL - // - _EM_OVERFLOW - // - _EM_UNDERFLOW - // - _EM_INEXACT - - floatControlWord = (floatControlWord & ~_MCW_EM) | (_EM_DENORMAL | _EM_INEXACT | EM_UNDERFLOW | _EM_OVERFLOW); - floatMxCsr = (floatMxCsr & ~_MM_MASK_MASK) | (_MM_MASK_DENORM | _MM_MASK_INEXACT | _MM_MASK_UNDERFLOW | _MM_MASK_OVERFLOW); - } - - if (eFPESeverity == eFPE_All) - { - // Enable: - // - _EM_ZERODIVIDE - // - _EM_INVALID - // - _EM_UNDERFLOW - // - _EM_OVERFLOW - // - // Disable: - // - _EM_INEXACT - // - _EM_DENORMAL - - floatControlWord = (floatControlWord & ~_MCW_EM) | (_EM_INEXACT | _EM_DENORMAL); - floatMxCsr = (floatMxCsr & ~_MM_MASK_MASK) | (_MM_MASK_INEXACT | _MM_MASK_DENORM); - } -#endif - - ctx.ContextFlags = CONTEXT_ALL; - if (SetThreadContext(hThread, &ctx) == 0) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Error setting ThreadContext for ThreadID: %u", nThreadId); - ResumeThread(hThread); - CloseHandle(hThread); - return; - } - - ResumeThread(hThread); - CloseHandle(hThread); - } - - ////////////////////////////////////////////////////////////////////////// - uint GetFloatingPointExceptionMask() - { - uint nMask = 0; - _clearfp(); - _controlfp_s(&nMask, 0, 0); - return nMask; - } - - ////////////////////////////////////////////////////////////////////////// - void SetFloatingPointExceptionMask(uint nMask) - { - uint temp = 0; - _clearfp(); - const unsigned int kAllowedBits = _MCW_DN | _MCW_EM | _MCW_RC; - _controlfp_s(&temp, nMask, kAllowedBits); - } -} diff --git a/Code/CryEngine/CrySystem/DebugCallStack.cpp b/Code/CryEngine/CrySystem/DebugCallStack.cpp deleted file mode 100644 index f33e793db6..0000000000 --- a/Code/CryEngine/CrySystem/DebugCallStack.cpp +++ /dev/null @@ -1,926 +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 "CrySystem_precompiled.h" -#include "DebugCallStack.h" - -#if defined(WIN32) || defined(WIN64) - -#include -#include -#include -#include "System.h" - -#include -#include - -#include "resource.h" -__pragma(comment(lib, "version.lib")) - -//! Needs one external of DLL handle. -extern HMODULE gDLLHandle; - -#include - -#define MAX_PATH_LENGTH 1024 -#define MAX_SYMBOL_LENGTH 512 - -static HWND hwndException = 0; -static bool g_bUserDialog = true; // true=on crash show dialog box, false=supress user interaction - -static int PrintException(EXCEPTION_POINTERS* pex); - -static bool IsFloatingPointException(EXCEPTION_POINTERS* pex); - -extern LONG WINAPI CryEngineExceptionFilterWER(struct _EXCEPTION_POINTERS* pExceptionPointers); -extern LONG WINAPI CryEngineExceptionFilterMiniDump(struct _EXCEPTION_POINTERS* pExceptionPointers, const char* szDumpPath, MINIDUMP_TYPE mdumpValue); - -//============================================================================= -CONTEXT CaptureCurrentContext() -{ - CONTEXT context; - memset(&context, 0, sizeof(context)); - context.ContextFlags = CONTEXT_FULL; - RtlCaptureContext(&context); - - return context; -} - -LONG __stdcall CryUnhandledExceptionHandler(EXCEPTION_POINTERS* pex) -{ - return DebugCallStack::instance()->handleException(pex); -} - - -BOOL CALLBACK EnumModules( - PCSTR ModuleName, - DWORD64 BaseOfDll, - PVOID UserContext) -{ - DebugCallStack::TModules& modules = *static_cast(UserContext); - modules[(void*)BaseOfDll] = ModuleName; - - return TRUE; -} -//============================================================================= -// Class Statics -//============================================================================= - -// Return single instance of class. -IDebugCallStack* IDebugCallStack::instance() -{ - static DebugCallStack sInstance; - return &sInstance; -} - -//------------------------------------------------------------------------------------------------------------------------ -// Sets up the symbols for functions in the debug file. -//------------------------------------------------------------------------------------------------------------------------ -DebugCallStack::DebugCallStack() - : prevExceptionHandler(0) - , m_pSystem(0) - , m_nSkipNumFunctions(0) - , m_bCrash(false) - , m_szBugMessage(NULL) -{ -} - -DebugCallStack::~DebugCallStack() -{ -} - -void DebugCallStack::RemoveOldFiles() -{ - RemoveFile("error.log"); - RemoveFile("error.bmp"); - RemoveFile("error.dmp"); -} - -void DebugCallStack::RemoveFile(const char* szFileName) -{ - FILE* pFile = nullptr; - azfopen(&pFile, szFileName, "r"); - const bool bFileExists = (pFile != NULL); - - if (bFileExists) - { - fclose(pFile); - - WriteLineToLog("Removing file \"%s\"...", szFileName); - if (remove(szFileName) == 0) - { - WriteLineToLog("File successfully removed."); - } - else - { - WriteLineToLog("Couldn't remove file!"); - } - } -} - -void DebugCallStack::installErrorHandler(ISystem* pSystem) -{ - m_pSystem = pSystem; - prevExceptionHandler = (void*)SetUnhandledExceptionFilter(CryUnhandledExceptionHandler); -} - -////////////////////////////////////////////////////////////////////////// -void DebugCallStack::SetUserDialogEnable(const bool bUserDialogEnable) -{ - g_bUserDialog = bUserDialogEnable; -} - - -DWORD g_idDebugThreads[10]; -const char* g_nameDebugThreads[10]; -int g_nDebugThreads = 0; -volatile int g_lockThreadDumpList = 0; - -void MarkThisThreadForDebugging(const char* name) -{ - EBUS_EVENT(AZ::Debug::EventTraceDrillerSetupBus, SetThreadName, AZStd::this_thread::get_id(), name); - - WriteLock lock(g_lockThreadDumpList); - DWORD id = GetCurrentThreadId(); - if (g_nDebugThreads == sizeof(g_idDebugThreads) / sizeof(g_idDebugThreads[0])) - { - return; - } - for (int i = 0; i < g_nDebugThreads; i++) - { - if (g_idDebugThreads[i] == id) - { - return; - } - } - g_nameDebugThreads[g_nDebugThreads] = name; - g_idDebugThreads[g_nDebugThreads++] = id; - ((CSystem*)gEnv->pSystem)->EnableFloatExceptions(g_cvars.sys_float_exceptions); -} - -void UnmarkThisThreadFromDebugging() -{ - WriteLock lock(g_lockThreadDumpList); - DWORD id = GetCurrentThreadId(); - for (int i = g_nDebugThreads - 1; i >= 0; i--) - { - if (g_idDebugThreads[i] == id) - { - memmove(g_idDebugThreads + i, g_idDebugThreads + i + 1, (g_nDebugThreads - 1 - i) * sizeof(g_idDebugThreads[0])); - memmove(g_nameDebugThreads + i, g_nameDebugThreads + i + 1, (g_nDebugThreads - 1 - i) * sizeof(g_nameDebugThreads[0])); - --g_nDebugThreads; - } - } -} - -extern int prev_sys_float_exceptions; -void UpdateFPExceptionsMaskForThreads() -{ - int mask = -iszero(g_cvars.sys_float_exceptions); - CONTEXT ctx; - for (int i = 0; i < g_nDebugThreads; i++) - { - if (g_idDebugThreads[i] != GetCurrentThreadId()) - { - HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, TRUE, g_idDebugThreads[i]); - ctx.ContextFlags = CONTEXT_ALL; - SuspendThread(hThread); - GetThreadContext(hThread, &ctx); -#ifndef WIN64 - (ctx.FloatSave.ControlWord |= 7) &= ~5 | mask; - (*(WORD*)(ctx.ExtendedRegisters + 24) |= 0x280) &= ~0x280 | mask; -#else - (ctx.FltSave.ControlWord |= 7) &= ~5 | mask; - (ctx.FltSave.MxCsr |= 0x280) &= ~0x280 | mask; -#endif - SetThreadContext(hThread, &ctx); - ResumeThread(hThread); - } - } -} - -////////////////////////////////////////////////////////////////////////// -int DebugCallStack::handleException(EXCEPTION_POINTERS* exception_pointer) -{ - if (gEnv == NULL) - { - return EXCEPTION_EXECUTE_HANDLER; - } - - ResetFPU(exception_pointer); - - prev_sys_float_exceptions = 0; - const int cached_sys_float_exceptions = g_cvars.sys_float_exceptions; - - ((CSystem*)gEnv->pSystem)->EnableFloatExceptions(0); - - if (g_cvars.sys_WER) - { - gEnv->pLog->FlushAndClose(); - return CryEngineExceptionFilterWER(exception_pointer); - } - - if (g_cvars.sys_no_crash_dialog) - { - DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX); - SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX); - } - - m_bCrash = true; - - if (g_cvars.sys_no_crash_dialog) - { - DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX); - SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX); - } - - static bool firstTime = true; - - if (g_cvars.sys_dump_aux_threads) - { - for (int i = 0; i < g_nDebugThreads; i++) - { - if (g_idDebugThreads[i] != GetCurrentThreadId()) - { - SuspendThread(OpenThread(THREAD_ALL_ACCESS, TRUE, g_idDebugThreads[i])); - } - } - } - - // uninstall our exception handler. - SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)prevExceptionHandler); - - if (!firstTime) - { - WriteLineToLog("Critical Exception! Called Multiple Times!"); - gEnv->pLog->FlushAndClose(); - // Exception called more then once. - return EXCEPTION_EXECUTE_HANDLER; - } - - // Print exception info: - { - char excCode[80]; - char excAddr[80]; - WriteLineToLog(""); - sprintf_s(excAddr, "0x%04X:0x%p", exception_pointer->ContextRecord->SegCs, exception_pointer->ExceptionRecord->ExceptionAddress); - sprintf_s(excCode, "0x%08X", exception_pointer->ExceptionRecord->ExceptionCode); - WriteLineToLog("Exception: %s, at Address: %s", excCode, excAddr); - - { - IMemoryManager::SProcessMemInfo memInfo; - if (gEnv->pSystem->GetIMemoryManager()->GetProcessMemInfo(memInfo)) - { - uint32 nMemUsage = (uint32)(memInfo.PagefileUsage / (1024 * 1024)); - WriteLineToLog("Virtual memory usage: %dMb", nMemUsage); - } - gEnv->szDebugStatus[SSystemGlobalEnvironment::MAX_DEBUG_STRING_LENGTH - 1] = '\0'; - WriteLineToLog("Debug Status: %s", gEnv->szDebugStatus); - } - } - - firstTime = false; - - const int ret = SubmitBug(exception_pointer); - - if (ret != IDB_IGNORE) - { - CryEngineExceptionFilterWER(exception_pointer); - } - - gEnv->pLog->FlushAndClose(); - - if (exception_pointer->ExceptionRecord->ExceptionFlags & EXCEPTION_NONCONTINUABLE) - { - // This is non continuable exception. abort application now. - exit(exception_pointer->ExceptionRecord->ExceptionCode); - } - - //typedef long (__stdcall *ExceptionFunc)(EXCEPTION_POINTERS*); - //ExceptionFunc prevFunc = (ExceptionFunc)prevExceptionHandler; - //return prevFunc( (EXCEPTION_POINTERS*)exception_pointer ); - if (ret == IDB_EXIT) - { - // Immediate exit. - // on windows, exit() and _exit() do all sorts of things, unfortuantely - // TerminateProcess is the only way to die. - TerminateProcess(GetCurrentProcess(), exception_pointer->ExceptionRecord->ExceptionCode); // we crashed, so don't return a zero exit code! - // on linux based systems, _exit will not call ATEXIT and other things, which makes it more suitable for termination in an emergency such - // as an unhandled exception. - // however, this function is a windows exception handler. - } - else if (ret == IDB_IGNORE) - { -#ifndef WIN64 - exception_pointer->ContextRecord->FloatSave.StatusWord &= ~31; - exception_pointer->ContextRecord->FloatSave.ControlWord |= 7; - (*(WORD*)(exception_pointer->ContextRecord->ExtendedRegisters + 24) &= 31) |= 0x1F80; -#else - exception_pointer->ContextRecord->FltSave.StatusWord &= ~31; - exception_pointer->ContextRecord->FltSave.ControlWord |= 7; - (exception_pointer->ContextRecord->FltSave.MxCsr &= 31) |= 0x1F80; -#endif - firstTime = true; - prevExceptionHandler = (void*)SetUnhandledExceptionFilter(CryUnhandledExceptionHandler); - g_cvars.sys_float_exceptions = cached_sys_float_exceptions; - ((CSystem*)gEnv->pSystem)->EnableFloatExceptions(g_cvars.sys_float_exceptions); - return EXCEPTION_CONTINUE_EXECUTION; - } - - // Continue; - return EXCEPTION_EXECUTE_HANDLER; -} - -void DebugCallStack::ReportBug(const char* szErrorMessage) -{ - WriteLineToLog("Reporting bug: %s", szErrorMessage); - - m_szBugMessage = szErrorMessage; - m_context = CaptureCurrentContext(); - SubmitBug(NULL); - m_szBugMessage = NULL; -} - -void DebugCallStack::dumpCallStack(std::vector& funcs) -{ - WriteLineToLog("============================================================================="); - int len = (int)funcs.size(); - for (int i = 0; i < len; i++) - { - const char* str = funcs[i].c_str(); - WriteLineToLog("%2d) %s", len - i, str); - } - WriteLineToLog("============================================================================="); -} - - -////////////////////////////////////////////////////////////////////////// -void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) -{ - string path(""); - if ((gEnv) && (gEnv->pFileIO)) - { - const char* logAlias = gEnv->pFileIO->GetAlias("@log@"); - if (!logAlias) - { - logAlias = gEnv->pFileIO->GetAlias("@root@"); - } - if (logAlias) - { - path = logAlias; - path += "/"; - } - } - - string fileName = path; - fileName += "error.log"; - - struct stat fileInfo; - string timeStamp; - string backupPath; - if (gEnv->IsDedicated()) - { - backupPath = PathUtil::ToUnixPath(PathUtil::AddSlash(path + "DumpBackups")); - gEnv->pFileIO->CreatePath(backupPath.c_str()); - - if (stat(fileName.c_str(), &fileInfo) == 0) - { - // Backup log - tm creationTime; - localtime_s(&creationTime, &fileInfo.st_mtime); - char tempBuffer[32]; - strftime(tempBuffer, sizeof(tempBuffer), "%d %b %Y (%H %M %S)", &creationTime); - timeStamp = tempBuffer; - - string backupFileName = backupPath + timeStamp + " error.log"; - CopyFile(fileName.c_str(), backupFileName.c_str(), true); - } - } - - FILE* f = nullptr; - azfopen(&f, fileName.c_str(), "wt"); - - CDebugAllowFileAccess ignoreInvalidFileAccess; - - static char errorString[s_iCallStackSize]; - errorString[0] = 0; - - // Time and Version. - char versionbuf[1024]; - azstrcpy(versionbuf, AZ_ARRAY_SIZE(versionbuf), ""); - PutVersion(versionbuf, AZ_ARRAY_SIZE(versionbuf)); - cry_strcat(errorString, versionbuf); - cry_strcat(errorString, "\n"); - - char excCode[MAX_WARNING_LENGTH]; - char excAddr[80]; - char desc[1024]; - char excDesc[MAX_WARNING_LENGTH]; - - // make sure the mouse cursor is visible - ShowCursor(TRUE); - - const char* excName; - if (m_bIsFatalError || !pex) - { - const char* const szMessage = m_bIsFatalError ? s_szFatalErrorCode : m_szBugMessage; - excName = szMessage; - cry_strcpy(excCode, szMessage); - cry_strcpy(excAddr, ""); - cry_strcpy(desc, ""); - cry_strcpy(m_excModule, ""); - cry_strcpy(excDesc, szMessage); - } - else - { - sprintf_s(excAddr, "0x%04X:0x%p", pex->ContextRecord->SegCs, pex->ExceptionRecord->ExceptionAddress); - sprintf_s(excCode, "0x%08X", pex->ExceptionRecord->ExceptionCode); - excName = TranslateExceptionCode(pex->ExceptionRecord->ExceptionCode); - cry_strcpy(desc, ""); - sprintf_s(excDesc, "%s\r\n%s", excName, desc); - - - if (pex->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) - { - if (pex->ExceptionRecord->NumberParameters > 1) - { - ULONG_PTR iswrite = pex->ExceptionRecord->ExceptionInformation[0]; - DWORD64 accessAddr = pex->ExceptionRecord->ExceptionInformation[1]; - if (iswrite) - { - sprintf_s(desc, "Attempt to write data to address 0x%08llu\r\nThe memory could not be \"written\"", accessAddr); - } - else - { - sprintf_s(desc, "Attempt to read from address 0x%08llu\r\nThe memory could not be \"read\"", accessAddr); - } - } - } - } - - - WriteLineToLog("Exception Code: %s", excCode); - WriteLineToLog("Exception Addr: %s", excAddr); - WriteLineToLog("Exception Module: %s", m_excModule); - WriteLineToLog("Exception Name : %s", excName); - WriteLineToLog("Exception Description: %s", desc); - - - cry_strcpy(m_excDesc, excDesc); - cry_strcpy(m_excAddr, excAddr); - cry_strcpy(m_excCode, excCode); - - - char errs[32768]; - sprintf_s(errs, "Exception Code: %s\nException Addr: %s\nException Module: %s\nException Description: %s, %s\n", - excCode, excAddr, m_excModule, excName, desc); - - - IMemoryManager::SProcessMemInfo memInfo; - if (gEnv->pSystem->GetIMemoryManager()->GetProcessMemInfo(memInfo)) - { - char memoryString[256]; - double MB = 1024 * 1024; - sprintf_s(memoryString, "Memory in use: %3.1fMB\n", (double)(memInfo.PagefileUsage) / MB); - cry_strcat(errs, memoryString); - } - { - const int tempStringSize = 256; - char tempString[tempStringSize]; - - gEnv->szDebugStatus[SSystemGlobalEnvironment::MAX_DEBUG_STRING_LENGTH - 1] = '\0'; - sprintf_s(tempString, tempStringSize, "Debug Status: %s\n", gEnv->szDebugStatus); - cry_strcat(errs, tempString); - - sprintf_s(tempString, tempStringSize, "Out of Memory: %d\n", gEnv->bIsOutOfMemory); - cry_strcat(errs, tempString); - } - cry_strcat(errs, "\nCall Stack Trace:\n"); - - std::vector funcs; - if (gEnv->bIsOutOfMemory) - { - cry_strcat(errs, "1) OUT_OF_MEMORY()\n"); - } - else - { - AZ::Debug::StackFrame frames[25]; - AZ::Debug::SymbolStorage::StackLine lines[AZ_ARRAY_SIZE(frames)]; - unsigned int numFrames = AZ::Debug::StackRecorder::Record(frames, AZ_ARRAY_SIZE(frames), 3); - if (numFrames) - { - AZ::Debug::SymbolStorage::DecodeFrames(frames, numFrames, lines); - for (unsigned int i = 0; i < numFrames; i++) - { - funcs.push_back(lines[i]); - } - } - dumpCallStack(funcs); - // Fill call stack. - char str[s_iCallStackSize]; - cry_strcpy(str, ""); - for (unsigned int i = 0; i < funcs.size(); i++) - { - char temp[s_iCallStackSize]; - sprintf_s(temp, "%2zd) %s", funcs.size() - i, (const char*)funcs[i].c_str()); - cry_strcat(str, temp); - cry_strcat(str, "\r\n"); - cry_strcat(errs, temp); - cry_strcat(errs, "\n"); - } - cry_strcpy(m_excCallstack, str); - } - - cry_strcat(errorString, errs); - - if (f) - { - fwrite(errorString, strlen(errorString), 1, f); - if (!gEnv->bIsOutOfMemory) - { - if (g_cvars.sys_dump_aux_threads) - { - for (int i = 0; i < g_nDebugThreads; i++) - { - if (g_idDebugThreads[i] != GetCurrentThreadId()) - { - fprintf(f, "\n\nSuspended thread (%s):\n", g_nameDebugThreads[i]); - HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, TRUE, g_idDebugThreads[i]); - - // mirrors the AZ::Debug::Trace::PrintCallstack() functionality, but prints to a file - { - AZ::Debug::StackFrame frames[10]; - - // Without StackFrame explicit alignment frames array is aligned to 4 bytes - // which causes the stack tracing to fail. - AZ::Debug::SymbolStorage::StackLine lines[AZ_ARRAY_SIZE(frames)]; - - unsigned int numFrames = AZ::Debug::StackRecorder::Record(frames, AZ_ARRAY_SIZE(frames), 0, hThread); - if (numFrames) - { - AZ::Debug::SymbolStorage::DecodeFrames(frames, numFrames, lines); - for (unsigned int i2 = 0; i2 < numFrames; ++i2) - { - fprintf(f, "%2d) %s\n", numFrames - i2, lines[i2]); - } - } - } - - ResumeThread(hThread); - } - } - } - } - fflush(f); - fclose(f); - } - - if (pex) - { - MINIDUMP_TYPE mdumpValue; - bool bDump = true; - switch (g_cvars.sys_dump_type) - { - case 0: - bDump = false; - break; - case 1: - mdumpValue = MiniDumpNormal; - break; - case 2: - mdumpValue = (MINIDUMP_TYPE)(MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithDataSegs); - break; - case 3: - mdumpValue = MiniDumpWithFullMemory; - break; - default: - mdumpValue = (MINIDUMP_TYPE)g_cvars.sys_dump_type; - break; - } - if (bDump) - { - fileName = path + "error.dmp"; - - if (gEnv->IsDedicated() && stat(fileName.c_str(), &fileInfo) == 0) - { - // Backup dump (use timestamp from error.log if available) - if (timeStamp.empty()) - { - tm creationTime; - localtime_s(&creationTime, &fileInfo.st_mtime); - char tempBuffer[32]; - strftime(tempBuffer, sizeof(tempBuffer), "%d %b %Y (%H %M %S)", &creationTime); - timeStamp = tempBuffer; - } - - string backupFileName = backupPath + timeStamp + " error.dmp"; - CopyFile(fileName.c_str(), backupFileName.c_str(), true); - } - - CryEngineExceptionFilterMiniDump(pex, fileName.c_str(), mdumpValue); - } - } - - //if no crash dialog don't even submit the bug - if (m_postBackupProcess && g_cvars.sys_no_crash_dialog == 0 && g_bUserDialog) - { - m_postBackupProcess(); - } - else - { - // lawsonn: Disabling the JIRA-based crash reporter for now - // we'll need to deal with it our own way, pending QA. - // if you're customizing the engine this is also your opportunity to deal with it. - if (g_cvars.sys_no_crash_dialog != 0 || !g_bUserDialog) - { - // ------------ place custom crash handler here --------------------- - // it should launch an executable! - /// by this time, error.bmp will be in the engine root folder - // error.log and error.dmp will also be present in the engine root folder - // if your error dumper wants those, it should zip them up and send them or offer to do so. - // ------------------------------------------------------------------ - } - } - const bool bQuitting = !gEnv || !gEnv->pSystem || gEnv->pSystem->IsQuitting(); - - //[AlexMcC|16.04.10] When the engine is shutting down, MessageBox doesn't display a box - // and immediately returns IDYES. Avoid this by just not trying to save if we're quitting. - // Don't ask to save if this isn't a real crash (a real crash has exception pointers) - if (g_cvars.sys_no_crash_dialog == 0 && g_bUserDialog && gEnv->IsEditor() && !bQuitting && pex) - { - BackupCurrentLevel(); - - const INT_PTR res = DialogBoxParam(gDLLHandle, MAKEINTRESOURCE(IDD_CONFIRM_SAVE_LEVEL), NULL, DebugCallStack::ConfirmSaveDialogProc, NULL); - if (res == IDB_CONFIRM_SAVE) - { - if (SaveCurrentLevel()) - { - MessageBox(NULL, "Level has been successfully saved!\r\nPress Ok to terminate Editor.", "Save", MB_OK); - } - else - { - MessageBox(NULL, "Error saving level.\r\nPress Ok to terminate Editor.", "Save", MB_OK | MB_ICONWARNING); - } - } - } - - if (g_cvars.sys_no_crash_dialog != 0 || !g_bUserDialog) - { - // terminate immediately - since we're in a crash, there is no point unwinding stack, we've already done access violation or worse. - // calling exit will only cause further death down the line... - TerminateProcess(GetCurrentProcess(), pex->ExceptionRecord->ExceptionCode); - } -} - - -INT_PTR CALLBACK DebugCallStack::ExceptionDialogProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam) -{ - static EXCEPTION_POINTERS* pex; - - static char errorString[32768] = ""; - - switch (message) - { - case WM_INITDIALOG: - { - pex = (EXCEPTION_POINTERS*)lParam; - HWND h; - - if (pex->ExceptionRecord->ExceptionFlags & EXCEPTION_NONCONTINUABLE) - { - // Disable continue button for non continuable exceptions. - //h = GetDlgItem( hwndDlg,IDB_CONTINUE ); - //if (h) EnableWindow( h,FALSE ); - } - - DebugCallStack* pDCS = static_cast(DebugCallStack::instance()); - - h = GetDlgItem(hwndDlg, IDC_EXCEPTION_DESC); - if (h) - { - SendMessage(h, EM_REPLACESEL, FALSE, (LONG_PTR)pDCS->m_excDesc); - } - - h = GetDlgItem(hwndDlg, IDC_EXCEPTION_CODE); - if (h) - { - SendMessage(h, EM_REPLACESEL, FALSE, (LONG_PTR)pDCS->m_excCode); - } - - h = GetDlgItem(hwndDlg, IDC_EXCEPTION_MODULE); - if (h) - { - SendMessage(h, EM_REPLACESEL, FALSE, (LONG_PTR)pDCS->m_excModule); - } - - h = GetDlgItem(hwndDlg, IDC_EXCEPTION_ADDRESS); - if (h) - { - SendMessage(h, EM_REPLACESEL, FALSE, (LONG_PTR)pDCS->m_excAddr); - } - - // Fill call stack. - HWND callStack = GetDlgItem(hwndDlg, IDC_CALLSTACK); - if (callStack) - { - SendMessage(callStack, WM_SETTEXT, FALSE, (LPARAM)pDCS->m_excCallstack); - } - - if (hwndException) - { - DestroyWindow(hwndException); - hwndException = 0; - } - - if (IsFloatingPointException(pex)) - { - EnableWindow(GetDlgItem(hwndDlg, IDB_IGNORE), TRUE); - } - } - break; - - case WM_COMMAND: - switch (LOWORD(wParam)) - { - case IDB_EXIT: - case IDB_IGNORE: - // Fall through. - - EndDialog(hwndDlg, wParam); - return TRUE; - } - } - return FALSE; -} - -INT_PTR CALLBACK DebugCallStack::ConfirmSaveDialogProc(HWND hwndDlg, UINT message, WPARAM wParam, [[maybe_unused]] LPARAM lParam) -{ - switch (message) - { - case WM_INITDIALOG: - { - // The user might be holding down the spacebar while the engine crashes. - // If we don't remove keyboard focus from this dialog, the keypress will - // press the default button before the dialog actually appears, even if - // the user has already released the key, which is bad. - SetFocus(NULL); - } break; - case WM_COMMAND: - { - switch (LOWORD(wParam)) - { - case IDB_CONFIRM_SAVE: // Fall through - case IDB_DONT_SAVE: - { - EndDialog(hwndDlg, wParam); - return TRUE; - } - } - } break; - } - - return FALSE; -} - -bool DebugCallStack::BackupCurrentLevel() -{ - CSystem* pSystem = static_cast(m_pSystem); - if (pSystem && pSystem->GetUserCallback()) - { - return pSystem->GetUserCallback()->OnBackupDocument(); - } - - return false; -} - -bool DebugCallStack::SaveCurrentLevel() -{ - CSystem* pSystem = static_cast(m_pSystem); - if (pSystem && pSystem->GetUserCallback()) - { - return pSystem->GetUserCallback()->OnSaveDocument(); - } - - return false; -} - -int DebugCallStack::SubmitBug(EXCEPTION_POINTERS* exception_pointer) -{ - int ret = IDB_EXIT; - - assert(!hwndException); - - RemoveOldFiles(); - - AZ::Debug::Trace::PrintCallstack("", 2); - - LogExceptionInfo(exception_pointer); - - if (IsFloatingPointException(exception_pointer)) - { - //! Print exception dialog. - ret = PrintException(exception_pointer); - } - - return ret; -} - -void DebugCallStack::ResetFPU(EXCEPTION_POINTERS* pex) -{ - if (IsFloatingPointException(pex)) - { - // How to reset FPU: http://www.experts-exchange.com/Programming/System/Windows__Programming/Q_10310953.html - _clearfp(); -#ifndef WIN64 - pex->ContextRecord->FloatSave.ControlWord |= 0x2F; - pex->ContextRecord->FloatSave.StatusWord &= ~0x8080; -#endif - } -} - -string DebugCallStack::GetModuleNameForAddr(void* addr) -{ - if (m_modules.empty()) - { - return "[unknown]"; - } - - if (addr < m_modules.begin()->first) - { - return "[unknown]"; - } - - TModules::const_iterator it = m_modules.begin(); - TModules::const_iterator end = m_modules.end(); - for (; ++it != end; ) - { - if (addr < it->first) - { - return (--it)->second; - } - } - - //if address is higher than the last module, we simply assume it is in the last module. - return m_modules.rbegin()->second; -} - -void DebugCallStack::GetProcNameForAddr(void* addr, string& procName, void*& baseAddr, string& filename, int& line) -{ - AZ::Debug::SymbolStorage::StackLine func, file, module; - AZ::Debug::SymbolStorage::FindFunctionFromIP(addr, &func, &file, &module, line, baseAddr); - procName = func; - filename = file; -} - -string DebugCallStack::GetCurrentFilename() -{ - char fullpath[MAX_PATH_LENGTH + 1]; - GetModuleFileName(NULL, fullpath, MAX_PATH_LENGTH); - return fullpath; -} - -static bool IsFloatingPointException(EXCEPTION_POINTERS* pex) -{ - if (!pex) - { - return false; - } - - DWORD exceptionCode = pex->ExceptionRecord->ExceptionCode; - switch (exceptionCode) - { - case EXCEPTION_FLT_DENORMAL_OPERAND: - case EXCEPTION_FLT_DIVIDE_BY_ZERO: - case EXCEPTION_FLT_INEXACT_RESULT: - case EXCEPTION_FLT_INVALID_OPERATION: - case EXCEPTION_FLT_OVERFLOW: - case EXCEPTION_FLT_UNDERFLOW: - case STATUS_FLOAT_MULTIPLE_FAULTS: - case STATUS_FLOAT_MULTIPLE_TRAPS: - return true; - - default: - return false; - } -} - -int DebugCallStack::PrintException(EXCEPTION_POINTERS* exception_pointer) -{ - return (int)DialogBoxParam(gDLLHandle, MAKEINTRESOURCE(IDD_CRITICAL_ERROR), NULL, DebugCallStack::ExceptionDialogProc, (LPARAM)exception_pointer); -} - -#else -void MarkThisThreadForDebugging(const char*) {} -void UnmarkThisThreadFromDebugging() {} -void UpdateFPExceptionsMaskForThreads() {} -#endif //WIN32 diff --git a/Code/CryEngine/CrySystem/DebugCallStack.h b/Code/CryEngine/CrySystem/DebugCallStack.h deleted file mode 100644 index c37e6ba0d4..0000000000 --- a/Code/CryEngine/CrySystem/DebugCallStack.h +++ /dev/null @@ -1,95 +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_CRYSYSTEM_DEBUGCALLSTACK_H -#define CRYINCLUDE_CRYSYSTEM_DEBUGCALLSTACK_H -#pragma once - - -#include "IDebugCallStack.h" - -#if defined (WIN32) || defined (WIN64) - -//! Limits the maximal number of functions in call stack. -const int MAX_DEBUG_STACK_ENTRIES_FILE_DUMP = 12; - -struct ISystem; - -//!============================================================================ -//! -//! DebugCallStack class, capture call stack information from symbol files. -//! -//!============================================================================ -class DebugCallStack - : public IDebugCallStack -{ -public: - DebugCallStack(); - virtual ~DebugCallStack(); - - ISystem* GetSystem() { return m_pSystem; }; - - virtual string GetModuleNameForAddr(void* addr); - virtual void GetProcNameForAddr(void* addr, string& procName, void*& baseAddr, string& filename, int& line); - virtual string GetCurrentFilename(); - - void installErrorHandler(ISystem* pSystem); - virtual int handleException(EXCEPTION_POINTERS* exception_pointer); - - virtual void ReportBug(const char*); - - void dumpCallStack(std::vector& functions); - - void SetUserDialogEnable(const bool bUserDialogEnable); - - typedef std::map TModules; -protected: - static void RemoveOldFiles(); - static void RemoveFile(const char* szFileName); - - static int PrintException(EXCEPTION_POINTERS* exception_pointer); - static INT_PTR CALLBACK ExceptionDialogProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam); - static INT_PTR CALLBACK ConfirmSaveDialogProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam); - - void LogExceptionInfo(EXCEPTION_POINTERS* exception_pointer); - bool BackupCurrentLevel(); - bool SaveCurrentLevel(); - int SubmitBug(EXCEPTION_POINTERS* exception_pointer); - void ResetFPU(EXCEPTION_POINTERS* pex); - - static const int s_iCallStackSize = 32768; - - char m_excLine[256]; - char m_excModule[128]; - - char m_excDesc[MAX_WARNING_LENGTH]; - char m_excCode[MAX_WARNING_LENGTH]; - char m_excAddr[80]; - char m_excCallstack[s_iCallStackSize]; - - void* prevExceptionHandler; - - bool m_bCrash; - const char* m_szBugMessage; - - ISystem* m_pSystem; - - int m_nSkipNumFunctions; - CONTEXT m_context; - - TModules m_modules; -}; - -#endif //WIN32 - -#endif // CRYINCLUDE_CRYSYSTEM_DEBUGCALLSTACK_H diff --git a/Code/CryEngine/CrySystem/DllMain.cpp b/Code/CryEngine/CrySystem/DllMain.cpp index 6173ebc0c6..c3a15812ce 100644 --- a/Code/CryEngine/CrySystem/DllMain.cpp +++ b/Code/CryEngine/CrySystem/DllMain.cpp @@ -14,7 +14,6 @@ #include "CrySystem_precompiled.h" #include "System.h" #include -#include "DebugCallStack.h" #if defined(AZ_RESTRICTED_PLATFORM) #undef AZ_RESTRICTED_SECTION @@ -72,10 +71,6 @@ public: { switch (event) { - case ESYSTEM_EVENT_LEVEL_UNLOAD: - gEnv->pSystem->SetThreadState(ESubsys_Physics, false); - break; - case ESYSTEM_EVENT_LEVEL_LOAD_START: case ESYSTEM_EVENT_LEVEL_LOAD_END: { @@ -87,7 +82,6 @@ public: { CryCleanup(); STLALLOCATOR_CLEANUP; - gEnv->pSystem->SetThreadState(ESubsys_Physics, true); break; } } @@ -135,21 +129,6 @@ CRYSYSTEM_API ISystem* CreateSystemInterface(const SSystemInitParams& startupPar startupParams.pUserCallback->OnSystemConnect(pSystem); } - // Environment Variable to signal we don't want to override our exception handler - our crash report system will set this - auto envVar = AZ::Environment::FindVariable("ExceptionHandlerIsSet"); - bool handlerIsSet = (envVar && *envVar); - - if (!startupParams.bMinimal && !handlerIsSet) // in minimal mode, we want to crash when we crash! - { -#if defined(WIN32) - // Install exception handler in Release modes. - ((DebugCallStack*)IDebugCallStack::instance())->installErrorHandler(pSystem); -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION DLLMAIN_CPP_SECTION_3 -#include AZ_RESTRICTED_FILE(DllMain_cpp) -#endif - } - bool retVal = false; { AZ::Debug::StartupLogSinkReporter initLogSink; @@ -171,20 +150,5 @@ CRYSYSTEM_API ISystem* CreateSystemInterface(const SSystemInitParams& startupPar return pSystem; } - -CRYSYSTEM_API void WINAPI CryInstallUnhandledExceptionHandler() -{ -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION DLLMAIN_CPP_SECTION_4 -#include AZ_RESTRICTED_FILE(DllMain_cpp) -#endif -} - -#if defined(ENABLE_PROFILING_CODE) && !defined(LINUX) && !defined(APPLE) -CRYSYSTEM_API void CryInstallPostExceptionHandler(void (* PostExceptionHandlerCallback)()) -{ - return IDebugCallStack::instance()->FileCreationCallback(PostExceptionHandlerCallback); -} -#endif }; diff --git a/Code/CryEngine/CrySystem/IDebugCallStack.cpp b/Code/CryEngine/CrySystem/IDebugCallStack.cpp deleted file mode 100644 index 3d865dee6c..0000000000 --- a/Code/CryEngine/CrySystem/IDebugCallStack.cpp +++ /dev/null @@ -1,278 +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 : A multiplatform base class for handling errors and collecting call stacks - - -#include "CrySystem_precompiled.h" -#include "IDebugCallStack.h" -#include -#include "System.h" -#include -#include -#include -#include -//#if !defined(LINUX) - -#include - -const char* const IDebugCallStack::s_szFatalErrorCode = "FATAL_ERROR"; - -IDebugCallStack::IDebugCallStack() - : m_bIsFatalError(false) - , m_postBackupProcess(0) - , m_memAllocFileHandle(AZ::IO::InvalidHandle) -{ -} - -IDebugCallStack::~IDebugCallStack() -{ - StopMemLog(); -} - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_DEBUGCALLSTACK_SINGLETON -IDebugCallStack* IDebugCallStack::instance() -{ - static IDebugCallStack sInstance; - return &sInstance; -} -#endif - -void IDebugCallStack::FileCreationCallback(void (* postBackupProcess)()) -{ - m_postBackupProcess = postBackupProcess; -} -////////////////////////////////////////////////////////////////////////// -void IDebugCallStack::LogCallstack() -{ - AZ::Debug::Trace::PrintCallstack("", 2); -} - -const char* IDebugCallStack::TranslateExceptionCode(DWORD dwExcept) -{ - switch (dwExcept) - { -#if AZ_LEGACY_CRYSYSTEM_TRAIT_DEBUGCALLSTACK_TRANSLATE - case EXCEPTION_ACCESS_VIOLATION: - return "EXCEPTION_ACCESS_VIOLATION"; - break; - case EXCEPTION_DATATYPE_MISALIGNMENT: - return "EXCEPTION_DATATYPE_MISALIGNMENT"; - break; - case EXCEPTION_BREAKPOINT: - return "EXCEPTION_BREAKPOINT"; - break; - case EXCEPTION_SINGLE_STEP: - return "EXCEPTION_SINGLE_STEP"; - break; - case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: - return "EXCEPTION_ARRAY_BOUNDS_EXCEEDED"; - break; - case EXCEPTION_FLT_DENORMAL_OPERAND: - return "EXCEPTION_FLT_DENORMAL_OPERAND"; - break; - case EXCEPTION_FLT_DIVIDE_BY_ZERO: - return "EXCEPTION_FLT_DIVIDE_BY_ZERO"; - break; - case EXCEPTION_FLT_INEXACT_RESULT: - return "EXCEPTION_FLT_INEXACT_RESULT"; - break; - case EXCEPTION_FLT_INVALID_OPERATION: - return "EXCEPTION_FLT_INVALID_OPERATION"; - break; - case EXCEPTION_FLT_OVERFLOW: - return "EXCEPTION_FLT_OVERFLOW"; - break; - case EXCEPTION_FLT_STACK_CHECK: - return "EXCEPTION_FLT_STACK_CHECK"; - break; - case EXCEPTION_FLT_UNDERFLOW: - return "EXCEPTION_FLT_UNDERFLOW"; - break; - case EXCEPTION_INT_DIVIDE_BY_ZERO: - return "EXCEPTION_INT_DIVIDE_BY_ZERO"; - break; - case EXCEPTION_INT_OVERFLOW: - return "EXCEPTION_INT_OVERFLOW"; - break; - case EXCEPTION_PRIV_INSTRUCTION: - return "EXCEPTION_PRIV_INSTRUCTION"; - break; - case EXCEPTION_IN_PAGE_ERROR: - return "EXCEPTION_IN_PAGE_ERROR"; - break; - case EXCEPTION_ILLEGAL_INSTRUCTION: - return "EXCEPTION_ILLEGAL_INSTRUCTION"; - break; - case EXCEPTION_NONCONTINUABLE_EXCEPTION: - return "EXCEPTION_NONCONTINUABLE_EXCEPTION"; - break; - case EXCEPTION_STACK_OVERFLOW: - return "EXCEPTION_STACK_OVERFLOW"; - break; - case EXCEPTION_INVALID_DISPOSITION: - return "EXCEPTION_INVALID_DISPOSITION"; - break; - case EXCEPTION_GUARD_PAGE: - return "EXCEPTION_GUARD_PAGE"; - break; - case EXCEPTION_INVALID_HANDLE: - return "EXCEPTION_INVALID_HANDLE"; - break; - //case EXCEPTION_POSSIBLE_DEADLOCK: return "EXCEPTION_POSSIBLE_DEADLOCK"; break ; - - case STATUS_FLOAT_MULTIPLE_FAULTS: - return "STATUS_FLOAT_MULTIPLE_FAULTS"; - break; - case STATUS_FLOAT_MULTIPLE_TRAPS: - return "STATUS_FLOAT_MULTIPLE_TRAPS"; - break; - - -#endif - default: - return "Unknown"; - break; - } -} - -void IDebugCallStack::PutVersion(char* str, size_t length) -{ -AZ_PUSH_DISABLE_WARNING(4996, "-Wunknown-warning-option") - - if (!gEnv || !gEnv->pSystem) - { - return; - } - - char sFileVersion[128]; - gEnv->pSystem->GetFileVersion().ToString(sFileVersion, sizeof(sFileVersion)); - - char sProductVersion[128]; - gEnv->pSystem->GetProductVersion().ToString(sProductVersion, sizeof(sFileVersion)); - - - //! Get time. - time_t ltime; - time(<ime); - tm* today = localtime(<ime); - - char s[1024]; - //! Use strftime to build a customized time string. - strftime(s, 128, "Logged at %#c\n", today); - azstrcat(str, length, s); - sprintf_s(s, "FileVersion: %s\n", sFileVersion); - azstrcat(str, length, s); - sprintf_s(s, "ProductVersion: %s\n", sProductVersion); - azstrcat(str, length, s); - - if (gEnv->pLog) - { - const char* logfile = gEnv->pLog->GetFileName(); - if (logfile) - { - sprintf (s, "LogFile: %s\n", logfile); - azstrcat(str, length, s); - } - } - - AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath(); - azstrcat(str, length, "ProjectDir: "); - azstrcat(str, length, projectPath.c_str()); - azstrcat(str, length, "\n"); - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_DEBUGCALLSTACK_APPEND_MODULENAME - GetModuleFileNameA(NULL, s, sizeof(s)); - - // Log EXE filename only if possible (not full EXE path which could contain sensitive info) - AZStd::string exeName; - if (AZ::StringFunc::Path::GetFullFileName(s, exeName)) - { - azstrcat(str, length, "Executable: "); - azstrcat(str, length, exeName.c_str()); - -# ifdef AZ_DEBUG_BUILD - azstrcat(str, length, " (debug: yes"); -# else - azstrcat(str, length, " (debug: no"); -# endif - } -#endif -AZ_POP_DISABLE_WARNING -} - - -//Crash the application, in this way the debug callstack routine will be called and it will create all the necessary files (error.log, dump, and eventually screenshot) -void IDebugCallStack::FatalError(const char* description) -{ - m_bIsFatalError = true; - WriteLineToLog(description); - -#ifndef _RELEASE - bool bShowDebugScreen = g_cvars.sys_no_crash_dialog == 0; - // showing the debug screen is not safe when not called from mainthread - // it normally leads to a infinity recursion followed by a stack overflow, preventing - // useful call stacks, thus they are disabled - bShowDebugScreen = bShowDebugScreen && gEnv->mMainThreadId == CryGetCurrentThreadId(); - if (bShowDebugScreen) - { - EBUS_EVENT(AZ::NativeUI::NativeUIRequestBus, DisplayOkDialog, "Open 3D Engine Fatal Error", description, false); - } -#endif - -#if defined(WIN32) || !defined(_RELEASE) - int* p = 0x0; - PREFAST_SUPPRESS_WARNING(6011) * p = 1; // we're intentionally crashing here -#endif -} - -void IDebugCallStack::WriteLineToLog(const char* format, ...) -{ - CDebugAllowFileAccess allowFileAccess; - - va_list ArgList; - char szBuffer[MAX_WARNING_LENGTH]; - va_start(ArgList, format); - vsnprintf_s(szBuffer, sizeof(szBuffer), sizeof(szBuffer) - 1, format, ArgList); - cry_strcat(szBuffer, "\n"); - szBuffer[sizeof(szBuffer) - 1] = '\0'; - va_end(ArgList); - - AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; - AZ::IO::FileIOBase::GetDirectInstance()->Open("@Log@\\error.log", AZ::IO::GetOpenModeFromStringMode("a+t"), fileHandle); - if (fileHandle != AZ::IO::InvalidHandle) - { - AZ::IO::FileIOBase::GetDirectInstance()->Write(fileHandle, szBuffer, strlen(szBuffer)); - AZ::IO::FileIOBase::GetDirectInstance()->Flush(fileHandle); - AZ::IO::FileIOBase::GetDirectInstance()->Close(fileHandle); - } -} - -////////////////////////////////////////////////////////////////////////// -void IDebugCallStack::StartMemLog() -{ - AZ::IO::FileIOBase::GetDirectInstance()->Open("@Log@\\memallocfile.log", AZ::IO::OpenMode::ModeWrite, m_memAllocFileHandle); - - assert(m_memAllocFileHandle != AZ::IO::InvalidHandle); -} - -////////////////////////////////////////////////////////////////////////// -void IDebugCallStack::StopMemLog() -{ - if (m_memAllocFileHandle != AZ::IO::InvalidHandle) - { - AZ::IO::FileIOBase::GetDirectInstance()->Close(m_memAllocFileHandle); - m_memAllocFileHandle = AZ::IO::InvalidHandle; - } -} -//#endif //!defined(LINUX) diff --git a/Code/CryEngine/CrySystem/IDebugCallStack.h b/Code/CryEngine/CrySystem/IDebugCallStack.h deleted file mode 100644 index f181b73913..0000000000 --- a/Code/CryEngine/CrySystem/IDebugCallStack.h +++ /dev/null @@ -1,90 +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 : A multiplatform base class for handling errors and collecting call stacks - -#ifndef CRYINCLUDE_CRYSYSTEM_IDEBUGCALLSTACK_H -#define CRYINCLUDE_CRYSYSTEM_IDEBUGCALLSTACK_H -#pragma once - -#include "System.h" - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_FORWARD_EXCEPTION_POINTERS -struct EXCEPTION_POINTERS; -#endif -//! Limits the maximal number of functions in call stack. -enum -{ - MAX_DEBUG_STACK_ENTRIES = 80 -}; - -class IDebugCallStack -{ -public: - // Returns single instance of DebugStack - static IDebugCallStack* instance(); - - virtual int handleException([[maybe_unused]] EXCEPTION_POINTERS* exception_pointer){return 0; } - - // returns the module name of a given address - virtual string GetModuleNameForAddr([[maybe_unused]] void* addr) { return "[unknown]"; } - - // returns the function name of a given address together with source file and line number (if available) of a given address - virtual void GetProcNameForAddr(void* addr, string& procName, void*& baseAddr, string& filename, int& line) - { - filename = "[unknown]"; - line = 0; - baseAddr = addr; -#if defined(PLATFORM_64BIT) - procName.Format("[%016llX]", addr); -#else - procName.Format("[%08X]", addr); -#endif - } - - // returns current filename - virtual string GetCurrentFilename() { return "[unknown]"; } - - //! Dumps Current Call Stack to log. - virtual void LogCallstack(); - //triggers a fatal error, so the DebugCallstack can create the error.log and terminate the application - void FatalError(const char*); - - //Reports a bug and continues execution - virtual void ReportBug(const char*) {} - - virtual void FileCreationCallback(void (* postBackupProcess)()); - - static void WriteLineToLog(const char* format, ...); - - virtual void StartMemLog(); - virtual void StopMemLog(); - -protected: - IDebugCallStack(); - virtual ~IDebugCallStack(); - - static const char* TranslateExceptionCode(DWORD dwExcept); - static void PutVersion(char* str, size_t length); - - bool m_bIsFatalError; - static const char* const s_szFatalErrorCode; - - void (* m_postBackupProcess)(); - - AZ::IO::HandleType m_memAllocFileHandle; -}; - - - -#endif // CRYINCLUDE_CRYSYSTEM_IDEBUGCALLSTACK_H diff --git a/Code/CryEngine/CrySystem/IThreadConfigManager.h b/Code/CryEngine/CrySystem/IThreadConfigManager.h deleted file mode 100644 index 97c4d7237b..0000000000 --- a/Code/CryEngine/CrySystem/IThreadConfigManager.h +++ /dev/null @@ -1,59 +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 SThreadConfig -{ - enum eThreadParamFlag - { - eThreadParamFlag_ThreadName = BIT(0), - eThreadParamFlag_StackSize = BIT(1), - eThreadParamFlag_Affinity = BIT(2), - eThreadParamFlag_Priority = BIT(3), - eThreadParamFlag_PriorityBoost = BIT(4), - }; - - typedef uint32 TThreadParamFlag; - - const char* szThreadName; - uint32 stackSizeBytes; - uint32 affinityFlag; - int32 priority; - bool bDisablePriorityBoost; - - TThreadParamFlag paramActivityFlag; -}; - -class IThreadConfigManager -{ -public: - virtual ~IThreadConfigManager() - { - } - - //! Called once during System startup. - //! Loads the thread configuration for the executing platform from file. - virtual bool LoadConfig(const char* pcPath) = 0; - - //! Returns true if a config has been loaded. - virtual bool ConfigLoaded() const = 0; - - //! Gets the thread configuration for the specified thread on the active platform. - //! If no matching config is found a default configuration is returned (which does not have the same name as the search string). - virtual const SThreadConfig* GetThreadConfig(const char* sThreadName, ...) = 0; - virtual const SThreadConfig* GetDefaultThreadConfig() const = 0; - - //! Dump a detailed description of the thread startup configurations for this platform to the log file. - virtual void DumpThreadConfigurationsToLog() = 0; -}; diff --git a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp index b8002b74a9..0af52d8cc4 100644 --- a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp @@ -17,7 +17,6 @@ #include "LevelSystem.h" #include #include "IMovieSystem.h" -#include "IMaterialEffects.h" #include #include #include "CryPath.h" @@ -648,20 +647,6 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName) AZStd::string levelPath(pLevelInfo->GetPath()); - /* - ICVar *pFileCache = gEnv->pConsole->GetCVar("sys_FileCache"); CRY_ASSERT(pFileCache); - - if(pFileCache->GetIVal()) - { - if(pPak->OpenPack("",pLevelInfo->GetPath()+string("/FileCache.dat"))) - gEnv->pLog->Log("FileCache.dat loaded"); - else - gEnv->pLog->Log("FileCache.dat not loaded"); - } - */ - - m_pSystem->SetThreadState(ESubsys_Physics, false); - ICVar* pSpamDelay = gEnv->pConsole->GetCVar("log_SpamDelay"); float spamDelay = 0.0f; if (pSpamDelay) @@ -768,8 +753,6 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName) gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_START, 0, 0); - m_pSystem->SetThreadState(ESubsys_Physics, true); - return m_pCurrentLevel; } diff --git a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp b/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp index 2a7f8d5c5e..8b3c75cce2 100644 --- a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp +++ b/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp @@ -247,8 +247,6 @@ namespace LegacyLevelSystem auto pPak = gEnv->pCryPak; - m_pSystem->SetThreadState(ESubsys_Physics, false); - ICVar* pSpamDelay = gEnv->pConsole->GetCVar("log_SpamDelay"); float spamDelay = 0.0f; if (pSpamDelay) @@ -343,8 +341,6 @@ namespace LegacyLevelSystem gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_START, 0, 0); - m_pSystem->SetThreadState(ESubsys_Physics, true); - return true; } diff --git a/Code/CryEngine/CrySystem/Log.cpp b/Code/CryEngine/CrySystem/Log.cpp index 62cf29fef9..c51947d8bc 100644 --- a/Code/CryEngine/CrySystem/Log.cpp +++ b/Code/CryEngine/CrySystem/Log.cpp @@ -920,13 +920,7 @@ bool CLog::LogToMainThread(const char* szString, ELogType logType, bool bAdd, SL msg.bAdd = bAdd; msg.destination = destination; msg.logType = logType; - // don't try to store the log message for later in case of out of memory, since then its very likely that this allocation - // also fails and results in a stack overflow. This way we should at least get a out of memory on-screen message instead of - // a not obvious crash - if ((gEnv) && (gEnv->bIsOutOfMemory == false)) - { - m_threadSafeMsgQueue.push(msg); - } + m_threadSafeMsgQueue.push(msg); return true; } return false; @@ -1448,8 +1442,6 @@ void CLog::UpdateLoadingScreen(const char* szFormat, ...) if (CryGetCurrentThreadId() == m_nMainThreadId) { - ((CSystem*)m_pSystem)->UpdateLoadingScreen(); - #ifndef LINUX // Take this opportunity to update streaming engine. if (IStreamEngine* pStreamEngine = GetISystem()->GetStreamEngine()) diff --git a/Code/CryEngine/CrySystem/NotificationNetwork.cpp b/Code/CryEngine/CrySystem/NotificationNetwork.cpp deleted file mode 100644 index a0bd3fb9e6..0000000000 --- a/Code/CryEngine/CrySystem/NotificationNetwork.cpp +++ /dev/null @@ -1,1345 +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 "CrySystem_precompiled.h" -#include "NotificationNetwork.h" -#include - -#include -#include - -#undef LockDebug -//#define LockDebug(str1,str2) {string strMessage;strMessage.Format(str1,str2);if (m_clients.size()) OutputDebugString(strMessage.c_str());} -#define LockDebug(str1, str2) - -// - -extern bool RCON_IsRemoteAllowedToConnect(const AZ::AzSock::AzSocketAddress& connectee); - -using namespace NotificationNetwork; - -// - -#include -class CQueryNotification - : public INotificationNetworkListener -{ - // INotificationNetworkListener -public: - virtual void OnNotificationNetworkReceive([[maybe_unused]] const void* pBuffer, [[maybe_unused]] size_t length) - { - INotificationNetwork* pNotificationNetwork = - gEnv->pSystem->GetINotificationNetwork(); - if (!pNotificationNetwork) - { - return; - } - - AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath(); - if (projectPath.empty()) - { - return; - } - - pNotificationNetwork->Send("SystemInfo", projectPath.c_str(), projectPath.size()); - } -} g_queryNotification; - -AZSOCKET CConnectionBase::CreateSocket() -{ - AZSOCKET sock = AZ::AzSock::Socket(); - if (!AZ::AzSock::IsAzSocketValid(sock)) - { - CryLog("CNotificationNetworkClient::Create: Failed to create socket."); - return AZ_SOCKET_INVALID; - } - - if (AZ::AzSock::SetSocketOption(sock, AZ::AzSock::AzSocketOption::REUSEADDR, true)) - { - AZ::AzSock::CloseSocket(sock); - CryLog("CNotificationNetworkClient::Create: Failed to set SO_REUSEADDR option."); - return AZ_SOCKET_INVALID; - } - -#if defined (WIN32) || defined(WIN64) //MS Platforms - if (AZ::AzSock::SetSocketBlockingMode(sock, false)) - { - AZ::AzSock::CloseSocket(sock); - CryLog("CNotificationNetworkClient::Connect: Failed to set socket to asynchronous operation."); - return AZ_SOCKET_INVALID; - } - -#endif - - // TCP_NODELAY required for win32 because of high latency connection otherwise -#if defined(WIN32) - if (AZ::AzSock::EnableTCPNoDelay(sock, true)) - { - AZ::AzSock::CloseSocket(sock); - CryLog("CNotificationNetworkClient::Create: Failed to set TCP_NODELAY option."); - return AZ_SOCKET_INVALID; - } -#endif - - return sock; -} - -bool CConnectionBase::Connect(const char* address, uint16 port) -{ - AZ::AzSock::AzSocketAddress socketAddress; - socketAddress.SetAddress(address, port); - - int result = AZ::AzSock::Connect(m_socket, socketAddress); - if (AZ::AzSock::SocketErrorOccured(result)) - { - AZ::AzSock::AzSockError err = AZ::AzSock::AzSockError(result); - if (err == AZ::AzSock::AzSockError::eASE_EWOULDBLOCK_CONN) - { - return true; - } - - if (err == AZ::AzSock::AzSockError::eASE_EISCONN) - { - if (!m_boIsConnected) - { - m_boIsConnected = true; - m_boIsFailedToConnect = false; - OnConnect(true); - } - return true; - } - - if (err == AZ::AzSock::AzSockError::eASE_EALREADY) - { - // It will happen, in case of DNS problems, or if the console is not - // reachable or turned off. - //CryLog("CNotificationNetworkClient::Connect: Failed to connect. Reason: already conencted."); - return true; - } - - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - CryLog("CNotificationNetworkClient::Connect: Failed to connect. Reason: %d ", result); - return false; - } - - return true; -} - -/* - - CChannel - -*/ - -bool CChannel::IsNameValid(const char* name) -{ - if (!name) - { - return false; - } - if (!*name) - { - return false; - } - - if (::strlen(name) > NN_CHANNEL_NAME_LENGTH_MAX) - { - return false; - } - - return true; -} - -// - -CChannel::CChannel() -{ -} - -CChannel::CChannel(const char* name) -{ - if (!name) - { - return; - } - - if (!*name) - { - return; - } - - size_t length = MIN(::strlen(name), NN_CHANNEL_NAME_LENGTH_MAX); - ::memset(m_name, 0, NN_CHANNEL_NAME_LENGTH_MAX); - ::memcpy(m_name, name, length); -} - -CChannel::~CChannel() -{ -} - -// - -void CChannel::WriteToPacketHeader(void* pPacket) const -{ - ::memcpy((uint8*)pPacket + NN_PACKET_HEADER_OFFSET_CHANNEL, - m_name, NN_CHANNEL_NAME_LENGTH_MAX); -} - -void CChannel::ReadFromPacketHeader(void* pPacket) -{ - ::memcpy(m_name, (uint8*)pPacket + NN_PACKET_HEADER_OFFSET_CHANNEL, - NN_CHANNEL_NAME_LENGTH_MAX); -} - -// - -bool CChannel::operator ==(const CChannel& channel) const -{ - return ::strncmp(m_name, channel.m_name, NN_CHANNEL_NAME_LENGTH_MAX) == 0; -} - -bool CChannel::operator !=(const CChannel& channel) const -{ - return ::strncmp(m_name, channel.m_name, NN_CHANNEL_NAME_LENGTH_MAX) != 0; -} - -/* - - CListeners - -*/ - -CListeners::CListeners() -{ - m_pNotificationWrite = &m_notifications[0]; - m_pNotificationRead = &m_notifications[1]; -} - -CListeners::~CListeners() -{ - while (!m_pNotificationRead->empty()) - { - SBuffer buffer = m_pNotificationRead->front(); - m_pNotificationRead->pop(); - delete[] buffer.pData; - } - - while (!m_pNotificationWrite->empty()) - { - SBuffer buffer = m_pNotificationWrite->front(); - m_pNotificationWrite->pop(); - delete[] buffer.pData; - } -} - -// - -size_t CListeners::Count(const CChannel& channel) -{ - size_t count = 0; - for (size_t i = 0; i < m_listeners.size(); ++i) - { - if (m_listeners[i].second != channel) - { - continue; - } - - ++count; - } - - return count; -} - -CChannel* CListeners::Channel(INotificationNetworkListener* pListener) -{ - for (size_t i = 0; i < m_listeners.size(); ++i) - { - if (m_listeners[i].first != pListener) - { - continue; - } - - return &m_listeners[i].second; - } - - return nullptr; -} - -bool CListeners::Bind(const CChannel& channel, INotificationNetworkListener* pListener) -{ - for (size_t i = 0; i < m_listeners.size(); ++i) - { - if (m_listeners[i].first == pListener) - { - m_listeners[i].second = channel; - return true; - } - } - - m_listeners.push_back(std::pair()); - m_listeners.back().first = pListener; - m_listeners.back().second = channel; - return true; -} - -bool CListeners::Remove(INotificationNetworkListener* pListener) -{ - for (size_t i = 0; i < m_listeners.size(); ++i) - { - if (m_listeners[i].first != pListener) - { - continue; - } - - m_listeners[i] = m_listeners.back(); - m_listeners.pop_back(); - return true; - } - - return false; -} - -void CListeners::NotificationPush(const SBuffer& buffer) -{ - // TODO: Use auto lock. - m_notificationCriticalSection.Lock(); - m_pNotificationWrite->push(buffer); - m_notificationCriticalSection.Unlock(); -} - -void CListeners::NotificationsProcess() -{ - m_notificationCriticalSection.Lock(); - std::swap(m_pNotificationWrite, m_pNotificationRead); - m_notificationCriticalSection.Unlock(); - - while (!m_pNotificationRead->empty()) - { - SBuffer buffer = m_pNotificationRead->front(); - m_pNotificationRead->pop(); - - for (size_t i = 0; i < m_listeners.size(); ++i) - { - if (m_listeners[i].second != buffer.channel) - { - continue; - } - - m_listeners[i].first->OnNotificationNetworkReceive( - buffer.pData, buffer.length); - } - - delete[] buffer.pData; - } -} - -/* - - CConnectionBase - -*/ - -CConnectionBase::CConnectionBase(CNotificationNetwork* pNotificationNetwork) -{ - m_pNotificationNetwork = pNotificationNetwork; - - m_port = 0; - - m_socket = AZ_SOCKET_INVALID; - - m_buffer.pData = nullptr; - m_buffer.length = 0; - m_dataLeft = 0; - - m_boIsConnected = false; - m_boIsFailedToConnect = false; -} - -CConnectionBase::~CConnectionBase() -{ - if (m_buffer.pData) - { - delete[] m_buffer.pData; - } - - if (m_socket != AZ_SOCKET_INVALID) - { - CloseSocket_Internal(); - } -} - -// - -void CConnectionBase::SetAddress(const char* address, uint16 port) -{ - size_t length = MIN(::strlen(address), 15); - ::memset(m_address, 0, sizeof(m_address)); - ::memcpy(m_address, address, length); - m_port = port; -} - -bool CConnectionBase::Validate() -{ - if (m_socket != AZ_SOCKET_INVALID) - { - if (!m_port) - { - AZ::AzSock::AzSocketAddress socketAddress; - int result = AZ::AzSock::GetSockName(m_socket, socketAddress); - if (AZ::AzSock::SocketErrorOccured(result)) - { - return false; - } - } - - return Select_Internal(); - } - - if (!m_port) // If port is not set we don't want to try to reconnect. - { - return false; - } - - m_socket = CreateSocket(); - // If the create sockect will fail, it is likely that we will never be able to connect, - // we might want to signal that. - - Connect(m_address, m_port); - - return false; -} - -bool CConnectionBase::Send(const void* pBuffer, size_t length) -{ - if (!Validate()) - { - return false; - } - - size_t sent = 0; - while (sent < length) - { - int r = AZ::AzSock::Send(m_socket, (const char*)pBuffer + sent, length - sent, 0); - if (AZ::AzSock::SocketErrorOccured(r)) - { - AZ::AzSock::AzSockError nCurrentError = AZ::AzSock::AzSockError(r); - if (nCurrentError == AZ::AzSock::AzSockError::eASE_ENOTCONN) - { - r = 0; - break; - } - else if (nCurrentError == AZ::AzSock::AzSockError::eASE_EWOULDBLOCK) - { - r = 0; - } - else - { - CryLog("CNotificationNetworkClient::Send: Failed to send package. Reason: %s", AZ::AzSock::GetStringForError(r)); - CloseSocket_Internal(); - return false; - } - } - - sent += r; - } - - return true; -} - -bool CConnectionBase::SendMessage(EMessage eMessage, const CChannel& channel, uint32 data) -{ - char header[NN_PACKET_HEADER_LENGTH]; - ::memset(header, 0, NN_PACKET_HEADER_LENGTH); - *(uint32*)&header[NN_PACKET_HEADER_OFFSET_MESSAGE] = AZ::AzSock::HostToNetLong(eMessage); - *(uint32*)&header[NN_PACKET_HEADER_OFFSET_DATA_LENGTH] = AZ::AzSock::HostToNetLong(data); - channel.WriteToPacketHeader(header); - - if (!Send(header, NN_PACKET_HEADER_LENGTH)) - { - return false; - } - - return true; -} - -bool CConnectionBase::Select_Internal() -{ - if (m_socket == AZ_SOCKET_INVALID) - { - return false; - } - - AZFD_SET stExceptions; - AZFD_SET stWriteSockets; - - FD_ZERO(&stExceptions); - FD_SET(m_socket, &stExceptions); - - FD_ZERO(&stWriteSockets); - FD_SET(m_socket, &stWriteSockets); - - AZTIMEVAL timeOut = { 0, 0 }; - - int r = AZ::AzSock::Select(m_socket, nullptr, &stWriteSockets, &stExceptions, &timeOut); - if (AZ::AzSock::SocketErrorOccured(r)) - { - CryLog("CNotificationNetworkClient:: Failed to select socket. Reason: %s", AZ::AzSock::GetStringForError(r)); - CloseSocket_Internal(); - m_boIsFailedToConnect = true; - return false; - } - else if (!r) - { - return m_boIsConnected; - } - - if (FD_ISSET(m_socket, &stExceptions)) - { - CloseSocket_Internal(); - m_boIsFailedToConnect = true; - OnConnect(m_boIsConnected); // Handles failed attempt to connect. - return false; - } - else if (FD_ISSET(m_socket, &stWriteSockets)) // In Windows a socket can be in both lists. - { - if (!m_boIsConnected) - { - m_boIsConnected = true; - m_boIsFailedToConnect = false; - OnConnect(m_boIsConnected); // Handles successful attempt to connect. - } - return true; - } - - return false; -} - -void CConnectionBase::CloseSocket_Internal() -{ - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - if (m_boIsConnected) - { - OnDisconnect(); - } - m_boIsConnected = false; -} - -bool CConnectionBase::SendNotification(const CChannel& channel, const void* pBuffer, size_t length) -{ - if (!SendMessage(eMessage_DataTransfer, channel, length)) - { - return false; - } - if (!length) - { - return true; - } - - if (!Send(pBuffer, length)) - { - return false; - } - - return true; -} - -bool CConnectionBase::ReceiveMessage(CListeners& listeners) -{ - if (!Validate()) - { - return false; - } - - if (!m_dataLeft) - { - m_dataLeft = NN_PACKET_HEADER_LENGTH; - } - int r = AZ::AzSock::Recv(m_socket, (char*)&m_bufferHeader[NN_PACKET_HEADER_LENGTH - m_dataLeft], m_dataLeft, 0); - if (!r) - { - // Connection terminated. - m_dataLeft = 0; - - CloseSocket_Internal(); - return false; - } - if (AZ::AzSock::SocketErrorOccured(r)) - { - m_dataLeft = 0; - - CryLog("CNotificationNetworkClient::ReceiveMessage: Failed to receive package. Reason: %s", AZ::AzSock::GetStringForError(r)); - CloseSocket_Internal(); - return false; - } - - if (m_dataLeft -= r) - { - return true; - } - - // The whole message was received, process it... - - EMessage eMessage = (EMessage)AZ::AzSock::NetToHostLong( - *(uint32*)&m_bufferHeader[NN_PACKET_HEADER_OFFSET_MESSAGE]); - const CChannel& channel = *(CChannel*)&m_bufferHeader[NN_PACKET_HEADER_OFFSET_CHANNEL]; - - if (eMessage == eMessage_DataTransfer) - { - m_dataLeft = AZ::AzSock::NetToHostLong(*(uint32*)&m_bufferHeader[NN_PACKET_HEADER_OFFSET_DATA_LENGTH]); - if (!m_dataLeft) - { - SBuffer buffer; - buffer.channel = channel; - buffer.pData = nullptr; - buffer.length = 0; - listeners.NotificationPush(buffer); - return true; - } - - m_buffer.pData = new uint8[m_buffer.length = m_dataLeft]; - if (!m_buffer.pData) - { - CryLog("CNotificationNetwork::CConnection::Receive: Failed to allocate buffer.\n"); - m_dataLeft = 0; - - CloseSocket_Internal(); - return false; - } - - m_buffer.channel.ReadFromPacketHeader(m_bufferHeader); - return +1; - } - - if (!OnMessage(eMessage, channel)) - { - CryLog("NotificationNetwork::CConnectionBase::ReceiveMessage: " - "Unknown message received, terminating Connection...\n"); - m_dataLeft = 0; - - CloseSocket_Internal(); - return false; - } - - return true; -} - -bool CConnectionBase::ReceiveNotification(CListeners& listeners) -{ - int r = AZ::AzSock::Recv(m_socket, (char*)&m_buffer.pData[m_buffer.length - m_dataLeft], m_dataLeft, 0); - if (!r) - { - CryLog("CNotificationNetworkClient::ReceiveNotification: Failed to receive package. Reason: Connection terminated."); - // Connection terminated. - m_dataLeft = 0; - - CloseSocket_Internal(); - return false; - } - - if (AZ::AzSock::SocketErrorOccured(r)) - { - m_dataLeft = 0; - - CryLog("CNotificationNetworkClient::ReceiveNotification: Failed to receive package. Reason: %s", AZ::AzSock::GetStringForError(r)); - CloseSocket_Internal(); - return false; - } - - if (m_dataLeft -= r) - { - return true; - } - - listeners.NotificationPush(m_buffer); - m_buffer.pData = nullptr; - m_buffer.length = 0; - m_dataLeft = 0; - return true; -} - -bool CConnectionBase::Receive(CListeners& listeners) -{ - if (m_buffer.pData) - { - return ReceiveNotification(listeners); - } - - return ReceiveMessage(listeners); -} - -bool CConnectionBase::GetIsConnectedFlag() -{ - return Select_Internal() || m_boIsConnected; -} - -bool CConnectionBase::GetIsFailedToConnectFlag() const -{ - return m_boIsFailedToConnect; -} - -/* - - CClient - -*/ - -CClient* CClient::Create(CNotificationNetwork* pNotificationNetwork, const char* address, uint16 port) -{ - CClient* pClient = new CClient(pNotificationNetwork); - AZSOCKET sock = pClient->CreateSocket(); - // In the current implementation, this is REALLY UNLIKELY to happen. - if (sock == AZ_SOCKET_INVALID) - { - delete pClient; - return nullptr; - } - - // - pClient->SetSocket(sock); - pClient->Connect(address, port); - - pClient->SetAddress(address, port); - pClient->SetSocket(sock); - return pClient; -} - -CClient* CClient::Create(CNotificationNetwork* pNotificationNetwork) -{ - CClient* pClient = new CClient(pNotificationNetwork); - return pClient; -} - -// - -CClient::CClient(CNotificationNetwork* pNotificationNetwork) - : CConnectionBase(pNotificationNetwork) -{ -} - -CClient::~CClient() -{ - GetNotificationNetwork()->ReleaseClients(this); -} - -// - -void CClient::Update() -{ - m_listeners.NotificationsProcess(); -} - -// CConnectionBase - -bool CClient::OnConnect(bool boConnected) -{ - if (boConnected) - { - for (size_t i = 0; i < m_listeners.Count(); ++i) - { - if (!SendMessage(eMessage_ChannelRegister, m_listeners.Channel(i), 0)) - { - return false; - } - } - } - - CryAutoLock lock(m_stConnectionCallbacksLock); - for (size_t nCount = 0; nCount < m_cNotificationNetworkConnectionCallbacks.size(); ++nCount) - { - m_cNotificationNetworkConnectionCallbacks[nCount]->OnConnect(this, boConnected); - } - - return boConnected; -} - -bool CClient::OnDisconnect() -{ - CryAutoLock lock(m_stConnectionCallbacksLock); - for (size_t nCount = 0; nCount < m_cNotificationNetworkConnectionCallbacks.size(); ++nCount) - { - m_cNotificationNetworkConnectionCallbacks[nCount]->OnDisconnected(this); - } - - return true; -} - -bool CClient::OnMessage([[maybe_unused]] EMessage eMessage, [[maybe_unused]] const CChannel& channel) -{ - return false; -} - -// INotificationNetworkClient - -bool CClient::Connect(const char* address, uint16 port) -{ - bool bReturnValue(false); - - if (m_socket == AZ_SOCKET_INVALID) - { - m_socket = CreateSocket(); - } - - bReturnValue = CConnectionBase::Connect(address, port); - if (bReturnValue) - { - SetAddress(address, port); - } - - return bReturnValue; -} - -bool CClient::ListenerBind(const char* channelName, INotificationNetworkListener* pListener) -{ - if (!CChannel::IsNameValid(channelName)) - { - return false; - } - - if (!m_listeners.Bind(CChannel(channelName), pListener)) - { - return false; - } - - if (!SendMessage(eMessage_ChannelRegister, CChannel(channelName), 0)) - { - return false; - } - - return true; -} - -bool CClient::ListenerRemove(INotificationNetworkListener* pListener) -{ - CChannel* pChannel = m_listeners.Channel(pListener); - if (!pChannel) - { - return false; - } - - if (!m_listeners.Remove(pListener)) - { - return false; - } - - if (!SendMessage(eMessage_ChannelUnregister, *pChannel, 0)) - { - return false; - } - - return true; -} - -bool CClient::Send(const char* channelName, const void* pBuffer, size_t length) -{ - CRY_ASSERT(CChannel::IsNameValid(channelName)); - // CRY_ASSERT_MESSAGE(channelLength <= NN_CHANNEL_NAME_LENGTH_MAX, - // "Channel name \"%s\" was passed to a Notification Network method, the name cannot be longer than %d chars.", - // channel, NN_CHANNEL_NAME_LENGTH_MAX); - - if (!CChannel::IsNameValid(channelName)) - { - return false; - } - if (!SendNotification(CChannel(channelName), pBuffer, length)) - { - return false; - } - - return true; -} - -bool CClient::RegisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback) -{ - CryAutoLock lock(m_stConnectionCallbacksLock); - return stl::push_back_unique(m_cNotificationNetworkConnectionCallbacks, pConnectionCallback); -} - -bool CClient::UnregisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback) -{ - CryAutoLock lock(m_stConnectionCallbacksLock); - return stl::find_and_erase(m_cNotificationNetworkConnectionCallbacks, pConnectionCallback); -} - -/* - - CNotificationNetwork::CConnection - -*/ - -CNotificationNetwork::CConnection::CConnection(CNotificationNetwork* pNotificationNetwork, AZSOCKET sock) - : CConnectionBase(pNotificationNetwork) -{ - SetSocket(sock); - m_listeningChannels.reserve(8); -} - -CNotificationNetwork::CConnection::~CConnection() -{ -} - -// - -bool CNotificationNetwork::CConnection::IsListening(const CChannel& channel) -{ - for (size_t i = 0; i < m_listeningChannels.size(); ++i) - { - if (m_listeningChannels[i] == channel) - { - return true; - } - } - - return false; -} - -// CConnectionBase - -bool CNotificationNetwork::CConnection::OnMessage(EMessage eMessage, const CChannel& channel) -{ - switch (eMessage) - { - case eMessage_ChannelRegister: - for (size_t i = 0; i < m_listeningChannels.size(); ++i) - { - if (m_listeningChannels[i] == channel) - { - return true; - } - } - m_listeningChannels.push_back(channel); - return true; - - case eMessage_ChannelUnregister: - for (size_t i = 0; i < m_listeningChannels.size(); ++i) - { - if (m_listeningChannels[i] != channel) - { - continue; - } - - m_listeningChannels[i] = m_listeningChannels.back(); - m_listeningChannels.pop_back(); - return true; - } - return true; - } - - return false; -} - -/* - - CNotificationNetwork::CThread - -*/ - -CNotificationNetwork::CThread::CThread() -{ - m_pNotificationNetwork = nullptr; - m_bRun = true; -} - -CNotificationNetwork::CThread::~CThread() -{ -} - -// - -bool CNotificationNetwork::CThread::Begin(CNotificationNetwork* pNotificationNetwork) -{ - m_pNotificationNetwork = pNotificationNetwork; - Start(-1, (char*)NN_THREAD_NAME); - return true; -} - - -void CNotificationNetwork::CThread::End() -{ - m_bRun = false; - // WaitForThread(); - - // TODO: Should properly close! -} - -// CryRunnable - -void CNotificationNetwork::CThread::Run() -{ - CryThreadSetName(threadID(THREADID_NULL), NN_THREAD_NAME); - while (m_bRun) - { - m_pNotificationNetwork->ProcessSockets(); - } -} - -/* - - CNotificationNetwork - -*/ - -CNotificationNetwork* CNotificationNetwork::Create() -{ - AZ::AzSock::Startup(); - - AZSOCKET sock = AZ::AzSock::Socket(); - if (!AZ::AzSock::IsAzSocketValid(sock)) - { - CryLog("CNotificationNetwork::Create: Failed to create socket.\n"); - return nullptr; - } - - // Disable nagling of small blocks to fight high latency connection - int result = AZ::AzSock::EnableTCPNoDelay(sock, true); - if (AZ::AzSock::SocketErrorOccured(result)) - { - AZ::AzSock::CloseSocket(sock); - CryLog("CNotificationNetworkClient::Create: Failed to set TCP_NODELAY option."); - return nullptr; - } - - result = AZ::AzSock::SetSocketBlockingMode(sock, false); - if (AZ::AzSock::SocketErrorOccured(result)) - { - AZ::AzSock::CloseSocket(sock); - CryLog("CNotificationNetworkClient::Connect: Failed to set socket to asynchronous operation."); - return nullptr; - } - - // Editor uses a different port to avoid conflicts when running both editor and game on same PC - // But allows the lua remote debugger to connect to the editor - unsigned short port = gEnv && gEnv->IsEditor() ? 9433 : 9432; - - AZ::AzSock::AzSocketAddress addr; - addr.SetAddrPort(port); - - result = AZ::AzSock::Bind(sock, addr); - if (AZ::AzSock::SocketErrorOccured(result)) - { - CryLog("CNotificationNetwork::Create: Failed to bind socket.\n"); - AZ::AzSock::CloseSocket(sock); - return nullptr; - } - - result = AZ::AzSock::Listen(sock, 8); - if (AZ::AzSock::SocketErrorOccured(result)) - { - CryLog("CNotificationNetwork::Create: Failed to listen.\n"); - AZ::AzSock::CloseSocket(sock); - return nullptr; - } - - CNotificationNetwork* pNotificationNetwork = new CNotificationNetwork(); - pNotificationNetwork->m_socket = sock; - - pNotificationNetwork->m_thread.Begin(pNotificationNetwork); - - return pNotificationNetwork; -} - -// - -CNotificationNetwork::CNotificationNetwork() -{ - m_socket = AZ_SOCKET_INVALID; - - m_connections.reserve(4); - - m_listeners.Bind("Query", &g_queryNotification); -} - -CNotificationNetwork::~CNotificationNetwork() -{ - m_thread.End(); - m_thread.Stop(); - m_thread.WaitForThread(); - while (!m_connections.empty()) - { - delete m_connections.back(); - m_connections.pop_back(); - } - - if (m_socket != AZ_SOCKET_INVALID) - { - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - } - - AZ::AzSock::Cleanup(); -} - -// - -void CNotificationNetwork::ReleaseClients(CClient* pClient) -{ - // TODO: Use CryAutoLock - LockDebug("Lock %s\n", "CNotificationNetwork::ReleaseClients()"); - m_clientsCriticalSection.Lock(); - for (size_t i = 0; i < m_clients.size(); ++i) - { - if (m_clients[i] != pClient) - { - continue; - } - - m_clients[i] = m_clients.back(); - m_clients.pop_back(); - break; - } - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock %s\n", "CNotificationNetwork::ReleaseClients()"); -} - -void CNotificationNetwork::ProcessSockets() -{ - fd_set read; - FD_ZERO(&read); - AZSOCKET socketMax = 0; - if (m_socket != AZ_SOCKET_INVALID) - { - FD_SET(m_socket, &read); - socketMax = m_socket; - } - for (size_t i = 0; i < m_connections.size(); ++i) - { - if (m_connections[i]->Validate()) - { - AZSOCKET sock = m_connections[i]->GetSocket(); - FD_SET(sock, &read); - - if (socketMax < sock) - { - socketMax = sock; - } - - continue; - } - - // The Connection is invalid, remove it. - CConnection* pConnection = m_connections[i]; - m_connections[i] = m_connections.back(); - m_connections.pop_back(); - delete pConnection; - - // Invalidate the loop increment since we just removed a Connection and - // in the process potentially replaced its slot with an unprocessed one. - --i; - - CryLog("Notification Network Connection terminated, current total: %d\n", - (int)m_connections.size()); - } - - LockDebug("Lock %s\n", "CNotificationNetwork::ProcessSockets()"); - m_clientsCriticalSection.Lock(); - for (size_t i = 0; i < m_clients.size(); ++i) - { - if (!m_clients[i]->Validate()) - { - continue; - } - - AZSOCKET sock = m_clients[i]->GetSocket(); - FD_SET(sock, &read); - - if (socketMax < sock) - { - socketMax = sock; - } - } - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock %s\n", "CNotificationNetwork::ProcessSockets()"); - - AZTIMEVAL timeOut = { 1, 0 }; - int r = AZ::AzSock::Select(socketMax, &read, nullptr, nullptr, &timeOut); - if (r == 0) - { - return; - } - - // When we have no sockets, the select statement will fail and not - // block for even 1 second, as it should... - if (AZ::AzSock::SocketErrorOccured(r)) - { - // So we force the sleep here for now. - Sleep(1000); - return; - } - - for (size_t i = 0; i < m_connections.size(); ++i) - { - if (!FD_ISSET(m_connections[i]->GetSocket(), &read)) - { - continue; - } - - m_connections[i]->Receive(m_listeners); - } - - LockDebug("Lock 2 %s\n", "CNotificationNetwork::ProcessSockets()"); - m_clientsCriticalSection.Lock(); - for (size_t i = 0; i < m_clients.size(); ++i) - { - if (!FD_ISSET(m_clients[i]->GetSocket(), &read)) - { - continue; - } - - m_clients[i]->Receive(); - } - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock 2 %s\n", "CNotificationNetwork::ProcessSockets()"); - - if (m_socket == AZ_SOCKET_INVALID) - { - return; - } - if (!FD_ISSET(m_socket, &read)) - { - return; - } - - AZ::AzSock::AzSocketAddress addr; - AZSOCKET sock = AZ::AzSock::Accept(m_socket, addr); - if (!AZ::AzSock::IsAzSocketValid(sock)) - { - return; - } - - if (!RCON_IsRemoteAllowedToConnect(addr)) - { - AZ::AzSock::CloseSocket(sock); - return; - } - - m_connections.push_back(new CConnection(this, sock)); - - CryLog("Notification Network accepted new Connection, current total: %d\n", - (int)m_connections.size()); -} - -// INotificationNetwork - -INotificationNetworkClient* CNotificationNetwork::CreateClient() -{ - CClient* pClient = CClient::Create(this); - - LockDebug("Lock %s\n", "CNotificationNetwork::CreateClient()"); - m_clientsCriticalSection.Lock(); - m_clients.push_back(pClient); - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock %s\n", "CNotificationNetwork::CreateClient()"); - - return pClient; -} - -INotificationNetworkClient* CNotificationNetwork::Connect(const char* address, uint16 port) -{ - CClient* pClient = CClient::Create(this, address, port); - if (!pClient) - { - return nullptr; - } - - LockDebug("Lock %s\n", "CNotificationNetwork::Connect()"); - m_clientsCriticalSection.Lock(); - m_clients.push_back(pClient); - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock %s\n", "CNotificationNetwork::Connect()"); - - return pClient; -} - -size_t CNotificationNetwork::GetConnectionCount(const char* channelName) -{ - if (!channelName) - { - return m_connections.size(); - } - - if (!CChannel::IsNameValid(channelName)) - { - return 0; - } - - CChannel channel(channelName); - size_t count = 0; - for (size_t i = 0; i < m_connections.size(); ++i) - { - if (!m_connections[i]->IsListening(channel)) - { - continue; - } - - ++count; - } - return count; -} - -bool CNotificationNetwork::ListenerBind(const char* channelName, INotificationNetworkListener* pListener) -{ - if (!CChannel::IsNameValid(channelName)) - { - return false; - } - - return m_listeners.Bind(CChannel(channelName), pListener); -} - -bool CNotificationNetwork::ListenerRemove(INotificationNetworkListener* pListener) -{ - return m_listeners.Remove(pListener); -} - -void CNotificationNetwork::Update() -{ - m_listeners.NotificationsProcess(); - - LockDebug("Lock %s\n", "CNotificationNetwork::Update()"); - m_clientsCriticalSection.Lock(); - for (size_t i = 0; i < m_clients.size(); ++i) - { - m_clients[i]->Update(); - } - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock %s\n", "CNotificationNetwork::Update()"); -} - -uint32 CNotificationNetwork::Send(const char* channelName, const void* pBuffer, size_t length) -{ - if (!CChannel::IsNameValid(channelName)) - { - return 0; - } - - CChannel channel(channelName); - - // TODO: There should be a mutex lock here to ensure thread safety. - - uint32 count = 0; - for (size_t i = 0; i < m_connections.size(); ++i) - { - if (!m_connections[i]->IsListening(channel)) - { - continue; - } - - if (m_connections[i]->SendNotification(channel, pBuffer, length)) - { - ++count; - } - } - - return count; -} diff --git a/Code/CryEngine/CrySystem/NotificationNetwork.h b/Code/CryEngine/CrySystem/NotificationNetwork.h deleted file mode 100644 index ee336dbbb0..0000000000 --- a/Code/CryEngine/CrySystem/NotificationNetwork.h +++ /dev/null @@ -1,293 +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_CRYSYSTEM_NOTIFICATIONNETWORK_H -#define CRYINCLUDE_CRYSYSTEM_NOTIFICATIONNETWORK_H - -#pragma once - -#include -#include -#include - -#include - -class CNotificationNetwork; -namespace NotificationNetwork { - // Constants - - static const uint32 NN_PACKET_HEADER_LENGTH = 2 * sizeof(uint32) + NN_CHANNEL_NAME_LENGTH_MAX; - - static const uint32 NN_PACKET_HEADER_OFFSET_MESSAGE = 0; - static const uint32 NN_PACKET_HEADER_OFFSET_DATA_LENGTH = sizeof(uint32); - static const uint32 NN_PACKET_HEADER_OFFSET_CHANNEL = sizeof(uint32) + sizeof(uint32); - - static const char* NN_THREAD_NAME = "NotificationNetwork"; - - enum EMessage - { - eMessage_DataTransfer = 0xbada2217, - - eMessage_ChannelRegister = 0xab4eda30, - eMessage_ChannelUnregister = 0xfa4e3423, - }; - - // Classes - - struct CChannel - { - public: - static bool IsNameValid(const char* name); - - public: - CChannel(); - CChannel(const char* name); - ~CChannel(); - - public: - void WriteToPacketHeader(void* pPacket) const; - void ReadFromPacketHeader(void* pPacket); - - public: - bool operator ==(const CChannel& channel) const; - bool operator !=(const CChannel& channel) const; - - private: - char m_name[NN_CHANNEL_NAME_LENGTH_MAX]; - }; - - // TEMP - struct SBuffer - { - uint8* pData; - uint32 length; - CChannel channel; - }; - - class CListeners - { - public: - CListeners(); - ~CListeners(); - - public: - size_t Count() { return m_listeners.size(); } - size_t Count(const CChannel& channel); - - CChannel& Channel(size_t index) { return m_listeners[index].second; } - CChannel* Channel(INotificationNetworkListener* pListener); - - bool Bind(const CChannel& channel, INotificationNetworkListener* pListener); - bool Remove(INotificationNetworkListener* pListener); - - void NotificationPush(const SBuffer& buffer); - void NotificationsProcess(); - - private: - std::vector< std::pair > m_listeners; - - std::queue m_notifications[2]; - std::queue* m_pNotificationWrite; - std::queue* m_pNotificationRead; - CryCriticalSection m_notificationCriticalSection; - }; - - class CConnectionBase - { - public: - CConnectionBase(CNotificationNetwork* pNotificationNetwork); - virtual ~CConnectionBase(); - - public: - AZSOCKET CreateSocket(); - - bool Connect(const char* address, uint16 port); - - AZSOCKET GetSocket() { return m_socket; } - - bool Validate(); - - bool SendNotification(const CChannel& channel, const void* pBuffer, size_t length); - - bool Receive(CListeners& listeners); - - bool GetIsConnectedFlag(); - bool GetIsFailedToConnectFlag() const; - - protected: - CNotificationNetwork* GetNotificationNetwork() { return m_pNotificationNetwork; } - - void SetAddress(const char* address, uint16 port); - void SetSocket(AZSOCKET sock) { m_socket = sock; } - - bool Send(const void* pBuffer, size_t length); - bool SendMessage(EMessage eMessage, const CChannel& channel, uint32 data); - - bool Select_Internal(); - void CloseSocket_Internal(); - - virtual bool OnConnect([[maybe_unused]] bool bConnectionResult) { return true; } - virtual bool OnDisconnect() {return true; } - virtual bool OnMessage([[maybe_unused]] EMessage eMessage, [[maybe_unused]] const CChannel& channel) { return false; } - - private: - bool ReceiveMessage(CListeners& listeners); - bool ReceiveNotification(CListeners& listeners); - - protected: - CNotificationNetwork* m_pNotificationNetwork; - - char m_address[16]; - uint16 m_port; - - AZSOCKET m_socket; - - uint8 m_bufferHeader[NN_PACKET_HEADER_LENGTH]; - SBuffer m_buffer; - uint32 m_dataLeft; - - volatile bool m_boIsConnected; - volatile bool m_boIsFailedToConnect; - }; - - class CClient - : public CConnectionBase - , public INotificationNetworkClient - { - public: - typedef std::vector TDNotificationNetworkConnectionCallbacks; - - static CClient* Create(CNotificationNetwork* pNotificationNetwork, const char* address, uint16 port); - static CClient* Create(CNotificationNetwork* pNotificationNetwork); - - private: - CClient(CNotificationNetwork* pNotificationNetwork); - ~CClient(); - - public: - bool Receive() { return CConnectionBase::Receive(m_listeners); } - - void Update(); - - // CConnectionBase - public: - virtual bool OnConnect(bool bConnectionResult); - virtual bool OnDisconnect(); - virtual bool OnMessage(EMessage eMessage, const CChannel& channel); - - // INotificationNetworkClient - public: - bool Connect(const char* address, uint16 port); - - void Release() { delete this; } - - virtual bool ListenerBind(const char* channelName, INotificationNetworkListener* pListener); - virtual bool ListenerRemove(INotificationNetworkListener* pListener); - - virtual bool Send(const char* channelName, const void* pBuffer, size_t length); - - virtual bool IsConnected() {return CConnectionBase::GetIsConnectedFlag(); } - virtual bool IsFailedToConnect() const{return CConnectionBase::GetIsFailedToConnectFlag(); } - - virtual bool RegisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback); - virtual bool UnregisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback); - private: - CListeners m_listeners; - - TDNotificationNetworkConnectionCallbacks m_cNotificationNetworkConnectionCallbacks; - CryCriticalSection m_stConnectionCallbacksLock; - }; -} // namespace NotificationNetwork -class CNotificationNetwork - : public INotificationNetwork -{ -private: - class CConnection - : public NotificationNetwork::CConnectionBase - { - public: - CConnection(CNotificationNetwork* pNotificationNetwork, AZSOCKET sock); - virtual ~CConnection(); - - public: - bool IsListening(const NotificationNetwork::CChannel& channel); - - // CConnectionBase - protected: - virtual bool OnMessage(NotificationNetwork::EMessage eMessage, const NotificationNetwork::CChannel& channel); - - private: - std::vector m_listeningChannels; - }; - - class CThread - : public CryThread - { - public: - CThread(); - ~CThread(); - - public: - bool Begin(CNotificationNetwork* pNotificationNetwork); - void End(); - - // CryRunnable - public: - virtual void Run(); - - private: - CNotificationNetwork* m_pNotificationNetwork; - bool m_bRun; - } m_thread; - -public: - static CNotificationNetwork* Create(); - -public: - CNotificationNetwork(); - ~CNotificationNetwork(); - -public: - void ReleaseClients(NotificationNetwork::CClient* pClient); - -private: - void ProcessSockets(); - - // INotificationNetwork -public: - virtual void Release() { delete this; } - - virtual INotificationNetworkClient* CreateClient(); - - virtual INotificationNetworkClient* Connect(const char* address, uint16 port); - - virtual size_t GetConnectionCount(const char* channelName); - - virtual void Update(); - - virtual bool ListenerBind(const char* channelName, INotificationNetworkListener* pListener); - virtual bool ListenerRemove(INotificationNetworkListener* pListener); - - virtual uint32 Send(const char* channelName, const void* pBuffer, size_t length); - -private: - AZSOCKET m_socket; - - std::vector m_connections; - std::vector m_clients; - NotificationNetwork::CListeners m_listeners; - - CryCriticalSection m_clientsCriticalSection; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_NOTIFICATIONNETWORK_H diff --git a/Code/CryEngine/CrySystem/ProfileLogSystem.cpp b/Code/CryEngine/CrySystem/ProfileLogSystem.cpp deleted file mode 100644 index 2a86dfc2ef..0000000000 --- a/Code/CryEngine/CrySystem/ProfileLogSystem.cpp +++ /dev/null @@ -1,134 +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 "CrySystem_precompiled.h" -#include "ProfileLogSystem.h" - -////////////////////////////////////////////////////////////////////////// -// class CLogElement -////////////////////////////////////////////////////////////////////////// - -CLogElement::CLogElement() - : m_pParent (NULL) - , m_time (0) -{ -} - -CLogElement::CLogElement(CLogElement* pParent) - : m_pParent (pParent) - , m_time (0) -{ -} - -CLogElement::CLogElement(CLogElement* pParent, const char* name, const char* message) - : m_pParent (pParent) - , m_strName (name) - , m_strMessage(message) - , m_time (0) -{ -} - -void CLogElement::Flush(stack_string& indent) -{ - if (m_logElements.empty()) - { - CryLog("%s%s [%.3f ms] %s", indent.c_str(), m_strName.c_str(), m_time, m_strMessage.c_str()); - return; - } - - CryLog("%s+%s [%.3f ms] %s", indent.c_str(), m_strName.c_str(), m_time, m_strMessage.c_str()); - - indent += " "; - for (std::list::iterator it = m_logElements.begin(); it != m_logElements.end(); ++it) - { - (*it).Flush(indent); - } - indent.erase(0, 2); - - CryLog("%s-%s", indent.c_str(), m_strName.c_str()); -} - -ILogElement* CLogElement::Log(const char* name, const char* message) -{ - m_logElements.push_back(CLogElement(this)); - m_logElements.back().m_strName = name; - m_logElements.back().m_strMessage = message; - - return &m_logElements.back(); -} - -ILogElement* CLogElement::SetTime(float time) -{ - m_time = time; - - return m_pParent; -} - -void CLogElement::Clear() -{ - m_logElements.resize(0); -} - -////////////////////////////////////////////////////////////////////////// -// class CProfileLogSystem -////////////////////////////////////////////////////////////////////////// - -CProfileLogSystem::CProfileLogSystem() - : m_rootElelent(NULL) - , m_pLastElelent(NULL) -{ -} - -CProfileLogSystem::~CProfileLogSystem() -{ -} - -ILogElement* CProfileLogSystem::Log(const char* name, const char* message) -{ - if (m_pLastElelent) - { - m_pLastElelent = m_pLastElelent->Log(name, message); - } - else - { - m_rootElelent.Clear(); - m_rootElelent.SetName(name); - m_rootElelent.SetMessage(message); - m_pLastElelent = &m_rootElelent; - } - - return m_pLastElelent; -} - -void CProfileLogSystem::SetTime(ILogElement* pElement, float time) -{ - if (pElement == NULL) - { - return; - } - - m_pLastElelent = pElement->SetTime(time); - if (m_pLastElelent) - { - return; - } - - stack_string indent; - m_rootElelent.Flush(indent); - m_rootElelent.Clear(); -} - -void CProfileLogSystem::Release() -{ - delete this; -} diff --git a/Code/CryEngine/CrySystem/ProfileLogSystem.h b/Code/CryEngine/CrySystem/ProfileLogSystem.h deleted file mode 100644 index b54e3067ec..0000000000 --- a/Code/CryEngine/CrySystem/ProfileLogSystem.h +++ /dev/null @@ -1,74 +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 the IProfileLogSystem interface, which is used to -// save hierarchical log with SHierProfileLogItem - - -#ifndef CRYINCLUDE_CRYSYSTEM_PROFILELOGSYSTEM_H -#define CRYINCLUDE_CRYSYSTEM_PROFILELOGSYSTEM_H - -#pragma once - -#include "ProfileLog.h" - -class CLogElement - : public ILogElement -{ -public: - CLogElement(); - CLogElement(CLogElement* pParent); - CLogElement(CLogElement* pParent, const char* name, const char* message); - - virtual ILogElement* Log (const char* name, const char* message); - virtual ILogElement* SetTime (float time); - virtual void Flush (stack_string& indent); - - void Clear (); - - inline void SetName(const char* name) - { - m_strName = name; - } - - inline void SetMessage(const char* message) - { - m_strMessage = message; - } - -private: - string m_strName; - string m_strMessage; - float m_time; // milliSeconds - - CLogElement* m_pParent; - std::list m_logElements; -}; - -class CProfileLogSystem - : public IProfileLogSystem -{ -public: - CProfileLogSystem(); - ~CProfileLogSystem(); - - virtual ILogElement* Log (const char* name, const char* message); - virtual void SetTime (ILogElement* pElement, float time); - virtual void Release (); - -private: - CLogElement m_rootElelent; - ILogElement* m_pLastElelent; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_PROFILELOGSYSTEM_H diff --git a/Code/CryEngine/CrySystem/ResourceManager.cpp b/Code/CryEngine/CrySystem/ResourceManager.cpp index f78538760f..5e9477a99c 100644 --- a/Code/CryEngine/CrySystem/ResourceManager.cpp +++ b/Code/CryEngine/CrySystem/ResourceManager.cpp @@ -699,7 +699,7 @@ void CResourceManager::OnSystemEvent(ESystemEvent event, [[maybe_unused]] UINT_P if (g_cvars.archiveVars.nLoadCache) { //Load the frontend common mode switch pak, this can considerably reduce the time spent switching especially from disc - if (!gEnv->bMultiplayer && LoadMenuCommonPak(FRONTEND_COMMON_PAK_FILENAME_SP) == false) + if (LoadMenuCommonPak(FRONTEND_COMMON_PAK_FILENAME_SP) == false) { CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "Could not load %s during init. This file can significantly reduce frontend loading times.\n", FRONTEND_COMMON_PAK_FILENAME_SP); } @@ -710,14 +710,7 @@ void CResourceManager::OnSystemEvent(ESystemEvent event, [[maybe_unused]] UINT_P case ESYSTEM_EVENT_LEVEL_LOAD_PREPARE: { - if (!gEnv->bMultiplayer) - { - UnloadMenuCommonPak(FRONTEND_COMMON_PAK_FILENAME_SP, FRONTEND_COMMON_LIST_FILENAME "_sp"); - } - else - { - UnloadMenuCommonPak(FRONTEND_COMMON_PAK_FILENAME_MP, FRONTEND_COMMON_LIST_FILENAME "_mp"); - } + UnloadMenuCommonPak(FRONTEND_COMMON_PAK_FILENAME_SP, FRONTEND_COMMON_LIST_FILENAME "_sp"); m_bLevelTransitioning = !m_sLevelName.empty(); diff --git a/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.cpp b/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.cpp deleted file mode 100644 index 9e141cc5a5..0000000000 --- a/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.cpp +++ /dev/null @@ -1,787 +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 "CrySystem_precompiled.h" - -#ifdef SOFTCODE_SYSTEM_ENABLED - -#ifndef SOFTCODE_ENABLED -// Even if this module isn't built with SC enabled, if the SC system is enabled we define -// it for this compilation unit to ensure we use the correct versions of the IType* interfaces. - #define SOFTCODE_ENABLED -#endif - -#include "SoftCodeMgr.h" -#include -#include -#include -#include // for function<> in find files - -// This should resolve to "GetTypeLibrary" but we export by ordinal to avoid overheads on 360 -// and keep everything consistent. -static const char* DLL_GETTYPELIBRARY = (LPCSTR)1; - -struct CInstanceData -{ - CInstanceData(void* pInstance, size_t memberCount) - : m_pOldInstance(pInstance) - , m_pNewInstance() - { - m_members.resize(memberCount); - } - - ~CInstanceData() - { - // Delete all members - for (TMemberVec::iterator iter(m_members.begin()); - iter != m_members.end(); - ++iter) - { - // TODO: Safe cross module? Same allocator? Use a Destroy() method? - delete *iter; - } - } - - void* Instance() { return m_pOldInstance; } - - void AddMember(size_t index, IExchangeValue& value) - { - // TODO: Add support for members with same name at different hierarchy levels - assert(m_members[index] == NULL); - assert(index != ~0); - - // Support expansion of m_members during while resolving members - if (index >= m_members.size()) - { - m_members.resize(index + 1); - } - - m_members[index] = value.Clone(); - } - - IExchangeValue* GetMember(size_t index) const - { - assert(index < m_members.size()); - return m_members[index]; - } - - void SetNewInstance(void* pNewInstance) { m_pNewInstance = pNewInstance; } - - void* m_pOldInstance; - void* m_pNewInstance; - - typedef std::vector TMemberVec; - TMemberVec m_members; -}; - - -class CExchanger - : public IExchanger -{ -public: - CExchanger() - : m_pInstanceData() - , m_instanceIndex(~0) - , m_state(eState_ResolvingMembers) - {} - - virtual ~CExchanger() - { - DestroyInstanceData(); - } - - virtual bool IsLoading() const { return m_state >= eState_WritingNewMembers; } - virtual size_t InstanceCount() const { return m_instances.size(); } - - virtual bool BeginInstance(void* pInstance) - { - if (IsLoading()) - { - if (++m_instanceIndex < m_instances.size()) - { - m_pInstanceData = m_instances[m_instanceIndex]; - m_pInstanceData->SetNewInstance(pInstance); - } - else - { - m_pInstanceData = NULL; - } - } - else // Reading/resolving members - { - m_instanceIndex = m_instances.size(); - m_pInstanceData = new CInstanceData(pInstance, m_memberMap.size()); - m_instances.push_back(m_pInstanceData); - } - - return m_pInstanceData != NULL; - } - - virtual bool SetValue(const char* name, IExchangeValue& value) - { - assert(!IsLoading()); - - const size_t index = FindMemberIndex(name); - const bool consumingValue = index != ~0; - - if (consumingValue) - { - m_pInstanceData->AddMember(index, value); - } - - return consumingValue; - } - - virtual IExchangeValue* GetValue(const char* name, void* pTarget, size_t targetSize) - { - assert(IsLoading()); - - const size_t index = FindMemberIndex(name); - - // If member resolved (may not be if restoring to old instances) - if (index != ~0) - { - // If member data available (may not be if member is new) - if (IExchangeValue* pValue = m_pInstanceData->GetMember(index)) - { - if (pValue->GetSizeOf() == targetSize) - { - return pValue; - } - else // Member size mismatch - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, - "SoftCode: Member %s of instance %p has changed size (old: %d new: %d), setting to default value.", - name, m_pInstanceData->Instance(), (int)pValue->GetSizeOf(), (int)targetSize); - } - } - else // Member unknown - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, - "SoftCode: Member %s (of instance %p) appears to be new.", - name, m_pInstanceData->Instance()); - - // TODO: Could attempt to validate against a known wipe pattern ie. 0xfefefefe - // This could catch most uninitialized variables... - - if (targetSize <= sizeof(void*)) - { - switch (targetSize) - { - case 1: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "\tLeaving as: %d", *reinterpret_cast(pTarget)); - break; - case 2: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "\tLeaving as: %04x", *reinterpret_cast(pTarget)); - break; - case 4: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "\tLeaving as: %08x", *reinterpret_cast(pTarget)); - break; - case 8: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "\tLeaving as: %llx", *reinterpret_cast(pTarget)); - break; - } - } - } - } - - // Indicate value should be default constructed - return NULL; - } - - // Used once required members have been established, members not already - // encountered will be ignored. - void LockMemberSet() - { - assert(m_state == eState_ResolvingMembers); - - DestroyInstanceData(); - m_state = eState_ReadingOldMembers; - } - - // Rewinds instance data and prepare for loading - void RewindForLoading() - { - assert(m_state == eState_ReadingOldMembers); - - m_pInstanceData = NULL; - m_instanceIndex = ~0; - m_state = eState_WritingNewMembers; - } - - // Rewinds instance data to prepare to restore old members (UNDO) - void RewindForRestore() - { - assert(m_state == eState_WritingNewMembers); - - m_pInstanceData = NULL; - m_instanceIndex = ~0; - m_state = eState_RestoringOldMembers; - } - - void NotifyListenerOfReplacements(ISoftCodeListener* pListener) - { - for (TInstanceVec::const_iterator iter(m_instances.begin()); iter != m_instances.end(); ++iter) - { - CInstanceData* pInstanceData = *iter; - pListener->InstanceReplaced(pInstanceData->m_pOldInstance, pInstanceData->m_pNewInstance); - } - } - -private: - void DestroyInstanceData() - { - m_pInstanceData = NULL; - m_instanceIndex = ~0; - - for (TInstanceVec::iterator iter(m_instances.begin()); iter != m_instances.end(); ++iter) - { - delete *iter; - } - - m_instances.resize(0); - } - - inline size_t FindMemberIndex(const string& memberName) - { - size_t index = ~0; - - // If needed members have been resolved - if (m_state != eState_ResolvingMembers) - { - TMemberMap::const_iterator iter(m_memberMap.find(memberName)); - if (iter != m_memberMap.end()) - { - index = iter->second; - } - } - else // Add this member to the map with a new index - { - // Ensure there's no member name duplicates - assert(m_memberMap.find(memberName) == m_memberMap.end()); - - // A new entry - index = m_memberMap.size(); - size_t& newIndex = m_memberMap[memberName]; - newIndex = index; - } - - return index; - } - -private: - CInstanceData* m_pInstanceData; - size_t m_instanceIndex; - - typedef std::vector TInstanceVec; - TInstanceVec m_instances; - - // Maps instance members to offsets in instance member vectors - typedef std::map TMemberMap; - TMemberMap m_memberMap; - - enum EState - { - eState_ResolvingMembers = 0, // Record new member names as found - eState_ReadingOldMembers, // Scrape requested member data from old instances - eState_WritingNewMembers, // Write old member data to new instances - eState_RestoringOldMembers, // Restore scraped values to old instances (UNDO) - }; - - EState m_state; -}; - - -// ---- - -DynamicTypeLibrary::DynamicTypeLibrary(const char* name) - : m_name(name) - , m_listeners(1) -{} - -const char* DynamicTypeLibrary::GetName() -{ - return m_name; -} - -void* DynamicTypeLibrary::CreateInstanceVoid(const char* typeName) -{ - TTypeMap::const_iterator typeIter(m_types.find(typeName)); - if (typeIter != m_types.end()) - { - ITypeRegistrar* pRegistrar = typeIter->second; - return pRegistrar->CreateInstance(); - } - - return NULL; -} - -void DynamicTypeLibrary::SetOverride(ITypeLibrary* /*pOverrideLib*/) -{ - CryFatalError("Unsupported: Attempting to SetOverride on a DynamicTypeLibrary!"); -} - -size_t DynamicTypeLibrary::GetTypes([[maybe_unused]] ITypeRegistrar** ppRegistrar, [[maybe_unused]] size_t& count) const -{ - CryFatalError("Unsupported: Attempting to GetTypes on a DynamicTypeLibrary!"); - return 0; -} - -void DynamicTypeLibrary::AddListener(const char* libraryName, ISoftCodeListener* pListener, const char* listenerName) -{ - // This DynamicTypeLibrary could have been created by this listener request - // So ensure we have a name...! - if (!m_name) - { - m_name = libraryName; - } - - m_listeners.Add(pListener, listenerName); -} - -void DynamicTypeLibrary::RemoveListener(ISoftCodeListener* pListener) -{ - m_listeners.Remove(pListener); -} - -void DynamicTypeLibrary::IntegrateLibrary(ITypeLibrary* pLib, bool isDefault) -{ - typedef std::vector TTypeVec; - - // Resolve our name if we haven't already - if (!m_name) - { - m_name = pLib->GetName(); - } - - // Override the new lib immediately - pLib->SetOverride(this); - - // Query the new library for its types - size_t typeCount = 0; - pLib->GetTypes(NULL, typeCount); - if (typeCount > 0) - { - TTypeVec typeVec; - typeVec.resize(typeCount); - pLib->GetTypes(&(typeVec.front()), typeCount); - - if (!isDefault) - { - CryLogAlways("SoftCode: Integrating %d new types defined in %s...", (int)typeCount, m_name); - } - - // Attempt to integrate each type found - for (TTypeVec::iterator typeIter(typeVec.begin()); typeIter != typeVec.end(); ++typeIter) - { - IntegrateType(*typeIter, isDefault); - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "SoftCode: New %s library has no registered types. Nothing to integrate.", pLib->GetName()); - } -} - -ITypeRegistrar* DynamicTypeLibrary::FindTypeForInstance(void* pInstance) const -{ - for (TTypeMap::const_iterator iter(m_types.begin()); iter != m_types.end(); ++iter) - { - ITypeRegistrar* pType = iter->second; - if (pType->HasInstance(pInstance)) - { - return pType; - } - } - - return NULL; -} - -void DynamicTypeLibrary::IntegrateType(ITypeRegistrar* pType, bool isDefault) -{ - const char* typeName = pType->GetName(); - - // If there's an existing registrar - ITypeRegistrar* pExistingType = m_types[typeName]; - assert(pExistingType != pType); // Sanity check - - // If the new type is the default (built-in) type but it's already been overridden - if (isDefault && pExistingType) - { - return; // Nothing to do - } - // TODO: Inform listeners that there's a new library available - // and ask if we should use it immediately or defer - - CExchanger exchanger; - - // If the type can be safely created, visited and destroyed - if (EvaluateType(pType, exchanger)) - { - // Override the type - m_types[typeName] = pType; - - if (!isDefault) - { - CryLogAlways("SoftCode: Overridden %s in library %s", typeName, m_name); - } - - const size_t instanceCount = (pExistingType) ? pExistingType->InstanceCount() : 0; - - // If there are any existing instances - if (instanceCount > 0) - { - CryLogAlways("SoftCode: Attempting to exchange %d %s instances to the new version...", (int)instanceCount, typeName); - - // Read instance members for type (removes data for resolved members) - if (pExistingType->ExchangeInstances(exchanger)) - { - exchanger.RewindForLoading(); - - // Write instance members for type - if (pType->ExchangeInstances(exchanger)) - { - // Success! Tell the listeners to fix up their pointers - for (TListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next()) - { - exchanger.NotifyListenerOfReplacements(*notifier); - } - - CryLogAlways("SoftCode: %d %s instances successfully overridden to latest!", (int)instanceCount, typeName); - - // Clean up old instances - if (!pExistingType->DestroyInstances()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "SoftCode: Failed to destroy old instances of type %s - leak probable.", typeName); - } - } - else // Failed to create & write into new instances - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to create and write into new instances of %s. Attempting restore of old instances...", typeName); - if (!pType->DestroyInstances()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "SoftCode: Failed to destroy new instances of type %s - leak probable.", typeName); - } - - // Restore the original type library as the active one - m_types[typeName] = pExistingType; - - // Attempt to restore the old instances with their original data - exchanger.RewindForRestore(); - if (pExistingType->ExchangeInstances(exchanger)) - { - CryLogAlways("SoftCode: Type %s in library %s successfully restored to previous revision!", typeName, m_name); - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Restore of old %s instances failed. State now undefined!", typeName); - } - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to read members on %s", typeName); - } - } - } -} - -bool DynamicTypeLibrary::EvaluateType(ITypeRegistrar* pType, CExchanger& exchanger) -{ - // Try a full object life-time with a single instance of the - // new type before attempting a member exchange. This also allow the - // exchanger to determine the required members to be removed from the - // old instances. - bool testPassed = false; - - // Create a single test instance of the type - if (pType->CreateInstance()) - { - // Read the instance members (also prepares the exchanger member set) - if (pType->ExchangeInstances(exchanger)) - { - // Destroy the old instance - if (pType->DestroyInstances()) - { - // Indicate required members are now resolved - exchanger.LockMemberSet(); - testPassed = true; - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to destroy test instance of type: %s. New type will be skipped.", pType->GetName()); - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to read members in test instance of type: %s. New type will be skipped.", pType->GetName()); - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to create test instance of type: %s. New type will be skipped.", pType->GetName()); - } - - return testPassed; -} - -// ---- - -// The export we expect to find in the SoftCode modules -typedef ITypeLibrary* (__stdcall * TGetTypeLibraryFcn)(); - -static void SoftCode_UpdateCmd([[maybe_unused]] IConsoleCmdArgs* pArgs) -{ - gEnv->pSoftCodeMgr->LoadNewModules(); -} - -static int g_autoUpdatePeriod = 0; - -SoftCodeMgr::SoftCodeMgr() -{ - REGISTER_CVAR2("sc_autoupdate", &g_autoUpdatePeriod, 5, VF_CHEAT, "Set the auto-update poll period for new SoftCode modules. Set to zero to disable"); - REGISTER_COMMAND("sc_update", reinterpret_cast(&SoftCode_UpdateCmd), VF_CHEAT, "Loads any new SoftCode modules"); - - // Clear out any old modules - { - typedef std::vector TStringVec; - TStringVec filePaths; - - if (FindSoftCodeFiles("*", filePaths) > 0) - { - for (TStringVec::const_iterator iter(filePaths.begin()); iter != filePaths.end(); ++iter) - { - if (!DeleteFile(iter->c_str())) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to clean %s", iter->c_str()); - } - } - } - } -} - -SoftCodeMgr::~SoftCodeMgr() -{ - if (gEnv->pConsole) - { - gEnv->pConsole->RemoveCommand("sc_update"); - gEnv->pConsole->UnregisterVariable("sc_autoupdate"); - } -} - -// Used to register built-in libraries on first use -void SoftCodeMgr::RegisterLibrary(ITypeLibrary* pDefaultLib) -{ - DynamicTypeLibrary& typeLib = m_libraryMap[pDefaultLib->GetName()]; - typeLib.IntegrateLibrary(pDefaultLib, true); -} - -// Look for new SoftCode modules and load them, adding their types to the registry -void SoftCodeMgr::LoadNewModules() -{ - typedef std::vector TStringVec; - typedef TStringVec::const_iterator TModuleIter; - TStringVec modulePaths; - - // Find modules - FindSoftCodeFiles("*.dll", modulePaths); - - for (TModuleIter libIter(modulePaths.begin()); libIter != modulePaths.end(); ++libIter) - { - const char* moduleName = libIter->c_str(); - LoadModule(moduleName); - } -} - -void SoftCodeMgr::AddListener(const char* libraryName, ISoftCodeListener* pListener, const char* listenerName) -{ - // Find an existing lib or create a new one to add the listener to - DynamicTypeLibrary& lib = m_libraryMap[libraryName]; - lib.AddListener(libraryName, pListener, listenerName); -} - -void SoftCodeMgr::RemoveListener(const char* libraryName, ISoftCodeListener* pListener) -{ - TLibMap::iterator iter(m_libraryMap.find(libraryName)); - - if (iter != m_libraryMap.end()) - { - iter->second.RemoveListener(pListener); - } -} - -// To be called regularly to poll for library updates -void SoftCodeMgr::PollForNewModules() -{ - if (g_autoUpdatePeriod > 0) - { - const CTimeValue frameStartTime(gEnv->pTimer->GetFrameStartTime(ITimer::ETIMER_UI)); - if (m_nextAutoCheckTime <= frameStartTime) - { - m_nextAutoCheckTime.SetSeconds((int64)g_autoUpdatePeriod); - m_nextAutoCheckTime += frameStartTime; - - // Attempt to find and load any new modules - LoadNewModules(); - } - } -} - -namespace -{ - // Util - class InstanceFixup - : public ISoftCodeListener - { - public: - InstanceFixup(void* pOldInstance) - : m_pOldInstance(pOldInstance) - , m_pNewInstance() {} - - virtual void InstanceReplaced(void* pOldInstance, void* pNewInstance) - { - if (m_pOldInstance == pOldInstance) - { - m_pNewInstance = pNewInstance; - } - } - - void* NewInstance() const { return m_pNewInstance; } - - private: - void* m_pOldInstance; - void* m_pNewInstance; - }; -} - -// Stops thread execution until a new SoftCode module is available -void* SoftCodeMgr::WaitForUpdate(void* pInstance) -{ - DynamicTypeLibrary* pOwningLib = NULL; - ITypeRegistrar* pOldType = NULL; - - // Find existing instance - for (TLibMap::iterator libIter(m_libraryMap.begin()); libIter != m_libraryMap.end(); ++libIter) - { - DynamicTypeLibrary& lib = libIter->second; - if (ITypeRegistrar* pType = lib.FindTypeForInstance(pInstance)) - { - pOwningLib = &lib; - pOldType = pType; - break; - } - } - - if (!pOwningLib) - { - CryFatalError("SoftCode: Attempting to wait for update on an unknown instance!"); - return NULL; - } - - InstanceFixup instanceFixup(pInstance); - pOwningLib->AddListener(pOwningLib->GetName(), &instanceFixup, "InstanceFixup"); - - while (true) - { - // Find and load new modules - LoadNewModules(); - - // Got a new instance? - if (instanceFixup.NewInstance()) - { - break; - } - - // Wait for a new module - CryLogAlways("SoftCode: Pausing execution until class %s in %s library is updated...", pOldType->GetName(), pOwningLib->GetName()); - __debugbreak(); // Stopped here? Check your log! - } - - pOwningLib->RemoveListener(&instanceFixup); - - return instanceFixup.NewInstance(); -} - -bool SoftCodeMgr::LoadModule(const char* moduleName) -{ - bool success = false; - - // If module not yet loaded - if (m_loadedSet.find(moduleName) == m_loadedSet.end()) - { - m_loadedSet.insert(moduleName); - - CryLogAlways("SoftCode: Found new module %s, attempting to load...", moduleName); - - HMODULE hModule = CryLoadLibrary(moduleName); - - if (hModule) - { - TGetTypeLibraryFcn pGetTypeLibraryFcn = reinterpret_cast(GetProcAddress(hModule, DLL_GETTYPELIBRARY)); - if (pGetTypeLibraryFcn) - { - // Add to list of loaded libs & override any earlier TypeLibraries already registered - ITypeLibrary* pTypeLibrary = pGetTypeLibraryFcn(); - if (pTypeLibrary) - { - const char* libraryName = pTypeLibrary->GetName(); - m_libraryMap[libraryName].IntegrateLibrary(pTypeLibrary, false); - - CryLogAlways("SoftCode: Loaded new type library \"%s\" from module %s.", libraryName, moduleName); - success = true; - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Failed to resolve GetTypeLibrary() export in: %s (error: %x)", moduleName, GetLastError()); - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Failed to load: %s (error: %x)", moduleName, GetLastError()); - } - } - - return success; -} - -size_t SoftCodeMgr::FindSoftCodeFiles(const string& searchName, std::vector& foundPaths) const -{ - foundPaths.clear(); - - stack_string scSoftCodeDir; - - TCHAR modulePath[MAX_PATH]; - GetModuleFileName(NULL, modulePath, sizeof(modulePath)); - scSoftCodeDir = PathUtil::GetParentDirectory(modulePath); - scSoftCodeDir += "\\SoftCode\\"; - - - gEnv->pFileIO->FindFiles(scSoftCodeDir.c_str(), searchName, [&](const char* filePath) -> bool - { - if (!gEnv->pFileIO->IsDirectory(filePath) && !gEnv->pFileIO->IsReadOnly(filePath)) - { - foundPaths.push_back(filePath); - } - - // Keep asking for more files, no early out - return true; - }); - - // Sort the paths into name order - std::sort(foundPaths.begin(), foundPaths.end()); - - return foundPaths.size(); -} - -#endif // SOFTCODE_ENABLED diff --git a/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.h b/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.h deleted file mode 100644 index f3f1b931a5..0000000000 --- a/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.h +++ /dev/null @@ -1,111 +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_CRYSYSTEM_SOFTCODE_SOFTCODEMGR_H -#define CRYINCLUDE_CRYSYSTEM_SOFTCODE_SOFTCODEMGR_H -#pragma once - -#include - -#include "ISoftCodeMgr.h" - -struct ITypeLibrary; -struct ITypeRegistrar; -class CExchanger; - -// Internal: Performs the dynamic type management needed for SoftCoding -class DynamicTypeLibrary - : public ITypeLibrary -{ -public: - DynamicTypeLibrary(const char* name = NULL); - - // ITypeLibrary impl. - virtual const char* GetName(); - virtual void* CreateInstanceVoid(const char* typeName); - virtual void SetOverride(ITypeLibrary* pOverrideLib); - virtual size_t GetTypes(ITypeRegistrar** ppRegistrar, size_t& count) const; - - void AddListener(const char* libraryName, ISoftCodeListener* pListener, const char* listenerName); - void RemoveListener(ISoftCodeListener* pListener); - - // Attempts to add the library types the active set - void IntegrateLibrary(ITypeLibrary* pLib, bool isDefault); - - ITypeRegistrar* FindTypeForInstance(void* pInstance) const; - -private: - // Attempts to add the type the active set - void IntegrateType(ITypeRegistrar* pType, bool isDefault); - // Ensure the type can be safely created, visited, destroyed and prep exchanger - bool EvaluateType(ITypeRegistrar* pType, CExchanger& exchanger); - -private: - typedef std::vector TLibVec; - typedef std::map TTypeMap; - typedef CListenerSet TListeners; - - // The current set of active types - std::map m_types; - // Current set of loaded libraries - TLibVec m_history; - // Set of listeners to SC changes - TListeners m_listeners; - - const char* m_name; // Supplied by the first real library that registers -}; - - -// Implements the global singleton responsible for SoftCode management -class SoftCodeMgr - : public ISoftCodeMgr -{ -public: - SoftCodeMgr(); - virtual ~SoftCodeMgr(); - - // Used to register built-in libraries on first use - virtual void RegisterLibrary(ITypeLibrary* pLib); - - // Look for new SoftCode modules and load them, adding their types to the registry - virtual void LoadNewModules(); - - virtual void AddListener(const char* libraryName, ISoftCodeListener* pListener, const char* listenerName); - virtual void RemoveListener(const char* libraryName, ISoftCodeListener* pListener); - - // To be called regularly to poll for library updates - virtual void PollForNewModules(); - - // Stops thread execution until a new SoftCode module is available - virtual void* WaitForUpdate(void* pInstance); - -private: - bool LoadModule(const char* moduleName); - size_t FindSoftCodeFiles(const string& searchName, std::vector& foundPaths) const; - -private: - typedef std::map TLibMap; - typedef std::set TLoadedLibSet; - - // Records the history for each TypeLibrary keyed by library name - TLibMap m_libraryMap; - - // Records the library files already loaded - TLoadedLibSet m_loadedSet; - - // Used to determine when the next auto-update will occur - CTimeValue m_nextAutoCheckTime; -}; - - -#endif // CRYINCLUDE_CRYSYSTEM_SOFTCODE_SOFTCODEMGR_H diff --git a/Code/CryEngine/CrySystem/System.cpp b/Code/CryEngine/CrySystem/System.cpp index 8a8cf14d91..9016ea99f1 100644 --- a/Code/CryEngine/CrySystem/System.cpp +++ b/Code/CryEngine/CrySystem/System.cpp @@ -124,8 +124,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include #include #include -#include -#include #include #include @@ -133,8 +131,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include #include "XConsole.h" #include "Log.h" -#include "NotificationNetwork.h" -#include "ProfileLog.h" #include "XML/xml.h" #include "XML/ReadWriteXMLSink.h" @@ -148,7 +144,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include "ServerThrottle.h" #include "ResourceManager.h" #include "HMDBus.h" -#include #include "IZLibCompressor.h" #include "IZlibDecompressor.h" @@ -267,22 +262,6 @@ namespace } #endif -#if defined(CVARS_WHITELIST) -struct SCVarsWhitelistConfigSink - : public ILoadConfigurationEntrySink -{ - virtual void OnLoadConfigurationEntry(const char* szKey, const char* szValue, const char* szGroup) - { - ICVarsWhitelist* pCVarsWhitelist = gEnv->pSystem->GetCVarsWhiteList(); - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(szKey, false) : true; - if (whitelisted) - { - gEnv->pConsole->LoadConfigVar(szKey, szValue); - } - } -} g_CVarsWhitelistConfigSink; -#endif // defined(CVARS_WHITELIST) - ///////////////////////////////////////////////////////////////////////////////// // System Implementation. ////////////////////////////////////////////////////////////////////////// @@ -322,27 +301,13 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_env.pSystem = this; m_env.pTimer = &m_Time; m_env.pNameTable = &m_nameTable; - m_env.bServer = false; - m_env.bMultiplayer = false; - m_env.bHostMigrating = false; m_env.bIgnoreAllAsserts = false; m_env.bNoAssertDialog = false; - m_env.bTesting = false; m_env.pSharedEnvironment = pSharedEnvironment; - - m_env.SetFMVIsPlaying(false); - m_env.SetCutsceneIsPlaying(false); - - m_env.szDebugStatus[0] = '\0'; - -#if !defined(CONSOLE) - m_env.SetIsClient(false); -#endif ////////////////////////////////////////////////////////////////////////// m_pStreamEngine = NULL; - m_PhysThread = 0; m_pIFont = NULL; m_pIFontUi = NULL; @@ -370,7 +335,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_pILZ4Decompressor = NULL; m_pIZStdDecompressor = nullptr; m_pLocalizationManager = NULL; - m_sys_physics_CPU = 0; #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_2 #include AZ_RESTRICTED_FILE(System_cpp) @@ -378,15 +342,9 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_sys_min_step = 0; m_sys_max_step = 0; - m_pNotificationNetwork = NULL; - m_cvAIUpdate = NULL; m_pUserCallback = NULL; -#if defined(CVARS_WHITELIST) - m_pCVarsWhitelist = NULL; - m_pCVarsWhitelistConfigSink = &g_CVarsWhitelistConfigSink; -#endif // defined(CVARS_WHITELIST) m_sys_memory_debug = NULL; m_sysWarnings = NULL; m_sysKeyboard = NULL; @@ -409,13 +367,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_bNoCrashDialog = false; m_bNoErrorReportWindow = false; -#ifndef _RELEASE - m_checkpointLoadCount = 0; - m_loadOrigin = eLLO_Unknown; - m_hasJustResumed = false; - m_expectingMapCommand = false; -#endif - m_pCVarQuit = NULL; m_bForceNonDevMode = false; @@ -429,13 +380,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_nServerConfigSpec = CONFIG_VERYHIGH_SPEC; m_nMaxConfigSpec = CONFIG_VERYHIGH_SPEC; - //m_hPhysicsThread = INVALID_HANDLE_VALUE; - //m_hPhysicsActive = INVALID_HANDLE_VALUE; - //m_bStopPhysics = 0; - //m_bPhysicsActive = 0; - - m_pProgressListener = 0; - m_bPaused = false; m_bNoUpdate = false; m_nUpdateCounter = 0; @@ -444,12 +388,9 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_pXMLUtils = new CXmlUtils(this); m_pMemoryManager = CryGetIMemoryManager(); - m_pThreadTaskManager = new CThreadTaskManager; m_pResourceManager = new CResourceManager; m_pTextModeConsole = NULL; - InitThreadSystem(); - g_pPakHeap = new CMTSafeHeap; if (!AZ::AllocatorInstance::IsReady()) @@ -464,7 +405,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) AZ::Debug::Trace::Instance().Init(); } - m_UpdateTimesIdx = 0U; m_bNeedDoWorkDuringOcclusionChecks = false; m_eRuntimeState = ESYSTEM_EVENT_LEVEL_UNLOAD; @@ -478,15 +418,12 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) #endif m_ConfigPlatform = CONFIG_INVALID_PLATFORM; - - AzFramework::Terrain::TerrainDataNotificationBus::Handler::BusConnect(); } ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// CSystem::~CSystem() { - AzFramework::Terrain::TerrainDataNotificationBus::Handler::BusDisconnect(); ShutDown(); #if AZ_LEGACY_CRYSYSTEM_TRAIT_USE_MESSAGE_HANDLER @@ -496,16 +433,8 @@ CSystem::~CSystem() CRY_ASSERT(m_windowMessageHandlers.empty() && "There exists a dangling window message handler somewhere"); SAFE_DELETE(m_pXMLUtils); - SAFE_DELETE(m_pThreadTaskManager); SAFE_DELETE(m_pResourceManager); SAFE_DELETE(m_pSystemEventDispatcher); - // SAFE_DELETE(m_pMemoryManager); - - if (gEnv && gEnv->pThreadManager) - { - gEnv->pThreadManager->UnRegisterThirdPartyThread("Main"); - } - ShutDownThreadSystem(); SAFE_DELETE(g_pPakHeap); @@ -617,8 +546,6 @@ void CSystem::ShutDown() SAFE_DELETE(m_pTextModeConsole); - KillPhysicsThread(); - if (m_sys_firstlaunch) { m_sys_firstlaunch->Set("0"); @@ -664,8 +591,6 @@ void CSystem::ShutDown() gEnv->pLyShine = nullptr; } - SAFE_DELETE(m_env.pResourceCompilerHelper); - SAFE_RELEASE(m_env.pMovieSystem); SAFE_RELEASE(m_env.pLyShine); SAFE_RELEASE(m_env.pCryFont); @@ -706,7 +631,6 @@ void CSystem::ShutDown() SAFE_RELEASE(m_sys_GraphicsQuality); SAFE_RELEASE(m_sys_firstlaunch); SAFE_RELEASE(m_sys_enable_budgetmonitoring); - SAFE_RELEASE(m_sys_physics_CPU); #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_3 @@ -716,9 +640,6 @@ void CSystem::ShutDown() SAFE_RELEASE(m_sys_min_step); SAFE_RELEASE(m_sys_max_step); - SAFE_RELEASE(m_pNotificationNetwork); - - SAFE_DELETE(m_env.pSoftCodeMgr); SAFE_DELETE(m_pDefaultValidator); m_pValidator = nullptr; @@ -743,7 +664,6 @@ void CSystem::ShutDown() SAFE_RELEASE(m_env.pConsole); // Log must be last thing released. - SAFE_RELEASE(m_env.pProfileLogSystem); if (m_env.pLog) { m_env.pLog->FlushAndClose(); @@ -752,10 +672,6 @@ void CSystem::ShutDown() ShutdownFileSystem(); -#if defined(MAP_LOADING_SLICING) - delete gEnv->pSystemScheduler; -#endif // defined(MAP_LOADING_SLICING) - ShutdownModuleLibraries(); EBUS_EVENT(CrySystemEventBus, OnCrySystemPostShutdown); @@ -841,273 +757,6 @@ ISystem* CSystem::GetCrySystem() return this; } -////////////////////////////////////////////////////////////////////////// -// Physics thread task -////////////////////////////////////////////////////////////////////////// -class CPhysicsThreadTask - : public IThreadTask -{ -public: - - CPhysicsThreadTask() - { - m_bStopRequested = 0; - m_bIsActive = 0; - m_stepRequested = 0; - m_bProcessing = 0; - m_doZeroStep = 0; - m_lastStepTimeTaken = 0U; - m_lastWaitTimeTaken = 0U; - } - - ////////////////////////////////////////////////////////////////////////// - // IThreadTask implementation. - ////////////////////////////////////////////////////////////////////////// - virtual void OnUpdate() - { - Run(); - // At the end.. delete the task - delete this; - } - virtual void Stop() - { - Cancel(); - } - virtual SThreadTaskInfo* GetTaskInfo() { return &m_TaskInfo; } - ////////////////////////////////////////////////////////////////////////// - - virtual void Run() - { - m_bStopRequested = 0; - m_bIsActive = 1; - - float step, timeTaken, kSlowdown = 1.0f; - int nSlowFrames = 0; - int64 timeStart; -#ifdef ENABLE_LW_PROFILERS - LARGE_INTEGER stepStart, stepEnd; -#endif - LARGE_INTEGER waitStart, waitEnd; - MarkThisThreadForDebugging("Physics"); - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_5 -#include AZ_RESTRICTED_FILE(System_cpp) -#endif - while (true) - { - QueryPerformanceCounter(&waitStart); - m_FrameEvent.Wait(); // Wait untill new frame - QueryPerformanceCounter(&waitEnd); - m_lastWaitTimeTaken = waitEnd.QuadPart - waitStart.QuadPart; - - if (m_bStopRequested) - { - UnmarkThisThreadFromDebugging(); - return; - } - bool stepped = false; -#ifdef ENABLE_LW_PROFILERS - QueryPerformanceCounter(&stepStart); -#endif - while ((step = m_stepRequested) > 0 || m_doZeroStep) - { - stepped = true; - m_stepRequested = 0; - m_bProcessing = 1; - m_doZeroStep = 0; - - if (kSlowdown != 1.0f) - { - step = max(1, FtoI(step * kSlowdown * 50 - 0.5f)) * 0.02f; - } - timeStart = CryGetTicks(); - timeTaken = gEnv->pTimer->TicksToSeconds(CryGetTicks() - timeStart); - if (timeTaken > step * 0.9f) - { - if (++nSlowFrames > 5) - { - kSlowdown = step * 0.9f / timeTaken; - } - } - else - { - kSlowdown = 1.0f, nSlowFrames = 0; - } - m_bProcessing = 0; - //int timeSleep = (int)((m_timeTarget-gEnv->pTimer->GetAsyncTime()).GetMilliSeconds()*0.9f); - //Sleep(max(0,timeSleep)); - } - if (!stepped) - { - Sleep(0); - } - m_FrameDone.Set(); -#ifdef ENABLE_LW_PROFILERS - QueryPerformanceCounter(&stepEnd); - m_lastStepTimeTaken = stepEnd.QuadPart - stepStart.QuadPart; -#endif - } - } - virtual void Cancel() - { - Pause(); - m_bStopRequested = 1; - m_FrameEvent.Set(); - m_bIsActive = 0; - } - - int Pause() - { - if (m_bIsActive) - { - AZ_PROFILE_FUNCTION_STALL(AZ::Debug::ProfileCategory::System); - m_bIsActive = 0; - while (m_bProcessing) - { - ; - } - return 1; - } - return 0; - } - int Resume() - { - if (!m_bIsActive) - { - m_bIsActive = 1; - return 1; - } - return 0; - } - int IsActive() { return m_bIsActive; } - int RequestStep(float dt) - { - if (m_bIsActive && dt > FLT_EPSILON) - { - m_stepRequested += dt; - if (dt <= 0.0f) - { - m_doZeroStep = 1; - } - m_FrameEvent.Set(); - } - - return m_bProcessing; - } - float GetRequestedStep() { return m_stepRequested; } - - uint64 LastStepTaken() const - { - return m_lastStepTimeTaken; - } - - uint64 LastWaitTime() const - { - return m_lastWaitTimeTaken; - } - - void EnsureStepDone() - { - FRAME_PROFILER("SysUpdate:PhysicsEnsureDone", gEnv->pSystem, PROFILE_SYSTEM); - if (m_bIsActive) - { - while (m_stepRequested > 0.0f || m_bProcessing) - { - m_FrameDone.Wait(); - } - } - } - -protected: - - volatile int m_bStopRequested; - volatile int m_bIsActive; - volatile float m_stepRequested; - volatile int m_bProcessing; - volatile int m_doZeroStep; - volatile uint64 m_lastStepTimeTaken; - volatile uint64 m_lastWaitTimeTaken; - - CryEvent m_FrameEvent; - CryEvent m_FrameDone; - - SThreadTaskInfo m_TaskInfo; -}; - -void CSystem::CreatePhysicsThread() -{ - if (!m_PhysThread) - { - ////////////////////////////////////////////////////////////////////////// - SThreadTaskParams threadParams; - threadParams.name = "Physics"; - threadParams.nFlags = THREAD_TASK_BLOCKING; - threadParams.nStackSizeKB = PHYSICS_STACK_SIZE >> 10; -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_6 -#include AZ_RESTRICTED_FILE(System_cpp) -#endif - - { - m_PhysThread = new CPhysicsThreadTask; - GetIThreadTaskManager()->RegisterTask(m_PhysThread, threadParams); - } - } - -} - -void CSystem::KillPhysicsThread() -{ - if (m_PhysThread) - { - GetIThreadTaskManager()->UnregisterTask(m_PhysThread); - m_PhysThread = 0; - } -} - -/////////////////////////////////////////////////////////////////////////// -// AzFramework::Terrain::TerrainDataNotificationBus START -void CSystem::OnTerrainDataCreateBegin() -{ - KillPhysicsThread(); -} - -void CSystem::OnTerrainDataDestroyBegin() -{ - OnTerrainDataCreateBegin(); -} - -// AzFramework::Terrain::TerrainDataNotificationBus END -/////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -int CSystem::SetThreadState(ESubsystem subsys, bool bActive) -{ - switch (subsys) - { - case ESubsys_Physics: - { - if (m_PhysThread) - { - return bActive ? ((CPhysicsThreadTask*)m_PhysThread)->Resume() : ((CPhysicsThreadTask*)m_PhysThread)->Pause(); - } - } - break; - } - return 0; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::SleepIfInactive() -{ - // ProcessSleep() - if (m_bDedicatedServer || m_bEditor || gEnv->bMultiplayer) - { - return; - } -} - ////////////////////////////////////////////////////////////////////////// void CSystem::SleepIfNeeded() { @@ -1180,11 +829,7 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) // do the dedicated sleep earlier than the frame profiler to avoid having it counted if (gEnv->IsDedicated()) { -#if defined(MAP_LOADING_SLICING) - gEnv->pSystemScheduler->SchedulingSleepIfNeeded(); -#else SleepIfNeeded(); -#endif // defined(MAP_LOADING_SLICING) } #endif //EXCLUDE_UPDATE_ON_CONSOLE @@ -1199,9 +844,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) m_nUpdateCounter++; #ifndef EXCLUDE_UPDATE_ON_CONSOLE - // Check if game needs to be sleeping when not active. - SleepIfInactive(); - if (m_pUserCallback) { m_pUserCallback->OnUpdate(); @@ -1216,7 +858,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) prev_sys_float_exceptions = g_cvars.sys_float_exceptions; EnableFloatExceptions(g_cvars.sys_float_exceptions); - UpdateFPExceptionsMaskForThreads(); } #endif //EXCLUDE_UPDATE_ON_CONSOLE ////////////////////////////////////////////////////////////////////////// @@ -1263,13 +904,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) } #endif //PROFILE_WITH_VTUNE -#ifdef SOFTCODE_SYSTEM_ENABLED - if (m_env.pSoftCodeMgr) - { - m_env.pSoftCodeMgr->PollForNewModules(); - } -#endif - if (m_pStreamEngine) { FRAME_PROFILER("StreamEngine::Update()", this, PROFILE_SYSTEM); @@ -1290,7 +924,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) if (m_sysNoUpdate && m_sysNoUpdate->GetIVal()) { bNoUpdate = true; - updateFlags = ESYSUPDATE_IGNORE_PHYSICS; } m_bNoUpdate = bNoUpdate; @@ -1373,16 +1006,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) return false; } -#ifndef EXCLUDE_UPDATE_ON_CONSOLE - - ////////////////////////////////////////////////////////////////////// - //update notification network system - if (m_pNotificationNetwork) - { - FRAME_PROFILER("SysUpdate:NotificationNetwork", this, PROFILE_SYSTEM); - m_pNotificationNetwork->Update(); - } -#endif //EXCLUDE_UPDATE_ON_CONSOLE ////////////////////////////////////////////////////////////////////// //update sound system Part 1 if in Editor / in Game Mode Viewsystem updates the Listeners if (!m_env.IsEditorGameMode()) @@ -1401,15 +1024,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) } } - ////////////////////////////////////////////////////////////////////////// - // Update Threads Task Manager. - ////////////////////////////////////////////////////////////////////////// - if (m_pThreadTaskManager) - { - FRAME_PROFILER("SysUpdate:ThreadTaskManager", this, PROFILE_SYSTEM); - m_pThreadTaskManager->OnUpdate(); - } - ////////////////////////////////////////////////////////////////////////// // Update Resource Manager. ////////////////////////////////////////////////////////////////////////// @@ -1418,77 +1032,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) m_pResourceManager->Update(); } - ////////////////////////////////////////////////////////////////////// - // update physic system - //static float time_zero = 0; - if (m_sys_physics_CPU->GetIVal() > 0 && !gEnv->IsDedicated()) - { - CreatePhysicsThread(); - } - else - { - KillPhysicsThread(); - } - - static int g_iPausedPhys = 0; - - CPhysicsThreadTask* pPhysicsThreadTask = ((CPhysicsThreadTask*)m_PhysThread); - if (!pPhysicsThreadTask) - { - FRAME_PROFILER_LEGACYONLY("SysUpdate:AllAIAndPhysics", this, PROFILE_SYSTEM); - AZ_TRACE_METHOD_NAME("SysUpdate::AllAIAndPhysics"); - - ////////////////////////////////////////////////////////////////////// - // update entity system (a little bit) before physics - if (nPauseMode != 1) - { - if (!bNoUpdate) - { - EBUS_EVENT(CrySystemEventBus, OnCrySystemPrePhysicsUpdate); - } - } - - // intermingle physics/AI updates so that if we get a big timestep (frame rate glitch etc) the - // AI gets to steer entities before they travel over cliffs etc. - const float maxTimeStep = 0.25f; - int maxSteps = 1; - //float fCurTime = m_Time.GetCurrTime(); - float timeToDo = m_Time.GetFrameTime();//fCurTime - fPrevTime; - if (m_env.bMultiplayer) - { - timeToDo = m_Time.GetRealFrameTime(); - } - - - - while (timeToDo > 0.0001f && maxSteps-- > 0) - { - float thisStep = min(maxTimeStep, timeToDo); - timeToDo -= thisStep; - - - EBUS_EVENT(CrySystemEventBus, OnCrySystemPostPhysicsUpdate); - } - - } - else - { - - // In multithreaded physics mode, post physics fires after physics events are dispatched on the main thread. - EBUS_EVENT(CrySystemEventBus, OnCrySystemPostPhysicsUpdate); - - ////////////////////////////////////////////////////////////////////// - // update entity system (a little bit) before physics - if (nPauseMode != 1) - { - if (!bNoUpdate) - { - EBUS_EVENT(CrySystemEventBus, OnCrySystemPrePhysicsUpdate); - } - } - - } - // Use UI timer for CryMovie, because it should not be affected by pausing game time const float fMovieFrameTime = m_Time.GetFrameTime(ITimer::ETIMER_UI); @@ -1550,8 +1093,6 @@ bool CSystem::UpdatePostTickBus(int updateFlags, int /*nPauseMode*/) m_updateTimes.push_back(std::make_pair(cur_time, updateTime)); } - UpdateUpdateTimes(); - { FRAME_PROFILER("SysUpdate - SystemEventDispatcher::Update", this, PROFILE_SYSTEM); m_pSystemEventDispatcher->Update(); @@ -1890,12 +1431,6 @@ ILocalizationManager* CSystem::GetLocalizationManager() return m_pLocalizationManager; } -////////////////////////////////////////////////////////////////////////// -IThreadTaskManager* CSystem::GetIThreadTaskManager() -{ - return m_pThreadTaskManager; -} - ////////////////////////////////////////////////////////////////////////// IResourceManager* CSystem::GetIResourceManager() { @@ -1960,10 +1495,6 @@ void CSystem::ExecuteCommandLine(bool deferred) if (pCmd->GetType() == eCLAT_Post) { string sLine = pCmd->GetName(); - -#if defined(CVARS_WHITELIST) - if (!GetCVarsWhiteList() || GetCVarsWhiteList()->IsWhiteListed(sLine, false)) -#endif { if (pCmd->GetValue()) { @@ -1973,12 +1504,6 @@ void CSystem::ExecuteCommandLine(bool deferred) GetILog()->Log("Executing command from command line: \n%s\n", sLine.c_str()); // - the actual command might be executed much later (e.g. level load pause) GetIConsole()->ExecuteString(sLine.c_str(), false, deferred); } -#if defined(CVARS_WHITELIST) - else if (gEnv->IsDedicated()) - { - GetILog()->LogError("Failed to execute command: '%s' as it is not whitelisted\n", sLine.c_str()); - } -#endif } } @@ -2078,93 +1603,6 @@ void CProfilingSystem::VTunePause() #endif } -////////////////////////////////////////////////////////////////////////// -sUpdateTimes& CSystem::GetCurrentUpdateTimeStats() -{ - return m_UpdateTimes[m_UpdateTimesIdx]; -} - -////////////////////////////////////////////////////////////////////////// -const sUpdateTimes* CSystem::GetUpdateTimeStats(uint32& index, uint32& num) -{ - index = m_UpdateTimesIdx; - num = NUM_UPDATE_TIMES; - return m_UpdateTimes; -} - -void CSystem::UpdateUpdateTimes() -{ - sUpdateTimes& sample = m_UpdateTimes[m_UpdateTimesIdx]; - if (m_PhysThread) - { - static uint64 lastPhysTime = 0U; - static uint64 lastMainTime = 0U; - static uint64 lastYields = 0U; - static uint64 lastPhysWait = 0U; - uint64 physTime = 0, mainTime = 0; - uint32 yields = 0; - physTime = ((CPhysicsThreadTask*)m_PhysThread)->LastStepTaken(); - mainTime = CryGetTicks() - lastMainTime; - lastMainTime = mainTime; - lastPhysWait = ((CPhysicsThreadTask*)m_PhysThread)->LastWaitTime(); - sample.PhysStepTime = physTime; - sample.SysUpdateTime = mainTime; - sample.PhysYields = yields; - sample.physWaitTime = lastPhysWait; - } - ++m_UpdateTimesIdx; - if (m_UpdateTimesIdx >= NUM_UPDATE_TIMES) - { - m_UpdateTimesIdx = 0; - } -} - - -#ifndef _RELEASE -void CSystem::GetCheckpointData(ICheckpointData& data) -{ - data.m_totalLoads = m_checkpointLoadCount; - data.m_loadOrigin = m_loadOrigin; -} - -void CSystem::IncreaseCheckpointLoadCount() -{ - if (!m_hasJustResumed) - { - ++m_checkpointLoadCount; - } - - m_hasJustResumed = false; -} - -void CSystem::SetLoadOrigin(LevelLoadOrigin origin) -{ - switch (origin) - { - case eLLO_NewLevel: // Intentional fall through - case eLLO_Level2Level: - m_expectingMapCommand = true; - break; - - case eLLO_Resumed: - m_hasJustResumed = true; - break; - - case eLLO_MapCmd: - if (m_expectingMapCommand) - { - // We knew a map command was coming, so don't process this. - m_expectingMapCommand = false; - return; - } - break; - } - - m_loadOrigin = origin; - m_checkpointLoadCount = 0; -} -#endif - bool CSystem::SteamInit() { #if USE_STEAM diff --git a/Code/CryEngine/CrySystem/System.h b/Code/CryEngine/CrySystem/System.h index c4f3bfabd6..e27dfe4866 100644 --- a/Code/CryEngine/CrySystem/System.h +++ b/Code/CryEngine/CrySystem/System.h @@ -26,14 +26,12 @@ #include "MTSafeAllocator.h" #include "CPUDetect.h" #include -#include "ThreadTask.h" #include "RenderBus.h" #include #include #include -#include namespace AzFramework { @@ -44,7 +42,6 @@ struct IConsoleCmdArgs; class CServerThrottle; struct IZLibCompressor; class CWatchdogThread; -class CThreadManager; #if defined(AZ_RESTRICTED_PLATFORM) #undef AZ_RESTRICTED_SECTION @@ -183,8 +180,6 @@ class CThreadManager; #include "CryLibrary.h" #endif -#define NUM_UPDATE_TIMES (128U) - #ifdef WIN32 typedef void* WIN_HMODULE; #else @@ -241,7 +236,6 @@ struct SSystemCVars int sys_WER; int sys_dump_type; int sys_ai; - int sys_physics; int sys_entitysystem; int sys_trackview; int sys_vtune; @@ -342,7 +336,6 @@ class CSystem , public IWindowMessageHandler , public AZ::RenderNotificationsBus::Handler , public CrySystemRequestBus::Handler - , private AzFramework::Terrain::TerrainDataNotificationBus::Handler { public: @@ -397,20 +390,8 @@ public: ISystem* GetCrySystem() override; //////////////////////////////////////////////////////////////////////// - //! Update screen during loading. - void UpdateLoadingScreen(); - - //! Update screen and call some important tick functions during loading. - void SynchronousLoadingTick(const char* pFunc, int line); - uint32 GetUsedMemory(); -#ifndef _RELEASE - virtual void GetCheckpointData(ICheckpointData& data); - virtual void IncreaseCheckpointLoadCount(); - virtual void SetLoadOrigin(LevelLoadOrigin origin); -#endif - virtual bool SteamInit(); void Relaunch(bool bRelaunch); @@ -425,8 +406,6 @@ public: virtual const char* GetUserName(); virtual int GetApplicationInstance(); int GetApplicationLogInstance(const char* logFilePath) override; - virtual sUpdateTimes& GetCurrentUpdateTimeStats(); - virtual const sUpdateTimes* GetUpdateTimeStats(uint32&, uint32&); ITimer* GetITimer(){ return m_env.pTimer; } AZ::IO::IArchive* GetIPak() { return m_env.pCryPak; }; @@ -434,7 +413,6 @@ public: IRemoteConsole* GetIRemoteConsole(); IMovieSystem* GetIMovieSystem() { return m_env.pMovieSystem; }; IMemoryManager* GetIMemoryManager(){ return m_pMemoryManager; } - IThreadManager* GetIThreadManager() override {return m_env.pThreadManager; } ICryFont* GetICryFont(){ return m_env.pCryFont; } ILog* GetILog(){ return m_env.pLog; } ICmdLine* GetICmdLine(){ return m_pCmdLine; } @@ -444,11 +422,8 @@ public: IViewSystem* GetIViewSystem(); ILevelSystem* GetILevelSystem(); ISystemEventDispatcher* GetISystemEventDispatcher() { return m_pSystemEventDispatcher; } - IThreadTaskManager* GetIThreadTaskManager(); IResourceManager* GetIResourceManager(); ITextModeConsole* GetITextModeConsole(); - IVisualLog* GetIVisualLog() { return m_env.pVisualLog; } - INotificationNetwork* GetINotificationNetwork() { return m_pNotificationNetwork; } IProfilingSystem* GetIProfilingSystem() { return &m_ProfilingSystem; } IZLibCompressor* GetIZLibCompressor() { return m_pIZLibCompressor; } IZLibDecompressor* GetIZLibDecompressor() { return m_pIZLibDecompressor; } @@ -459,19 +434,6 @@ public: CPNoise3* GetNoiseGen(); virtual uint64 GetUpdateCounter() { return m_nUpdateCounter; }; - virtual void SetLoadingProgressListener(ILoadingProgressListener* pLoadingProgressListener) - { - m_pProgressListener = pLoadingProgressListener; - }; - - virtual ILoadingProgressListener* GetLoadingProgressListener() const - { - return m_pProgressListener; - }; - - void SetIMaterialEffects(IMaterialEffects* pMaterialEffects) { m_env.pMaterialEffects = pMaterialEffects; } - void SetIOpticsManager(IOpticsManager* pOpticsManager) { m_env.pOpticsManager = pOpticsManager; } - void SetIVisualLog(IVisualLog* pVisualLog) { m_env.pVisualLog = pVisualLog; } void DetectGameFolderAccessRights(); virtual void ExecuteCommandLine(bool deferred=true); @@ -554,12 +516,6 @@ public: //! Return pointer to user defined callback. ISystemUserCallback* GetUserCallback() const { return m_pUserCallback; }; -#if defined(CVARS_WHITELIST) - virtual ICVarsWhitelist* GetCVarsWhiteList() const { return m_pCVarsWhitelist; }; - virtual ILoadConfigurationEntrySink* GetCVarsWhiteListConfigSink() const { return m_pCVarsWhitelistConfigSink; } -#else - virtual ILoadConfigurationEntrySink* GetCVarsWhiteListConfigSink() const { return nullptr; } -#endif // defined(CVARS_WHITELIST) ////////////////////////////////////////////////////////////////////////// virtual void SaveConfiguration(); @@ -571,7 +527,6 @@ public: virtual void SetConfigPlatform(ESystemConfigPlatform platform); ////////////////////////////////////////////////////////////////////////// - virtual int SetThreadState(ESubsystem subsys, bool bActive); virtual bool IsPaused() const { return m_bPaused; }; virtual ILocalizationManager* GetLocalizationManager(); @@ -608,8 +563,6 @@ private: // Release all resources. void ShutDown(); - void SleepIfInactive(); - bool LoadEngineDLLs(); //! @name Initialization routines @@ -623,12 +576,6 @@ private: //@} - ////////////////////////////////////////////////////////////////////////// - // Threading functions. - ////////////////////////////////////////////////////////////////////////// - void InitThreadSystem(); - void ShutDownThreadSystem(); - ////////////////////////////////////////////////////////////////////////// // Helper functions. ////////////////////////////////////////////////////////////////////////// @@ -645,9 +592,6 @@ private: void LogBuildInfo(); void SetDevMode(bool bEnable); - void CreatePhysicsThread(); - void KillPhysicsThread(); - #ifndef _RELEASE static void SystemVersionChanged(ICVar* pCVar); #endif // #ifndef _RELEASE @@ -676,7 +620,6 @@ public: virtual bool GetForceNonDevMode() const; virtual bool WasInDevMode() const { return m_bWasInDevMode; }; virtual bool IsDevMode() const { return m_bInDevMode && !GetForceNonDevMode(); } - virtual bool IsMinimalMode() const { return m_bMinimal; } virtual bool IsMODValid(const char* szMODName) const { if (!szMODName || strstr(szMODName, ".") || strstr(szMODName, "\\")) @@ -727,7 +670,6 @@ private: // ------------------------------------------------------ bool m_bRelaunch; //!< relaunching the app or not (true beforerelaunch) int m_iLoadingMode; //!< Game is loading w/o changing context (0 not, 1 quickloading, 2 full loading) bool m_bTestMode; //!< If running in testing mode. - bool m_bMinimal; //!< If running in 'minimal mode'. bool m_bEditor; //!< If running in Editor. bool m_bNoCrashDialog; bool m_bNoErrorReportWindow; @@ -742,16 +684,6 @@ private: // ------------------------------------------------------ SDefaultValidator* m_pDefaultValidator; //!< CCpuFeatures* m_pCpu; //!< CPU features int m_ttMemStatSS; //!< Time to memstat screenshot - string m_szCmdLine; - - int m_iTraceAllocations; - -#ifndef _RELEASE - int m_checkpointLoadCount;// Total times game has loaded from a checkpoint - LevelLoadOrigin m_loadOrigin; // Where the load was initiated from - bool m_hasJustResumed; // Has resume game just been called - bool m_expectingMapCommand; -#endif bool m_bDrawConsole; //!< Set to true if OK to draw the console. bool m_bDrawUI; //!< Set to true if OK to draw UI. @@ -867,8 +799,6 @@ private: // ------------------------------------------------------ ICVar* m_sys_asset_processor; ICVar* m_sys_load_files_to_memory; - ICVar* m_sys_physics_CPU; - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION SYSTEM_H_SECTION_4 #include AZ_RESTRICTED_FILE(System_h) @@ -891,15 +821,6 @@ private: // ------------------------------------------------------ //! User define callback for system events. ISystemUserCallback* m_pUserCallback; -#if defined(CVARS_WHITELIST) - ////////////////////////////////////////////////////////////////////////// - //! User define callback for whitelisting cvars - ICVarsWhitelist* m_pCVarsWhitelist; - ILoadConfigurationEntrySink* m_pCVarsWhitelistConfigSink; -#endif // defined(CVARS_WHITELIST) - - //int m_nCurrentLogVerbosity; - SFileVersion m_fileVersion; SFileVersion m_productVersion; SFileVersion m_buildVersion; @@ -910,8 +831,6 @@ private: // ------------------------------------------------------ // Name table. CNameTable m_nameTable; - IThreadTask* m_PhysThread; - ESystemConfigSpec m_nServerConfigSpec; ESystemConfigSpec m_nMaxConfigSpec; ESystemConfigPlatform m_ConfigPlatform; @@ -919,8 +838,6 @@ private: // ------------------------------------------------------ std::unique_ptr m_pServerThrottle; CProfilingSystem m_ProfilingSystem; - sUpdateTimes m_UpdateTimes[NUM_UPDATE_TIMES]; - uint32 m_UpdateTimesIdx; // Pause mode. bool m_bPaused; @@ -991,26 +908,14 @@ private: ESystemGlobalState m_systemGlobalState; static const char* GetSystemGlobalStateName(const ESystemGlobalState systemGlobalState); - /////////////////////////////////////////////////////////////////////////// - // AzFramework::Terrain::TerrainDataNotificationBus START - void OnTerrainDataCreateBegin() override; - void OnTerrainDataDestroyBegin() override; - // AzFramework::Terrain::TerrainDataNotificationBus END - /////////////////////////////////////////////////////////////////////////// - public: void InitLocalization(); - void UpdateUpdateTimes(); protected: // ------------------------------------------------------------- - ILoadingProgressListener* m_pProgressListener; CCmdLine* m_pCmdLine; - CThreadManager* m_pThreadManager; - CThreadTaskManager* m_pThreadTaskManager; class CResourceManager* m_pResourceManager; ITextModeConsole* m_pTextModeConsole; - INotificationNetwork* m_pNotificationNetwork; string m_currentLanguageAudio; string m_systemConfigName; // computed from system_(hardwareplatform)_(assetsPlatform) - eg, system_android_es3.cfg or system_android_opengl.cfg or system_windows_pc.cfg diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index 8bf2fb8930..48cb5e0d9e 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -35,13 +35,9 @@ #define SYSTEMINIT_CPP_SECTION_17 17 #endif -#if defined(MAP_LOADING_SLICING) -#include "SystemScheduler.h" -#endif // defined(MAP_LOADING_SLICING) #include "CryLibrary.h" #include "CryPath.h" #include -#include #include #include @@ -103,16 +99,12 @@ #include "PhysRenderer.h" #include "LocalizedStringManager.h" #include "SystemEventDispatcher.h" -#include "ThreadConfigManager.h" #include "Validator.h" #include "ServerThrottle.h" #include "SystemCFG.h" #include "AutoDetectSpec.h" #include "ResourceManager.h" #include "MTSafeAllocator.h" -#include "NotificationNetwork.h" -#include "ProfileLogSystem.h" -#include "SoftCode/SoftCodeMgr.h" #include "ZLibCompressor.h" #include "ZLibDecompressor.h" #include "ZStdDecompressor.h" @@ -146,8 +138,6 @@ #include "MobileDetectSpec.h" #endif -#include "IDebugCallStack.h" - #include "WindowsConsole.h" #if defined(EXTERNAL_CRASH_REPORTING) @@ -163,11 +153,6 @@ # include #endif -// if we enable the built-in local version instead of remote: -#if defined(CRY_ENABLE_RC_HELPER) -#include "ResourceCompilerHelper.h" -#endif - #ifdef WIN32 extern LONG WINAPI CryEngineExceptionFilterWER(struct _EXCEPTION_POINTERS* pExceptionPointers); #endif @@ -400,26 +385,20 @@ struct SysSpecOverrideSink } else { - // This could bypass the restricted/whitelisted cvar checks that exist elsewhere depending on + // This could bypass the restricted cvar checks that exist elsewhere depending on // the calling code so we also need check here before setting. bool isConst = pCvar->IsConstCVar(); bool isCheat = ((pCvar->GetFlags() & (VF_CHEAT | VF_CHEAT_NOCHECK | VF_CHEAT_ALWAYS_CHECK)) != 0); bool isReadOnly = ((pCvar->GetFlags() & VF_READONLY) != 0); bool isDeprecated = ((pCvar->GetFlags() & VF_DEPRECATED) != 0); bool allowApplyCvar = true; - bool whitelisted = true; - -#if defined CVARS_WHITELIST - ICVarsWhitelist* cvarWhitelist = gEnv->pSystem->GetCVarsWhiteList(); - whitelisted = cvarWhitelist ? cvarWhitelist->IsWhiteListed(szKey, true) : true; -#endif if ((isConst || isCheat || isReadOnly) || isDeprecated) { allowApplyCvar = !isDeprecated && (gEnv->pSystem->IsDevMode()) || (gEnv->IsEditor()); } - if ((allowApplyCvar && whitelisted) || ALLOW_CONST_CVAR_MODIFICATIONS) + if ((allowApplyCvar) || ALLOW_CONST_CVAR_MODIFICATIONS) { applyCvar = true; } @@ -1028,7 +1007,6 @@ bool CSystem::InitFileSystem() // get the DirectInstance FileIOBase which should be the AZ::LocalFileIO m_env.pFileIO = AZ::IO::FileIOBase::GetDirectInstance(); - m_env.pResourceCompilerHelper = nullptr; m_env.pCryPak = AZ::Interface::Get(); m_env.pFileIO = AZ::IO::FileIOBase::GetInstance(); @@ -1107,8 +1085,7 @@ bool CSystem::InitFileSystem_LoadEngineFolders(const SSystemInitParams&) { LOADING_TIME_PROFILE_SECTION; { - ILoadConfigurationEntrySink* pCVarsWhiteListConfigSink = GetCVarsWhiteListConfigSink(); - LoadConfiguration(m_systemConfigName.c_str(), pCVarsWhiteListConfigSink); + LoadConfiguration(m_systemConfigName.c_str()); AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "Loading system configuration from %s...", m_systemConfigName.c_str()); } @@ -1118,13 +1095,6 @@ bool CSystem::InitFileSystem_LoadEngineFolders(const SSystemInitParams&) GetISystem()->SetConfigPlatform(GetDevicePlatform()); -#if defined(CRY_ENABLE_RC_HELPER) - if (!m_env.pResourceCompilerHelper) - { - m_env.pResourceCompilerHelper = new CResourceCompilerHelper(); - } -#endif - auto projectPath = AZ::Utils::GetProjectPath(); AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "Project Path: %s\n", projectPath.empty() ? "None specified" : projectPath.c_str()); @@ -1179,7 +1149,6 @@ bool CSystem::InitAudioSystem(const SSystemInitParams& initParams) bool useRealAudioSystem = false; if (!initParams.bPreview - && !initParams.bMinimal && !m_bDedicatedServer && m_sys_audio_disable->GetIVal() == 0) { @@ -1672,12 +1641,8 @@ bool CSystem::Init(const SSystemInitParams& startupParams) gEnv->mMainThreadId = GetCurrentThreadId(); //Set this ASAP on startup InlineInitializationProcessing("CSystem::Init start"); - m_szCmdLine = startupParams.szSystemCmdLine; - m_env.szCmdLine = m_szCmdLine.c_str(); - m_env.bTesting = startupParams.bTesting; - m_env.bNoAssertDialog = startupParams.bTesting; - m_env.bNoRandomSeed = startupParams.bNoRandom; + m_env.bNoAssertDialog = false; m_bNoCrashDialog = gEnv->IsDedicated(); @@ -1754,16 +1719,10 @@ AZ_POP_DISABLE_WARNING m_bPreviewMode = startupParams.bPreview; m_bTestMode = startupParams.bTestMode; m_pUserCallback = startupParams.pUserCallback; - m_bMinimal = startupParams.bMinimal; -#if defined(CVARS_WHITELIST) - m_pCVarsWhitelist = startupParams.pCVarsWhitelist; -#endif // defined(CVARS_WHITELIST) m_bDedicatedServer = startupParams.bDedicatedServer; m_currentLanguageAudio = ""; - memcpy(gEnv->pProtectedFunctions, startupParams.pProtectedFunctions, sizeof(startupParams.pProtectedFunctions)); - #if !defined(CONSOLE) m_env.SetIsEditor(m_bEditor); m_env.SetIsEditorGameMode(false); @@ -1771,7 +1730,6 @@ AZ_POP_DISABLE_WARNING #endif m_env.SetToolMode(startupParams.bToolMode); - m_env.bIsOutOfMemory = false; if (m_bEditor) { @@ -1935,23 +1893,6 @@ AZ_POP_DISABLE_WARNING // so we log this immediately after setting the log filename LogVersion(); - //here we should be good to ask Crypak to do something - - // Initialise after pLog and CPU feature initialization - // AND after console creation (Editor only) - // May need access to engine folder .pak files - gEnv->pThreadManager->GetThreadConfigManager()->LoadConfig("config/engine_core.thread_config"); - - if (m_bEditor) - { - gEnv->pThreadManager->GetThreadConfigManager()->LoadConfig("config/engine_sandbox.thread_config"); - } - - // Setup main thread - void* pThreadHandle = 0; // Let system figure out thread handle - gEnv->pThreadManager->RegisterThirdPartyThread(pThreadHandle, "Main"); - m_env.pProfileLogSystem = new CProfileLogSystem(); - bool devModeEnable = true; #if defined(_RELEASE) @@ -1967,22 +1908,6 @@ AZ_POP_DISABLE_WARNING SetDevMode(devModeEnable); - ////////////////////////////////////////////////////////////////////////// - // CREATE NOTIFICATION NETWORK - ////////////////////////////////////////////////////////////////////////// - m_pNotificationNetwork = nullptr; -#ifndef _RELEASE - #ifndef LINUX - - if (!startupParams.bMinimal) - { - m_pNotificationNetwork = CNotificationNetwork::Create(); - } - #endif//LINUX -#endif // _RELEASE - - InlineInitializationProcessing("CSystem::Init NotificationNetwork"); - ////////////////////////////////////////////////////////////////////////// // CREATE CONSOLE ////////////////////////////////////////////////////////////////////////// @@ -2051,8 +1976,6 @@ AZ_POP_DISABLE_WARNING // CPU features detection. m_pCpu = new CCpuFeatures; m_pCpu->Detect(); - m_env.pi.numCoresAvailableToProcess = m_pCpu->GetCPUCount(); - m_env.pi.numLogicalProcessors = m_pCpu->GetLogicalCPUCount(); // Check hard minimum CPU requirements if (!CheckCPURequirements(m_pCpu, this)) @@ -2102,17 +2025,15 @@ AZ_POP_DISABLE_WARNING } { - ILoadConfigurationEntrySink* pCVarsWhiteListConfigSink = GetCVarsWhiteListConfigSink(); - // We have to load this file again since first time we did it without devmode - LoadConfiguration(m_systemConfigName.c_str(), pCVarsWhiteListConfigSink); + LoadConfiguration(m_systemConfigName.c_str()); // Optional user defined overrides - LoadConfiguration("user.cfg", pCVarsWhiteListConfigSink); + LoadConfiguration("user.cfg"); #if defined(ENABLE_STATS_AGENT) if (m_pCmdLine->FindArg(eCLAT_Pre, "useamblecfg")) { - LoadConfiguration("amble.cfg", pCVarsWhiteListConfigSink); + LoadConfiguration("amble.cfg"); } #endif } @@ -2159,7 +2080,7 @@ AZ_POP_DISABLE_WARNING InlineInitializationProcessing("CSystem::Init LoadConfigurations"); #ifdef WIN32 - if ((g_cvars.sys_WER) && (!startupParams.bMinimal)) + if ((g_cvars.sys_WER)) { SetUnhandledExceptionFilter(CryEngineExceptionFilterWER); } @@ -2169,7 +2090,6 @@ AZ_POP_DISABLE_WARNING ////////////////////////////////////////////////////////////////////////// // Localization ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bMinimal) { InitLocalization(); } @@ -2187,7 +2107,6 @@ AZ_POP_DISABLE_WARNING ////////////////////////////////////////////////////////////////////////// // AUDIO ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bMinimal) { if (InitAudioSystem(startupParams)) { @@ -2210,12 +2129,6 @@ AZ_POP_DISABLE_WARNING m_pUserCallback->OnInitProgress("First time asset processing - may take a minute..."); } -#ifdef SOFTCODE_SYSTEM_ENABLED - m_env.pSoftCodeMgr = new SoftCodeMgr(); -#else - m_env.pSoftCodeMgr = nullptr; -#endif - ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // System cursor @@ -2225,8 +2138,7 @@ AZ_POP_DISABLE_WARNING // - System cursor has to be enabled manually by the Game if needed; the custom UiCursor will typically be used instead if (!gEnv->IsDedicated() && - !gEnv->IsEditor() && - !startupParams.bTesting) + !gEnv->IsEditor()) { AzFramework::InputSystemCursorRequestBus::Event(AzFramework::InputDeviceMouse::Id, &AzFramework::InputSystemCursorRequests::SetSystemCursorState, @@ -2322,27 +2234,6 @@ AZ_POP_DISABLE_WARNING InlineInitializationProcessing("CSystem::Init ZStdDecompressor"); - ////////////////////////////////////////////////////////////////////////// - // Initialize task threads. - ////////////////////////////////////////////////////////////////////////// - { - m_pThreadTaskManager->InitThreads(); - - SetAffinity(); - AZ_Assert(CryMemory::IsHeapValid(), "CryMemory heap must be valid before initializing VTune."); - - - if (strstr(startupParams.szSystemCmdLine, "-VTUNE") != 0 || g_cvars.sys_vtune != 0) - { - if (!InitVTuneProfiler()) - { - return false; - } - } - } - - InlineInitializationProcessing("CSystem::Init InitTaskThreads"); - if (m_env.pLyShine) { m_env.pLyShine->PostInit(); @@ -2366,8 +2257,6 @@ AZ_POP_DISABLE_WARNING } } EnableFloatExceptions(g_cvars.sys_float_exceptions); - - MarkThisThreadForDebugging("Main"); } InlineInitializationProcessing("CSystem::Init End"); @@ -2422,8 +2311,7 @@ static void LoadConfigurationCmd(IConsoleCmdArgs* pParams) return; } - ILoadConfigurationEntrySink* pCVarsWhiteListConfigSink = GetISystem()->GetCVarsWhiteListConfigSink(); - GetISystem()->LoadConfiguration(string("Config/") + pParams->GetArg(1), pCVarsWhiteListConfigSink); + GetISystem()->LoadConfiguration(string("Config/") + pParams->GetArg(1)); } @@ -2648,20 +2536,6 @@ void CmdDrillToFile(IConsoleCmdArgs* pArgs) } } -void ChangeLogAllocations(ICVar* pVal) -{ - g_iTraceAllocations = pVal->GetIVal(); - - if (g_iTraceAllocations == 2) - { - IDebugCallStack::instance()->StartMemLog(); - } - else - { - IDebugCallStack::instance()->StopMemLog(); - } -} - ////////////////////////////////////////////////////////////////////////// void CSystem::CreateSystemVars() { @@ -2719,9 +2593,6 @@ void CSystem::CreateSystemVars() m_cvAIUpdate = REGISTER_INT("ai_NoUpdate", 0, VF_CHEAT, "Disables AI system update when 1"); - m_iTraceAllocations = g_iTraceAllocations; - REGISTER_CVAR2_CB("sys_logallocations", &m_iTraceAllocations, m_iTraceAllocations, VF_DUMPTODISK, "Save allocation call stack", ChangeLogAllocations); - m_cvMemStats = REGISTER_INT("MemStats", 0, 0, "0/x=refresh rate in milliseconds\n" "Use 1000 to switch on and 0 to switch off\n" @@ -2860,16 +2731,6 @@ void CSystem::CreateSystemVars() m_sys_TaskThread_CPU[5] = REGISTER_INT("sys_TaskThread5_CPU", 1, 0, "Specifies the physical CPU index taskthread5 will run on"); - //if physics thread is excluded all locks inside are mapped to NO_LOCK - //var must be not visible to accidentally get enabled -#if defined(EXCLUDE_PHYSICS_THREAD) - m_sys_physics_CPU = REGISTER_INT("sys_physics_CPU_disabled", 0, 0, - "Specifies the physical CPU index physics will run on"); -#else - m_sys_physics_CPU = REGISTER_INT("sys_physics_CPU", 1, 0, - "Specifies the physical CPU index physics will run on"); -#endif - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_12 #include AZ_RESTRICTED_FILE(SystemInit_cpp) @@ -3033,7 +2894,6 @@ void CSystem::CreateSystemVars() "0=off / 1=enabled"); */ REGISTER_CVAR2("sys_AI", &g_cvars.sys_ai, 1, 0, "Enables AI Update"); - REGISTER_CVAR2("sys_physics", &g_cvars.sys_physics, 1, 0, "Enables Physics Update"); REGISTER_CVAR2("sys_entities", &g_cvars.sys_entitysystem, 1, 0, "Enables Entities Update"); REGISTER_CVAR2("sys_trackview", &g_cvars.sys_trackview, 1, 0, "Enables TrackView Update"); @@ -3068,10 +2928,6 @@ void CSystem::CreateSystemVars() REGISTER_STRING("dlc_directory", "", 0, "Holds the path to the directory where DLC should be installed to and read from"); -#if defined(MAP_LOADING_SLICING) - CreateSystemScheduler(this); -#endif // defined(MAP_LOADING_SLICING) - #if defined(WIN32) || defined(WIN64) REGISTER_INT("sys_screensaver_allowed", 0, VF_NULL, "Specifies if screen saver is allowed to start up while the game is running."); #endif diff --git a/Code/CryEngine/CrySystem/SystemRender.cpp b/Code/CryEngine/CrySystem/SystemRender.cpp index 9e148bbc2b..b608ef5335 100644 --- a/Code/CryEngine/CrySystem/SystemRender.cpp +++ b/Code/CryEngine/CrySystem/SystemRender.cpp @@ -39,8 +39,6 @@ #include #include -#include "ThreadInfo.h" - #include #if defined(AZ_RESTRICTED_PLATFORM) @@ -90,52 +88,6 @@ void CSystem::OnScene3DEnd() } } - -//! Update screen and call some important tick functions during loading. -void CSystem::SynchronousLoadingTick([[maybe_unused]] const char* pFunc, [[maybe_unused]] int line) -{ - LOADING_TIME_PROFILE_SECTION; - if (gEnv && gEnv->bMultiplayer && !gEnv->IsEditor()) - { - //UpdateLoadingScreen currently contains a couple of tick functions that need to be called regularly during the synchronous level loading, - //when the usual engine and game ticks are suspended. - UpdateLoadingScreen(); - -#if defined(MAP_LOADING_SLICING) - GetISystemScheduler()->SliceAndSleep(pFunc, line); -#endif - } -} - - -////////////////////////////////////////////////////////////////////////// -void CSystem::UpdateLoadingScreen() -{ - // Do not update the network thread from here - it will cause context corruption - use the NetworkStallTicker thread system - - if (GetCurrentThreadId() != gEnv->mMainThreadId) - { - return; - } - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMRENDERER_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(SystemRender_cpp) -#endif - -#if AZ_LOADSCREENCOMPONENT_ENABLED - EBUS_EVENT(LoadScreenBus, UpdateAndRender); -#endif // if AZ_LOADSCREENCOMPONENT_ENABLED - - if (!m_bEditor && !IsQuitting()) - { - if (m_pProgressListener) - { - m_pProgressListener->OnLoadingProgress(0); - } - } -} - ////////////////////////////////////////////////////////////////////////// void CSystem::DisplayErrorMessage(const char* acMessage, diff --git a/Code/CryEngine/CrySystem/SystemScheduler.cpp b/Code/CryEngine/CrySystem/SystemScheduler.cpp deleted file mode 100644 index 5cee6d5529..0000000000 --- a/Code/CryEngine/CrySystem/SystemScheduler.cpp +++ /dev/null @@ -1,211 +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 the CSystemScheduler class - - -#include "CrySystem_precompiled.h" - -#include "ProjectDefines.h" -#if defined(MAP_LOADING_SLICING) - -#include "SystemScheduler.h" - -#include "MiniQueue.h" -#include "ClientHandler.h" -#include "ServerHandler.h" - -void CreateSystemScheduler(CSystem* pSystem) -{ - gEnv->pSystemScheduler = new CSystemScheduler(pSystem); -} - -CSystemScheduler::CSystemScheduler(CSystem* pSystem) - : m_pSystem(pSystem) - , m_lastSliceCheckTime(0.0f) - , m_sliceLoadingRef(0) -{ - int defaultSchedulingMode = 0; - if (gEnv->IsDedicated()) - { - defaultSchedulingMode = 2; - } - - m_svSchedulingMode = REGISTER_INT("sv_scheduling", defaultSchedulingMode, 0, "Scheduling mode\n" - " 0: Normal mode\n" - " 1: Client\n" - " 2: Server\n"); - - m_svSchedulingBucket = REGISTER_INT("sv_schedulingBucket", 0, 0, "Scheduling bucket\n"); - - m_svSchedulingAffinity = REGISTER_INT("sv_SchedulingAffinity", 0, 0, "Scheduling affinity\n"); - - m_svSchedulingClientTimeout = REGISTER_INT("sv_schedulingClientTimeout", 1000, 0, "Client wait server\n"); - m_svSchedulingServerTimeout = REGISTER_INT("sv_schedulingServerTimeout", 100, 0, "Server wait server\n"); - -#if defined(MAP_LOADING_SLICING) - m_svSliceLoadEnable = REGISTER_INT("sv_sliceLoadEnable", 1, 0, "Enable/disable slice loading logic\n"); - ; - m_svSliceLoadBudget = REGISTER_INT("sv_sliceLoadBudget", 10, 0, "Slice budget\n"); - ; - m_svSliceLoadLogging = REGISTER_INT("sv_sliceLoadLogging", 0, 0, "Enable/disable slice loading logging\n"); -#endif - - m_pLastSliceName = "INACTIVE"; - m_lastSliceLine = 0; -} - -CSystemScheduler::~CSystemScheduler(void) -{ -} - -void CSystemScheduler::SliceLoadingBegin() -{ - m_lastSliceCheckTime = gEnv->pTimer->GetAsyncTime(); - m_sliceLoadingRef++; - m_pLastSliceName = "START"; - m_lastSliceLine = 0; -} - -void CSystemScheduler::SliceLoadingEnd() -{ - m_sliceLoadingRef--; - m_pLastSliceName = "INACTIVE"; - m_lastSliceLine = 0; -} - -void CSystemScheduler::SliceAndSleep(const char* sliceName, int line) -{ -#if defined(MAP_LOADING_SLICING) - if (!gEnv->IsDedicated()) - { - return; - } - - if (!m_sliceLoadingRef) - { - return; - } - - if (!m_svSliceLoadEnable->GetIVal()) - { - return; - } - - SchedulingModeUpdate(); - - CTimeValue currTime = gEnv->pTimer->GetAsyncTime(); - - float sliceBudget = CLAMP(m_svSliceLoadBudget->GetFVal(), 0, 1000.0f / m_pSystem->GetDedicatedMaxRate()->GetFVal()); - bool doSleep = true; - if ((currTime - m_pSystem->GetLastTickTime()).GetMilliSeconds() < sliceBudget) - { - m_lastSliceCheckTime = currTime; - doSleep = false; - } - - if (doSleep) - { - if (m_svSliceLoadLogging->GetIVal()) - { - float diff = (currTime - m_lastSliceCheckTime).GetMilliSeconds(); - if (diff > sliceBudget) - { - CryLogAlways("[SliceAndSleep]: Interval between slice [%s:%i] and [%s:%i] was [%f] out of budget [%f]", m_pLastSliceName, m_lastSliceLine, sliceName, line, diff, sliceBudget); - } - } - - m_pSystem->SleepIfNeeded(); - } - - m_pLastSliceName = sliceName; - m_lastSliceLine = line; -#endif -} - -void CSystemScheduler::SchedulingSleepIfNeeded() -{ - if (!gEnv->IsDedicated()) - { - return; - } - - SchedulingModeUpdate(); - m_pSystem->SleepIfNeeded(); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Scheduling mode routines -// -/////////////////////////////////////////////////////////////////////////////////////////////////// - - - - - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Scheduling mode update logic -// -/////////////////////////////////////////////////////////////////////////////////////////////////// - -void CSystemScheduler::SchedulingModeUpdate() -{ - static std::unique_ptr m_client; - static std::unique_ptr m_server; - - if (int scheduling = m_svSchedulingMode->GetIVal()) - { - if (scheduling == 1) //client - { - if (!m_client.get()) - { - m_server.reset(); - m_client.reset(new ClientHandler(m_svSchedulingBucket->GetString(), m_svSchedulingAffinity->GetIVal(), m_svSchedulingClientTimeout->GetIVal())); - } - if (m_client->Sync()) - { - return; - } - } - else if (scheduling == 2) //server - { - if (!m_server.get()) - { - m_client.reset(); - m_server.reset(new ServerHandler(m_svSchedulingBucket->GetString(), m_svSchedulingAffinity->GetIVal(), m_svSchedulingServerTimeout->GetIVal())); - } - if (m_server->Sync()) - { - return; - } - } - } - else - { - m_client.reset(); - m_server.reset(); - } -} - -#endif // defined(MAP_LOADING_SLICING) - -extern "C" void SliceAndSleep(const char* pFunc, int line) -{ - if (GetISystemScheduler()) - { - GetISystemScheduler()->SliceAndSleep(pFunc, line); - } -} - diff --git a/Code/CryEngine/CrySystem/SystemScheduler.h b/Code/CryEngine/CrySystem/SystemScheduler.h deleted file mode 100644 index feb6e2850c..0000000000 --- a/Code/CryEngine/CrySystem/SystemScheduler.h +++ /dev/null @@ -1,63 +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_CRYSYSTEM_SYSTEMSCHEDULER_H -#define CRYINCLUDE_CRYSYSTEM_SYSTEMSCHEDULER_H - -#pragma once - -#include "System.h" -#include - -class CSystemScheduler - : public ISystemScheduler -{ -public: - CSystemScheduler(CSystem* pSystem); - virtual ~CSystemScheduler(void); - - // ISystemScheduler - virtual void SliceAndSleep(const char* sliceName, int line); - virtual void SliceLoadingBegin(); - virtual void SliceLoadingEnd(); - - virtual void SchedulingSleepIfNeeded(void); - // ~ISystemScheduler - -protected: - void SchedulingModeUpdate(void); - -private: - CSystem* m_pSystem; - ICVar* m_svSchedulingAffinity; - ICVar* m_svSchedulingClientTimeout; - ICVar* m_svSchedulingServerTimeout; - ICVar* m_svSchedulingBucket; - ICVar* m_svSchedulingMode; - ICVar* m_svSliceLoadEnable; - ICVar* m_svSliceLoadBudget; - ICVar* m_svSliceLoadLogging; - - CTimeValue m_lastSliceCheckTime; - - int m_sliceLoadingRef; - - const char* m_pLastSliceName; - int m_lastSliceLine; -}; - -// Summary: -// Creates the system scheduler interface. -void CreateSystemScheduler(CSystem* pSystem); - -#endif // CRYINCLUDE_CRYSYSTEM_SYSTEMSCHEDULER_H diff --git a/Code/CryEngine/CrySystem/SystemThreading.cpp b/Code/CryEngine/CrySystem/SystemThreading.cpp deleted file mode 100644 index 9354e4e1c3..0000000000 --- a/Code/CryEngine/CrySystem/SystemThreading.cpp +++ /dev/null @@ -1,697 +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 "CrySystem_precompiled.h" -#include "System.h" -#include "ThreadConfigManager.h" -#include "IThreadManager.h" -#include -#include "CryUtils.h" - -#define INCLUDED_FROM_SYSTEM_THREADING_CPP - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define SYSTEMTHREADING_CPP_SECTION_1 1 -#define SYSTEMTHREADING_CPP_SECTION_2 2 -#define SYSTEMTHREADING_CPP_SECTION_3 3 -#endif - -#if defined(WIN32) || defined(WIN64) - #include "CryThreadUtil_win32_thread.h" -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMTHREADING_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(SystemThreading_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - #include "CryThreadUtil_pthread.h" -#endif -#undef INCLUDED_FROM_SYSTEM_THREADING_CPP - -////////////////////////////////////////////////////////////////////////// -static void ApplyThreadConfig(CryThreadUtil::TThreadHandle pThreadHandle, const SThreadConfig& rThreadDesc) -{ - // Apply config - if (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_ThreadName) - { - CryThreadUtil::CrySetThreadName(pThreadHandle, rThreadDesc.szThreadName); - } - if (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_Affinity) - { - CryThreadUtil::CrySetThreadAffinityMask(pThreadHandle, rThreadDesc.affinityFlag); - } - if (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_Priority) - { - CryThreadUtil::CrySetThreadPriority(pThreadHandle, rThreadDesc.priority); - } - if (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_PriorityBoost) - { - CryThreadUtil::CrySetThreadPriorityBoost(pThreadHandle, !rThreadDesc.bDisablePriorityBoost); - } - - CryComment(" Configured thread \"%s\" %s | AffinityMask: %u %s | Priority: %i %s | PriorityBoost: %s %s", - rThreadDesc.szThreadName, (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_ThreadName) ? "" : "(ignored)", - rThreadDesc.affinityFlag, (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_Affinity) ? "" : "(ignored)", - rThreadDesc.priority, (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_Priority) ? "" : "(ignored)", - !rThreadDesc.bDisablePriorityBoost ? "enabled" : "disabled", (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_PriorityBoost) ? "" : "(ignored)"); -} - -////////////////////////////////////////////////////////////////////////// -struct SThreadMetaData - : public CMultiThreadRefCount -{ - SThreadMetaData() - : m_pThreadTask(0) - , m_threadHandle(0) - , m_threadId(0) - , m_threadName("Cry_UnnamedThread") - , m_isRunning(false) - { - } - - IThread* m_pThreadTask; // Pointer to thread task to be executed - CThreadManager* m_pThreadMngr; // Pointer to thread manager - - CryThreadUtil::TThreadHandle m_threadHandle; // Thread handle - threadID m_threadId; // The active threadId, 0 = Invalid Id - - CryMutex m_threadExitMutex; // Mutex used to safeguard thread exit condition signaling - CryConditionVariable m_threadExitCondition; // Signaled when the thread is about to exit - - CryFixedStringT m_threadName; // Thread name - volatile bool m_isRunning; // Indicates the thread is not ready to exit yet -}; - -////////////////////////////////////////////////////////////////////////// -class CThreadManager - : public IThreadManager -{ -public: - // - virtual ~CThreadManager() - { - } - - virtual bool SpawnThread(IThread* pThread, const char* sThreadName, ...) override; - virtual bool JoinThread(IThread* pThreadTask, EJoinMode eJoinMode) override; - - virtual bool RegisterThirdPartyThread(void* pThreadHandle, const char* sThreadName, ...) override; - virtual bool UnRegisterThirdPartyThread(const char* sThreadName, ...) override; - - virtual const char* GetThreadName(threadID nThreadId) override; - virtual threadID GetThreadId(const char* sThreadName, ...) override; - - virtual void ForEachOtherThread(IThreadManager::ThreadModifFunction fpThreadModiFunction, void* pFuncData = 0) override; - - virtual void EnableFloatExceptions(EFPE_Severity eFPESeverity, threadID nThreadId = 0) override; - virtual void EnableFloatExceptionsForEachOtherThread(EFPE_Severity eFPESeverity) override; - - virtual uint GetFloatingPointExceptionMask() override; - virtual void SetFloatingPointExceptionMask(uint nMask) override; - - IThreadConfigManager* GetThreadConfigManager() override - { - return &m_threadConfigManager; - } - // -private: -#if defined(WIN32) || defined(WIN64) - static unsigned __stdcall RunThread(void* thisPtr); -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMTHREADING_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(SystemThreading_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - static void* RunThread(void* thisPtr); -#endif - -private: - bool UnregisterThread(IThread* pThreadTask); - - bool SpawnThreadImpl(IThread* pThread, const char* sThreadName); - - bool RegisterThirdPartyThreadImpl(CryThreadUtil::TThreadHandle pThreadHandle, const char* sThreadName); - bool UnRegisterThirdPartyThreadImpl(const char* sThreadName); - - threadID GetThreadIdImpl(const char* sThreadName); - -private: - // Note: Guard SThreadMetaData with a _smart_ptr and lock to ensure that a thread waiting to be signaled by another still - // has access to valid SThreadMetaData even though the other thread terminated and as a result unregistered itself from the CThreadManager. - // An example would be the join method. Where one thread waits on a signal from an other thread to terminate and release its SThreadMetaData, - // sharing the same SThreadMetaData condition variable. - typedef std::map > SpawnedThreadMap; - typedef std::map >::iterator SpawnedThreadMapIter; - typedef std::map >::const_iterator SpawnedThreadMapConstIter; - typedef std::pair > ThreadMapPair; - - typedef std::map, _smart_ptr > SpawnedThirdPartyThreadMap; - typedef std::map, _smart_ptr >::iterator SpawnedThirdPartyThreadMapIter; - typedef std::map, _smart_ptr >::const_iterator SpawnedThirdPartyThreadMapConstIter; - typedef std::pair, _smart_ptr > ThirdPartyThreadMapPair; - - CryCriticalSection m_spawnedThreadsLock; // Use lock for the rare occasion a thread is created/destroyed - SpawnedThreadMap m_spawnedThreads; // Holds information of all spawned threads (through this system) - - CryCriticalSection m_spawnedThirdPartyThreadsLock; // Use lock for the rare occasion a thread is created/destroyed - SpawnedThirdPartyThreadMap m_spawnedThirdPartyThread; // Holds information of all registered 3rd party threads (through this system) - - CThreadConfigManager m_threadConfigManager; -}; - -////////////////////////////////////////////////////////////////////////// -#if defined(WIN32) || defined(WIN64) -unsigned __stdcall CThreadManager::RunThread(void* thisPtr) -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMTHREADING_CPP_SECTION_3 -#include AZ_RESTRICTED_FILE(SystemThreading_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -void* CThreadManager::RunThread(void* thisPtr) -#endif -{ - // Check that we are not spawning a thread before gEnv->pSystem has been set - // Otherwise we cannot enable floating point exceptions - if (!gEnv || !gEnv->pSystem) - { - CryFatalError("[Error]: CThreadManager::RunThread requires gEnv->pSystem to be initialized."); - } - - IThreadConfigManager* pThreadConfigMngr = gEnv->pThreadManager->GetThreadConfigManager(); - - SThreadMetaData* pThreadData = reinterpret_cast(thisPtr); - pThreadData->m_threadId = CryThreadUtil::CryGetCurrentThreadId(); - - // Apply config - const SThreadConfig* pThreadConfig = pThreadConfigMngr->GetThreadConfig(pThreadData->m_threadName.c_str()); - ApplyThreadConfig(pThreadData->m_threadHandle, *pThreadConfig); - - // Config not found, append thread name with no config tag - if (pThreadConfig == pThreadConfigMngr->GetDefaultThreadConfig()) - { - CryFixedStringT tmpString(pThreadData->m_threadName); - const char* cNoConfigAppendix = "(NoCfgFound)"; - int nNumCharsToReplace = strlen(cNoConfigAppendix); - - // Replace thread name ending - if (pThreadData->m_threadName.size() > THREAD_NAME_LENGTH_MAX - nNumCharsToReplace) - { - tmpString.replace(THREAD_NAME_LENGTH_MAX - nNumCharsToReplace, nNumCharsToReplace, cNoConfigAppendix, nNumCharsToReplace); - } - else - { - tmpString.append(cNoConfigAppendix); - } - - // Print to log - if (pThreadConfigMngr->ConfigLoaded()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " No Thread config found for thread %s using ... default config.", pThreadData->m_threadName.c_str()); - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Thread config not loaded yet. Hence no thread config was found for thread %s ... using default config.", pThreadData->m_threadName.c_str()); - } - - // Rename Thread - CryThreadUtil::CrySetThreadName(pThreadData->m_threadHandle, tmpString.c_str()); - } - - // Enable FPEs - gEnv->pThreadManager->EnableFloatExceptions((EFPE_Severity)g_cvars.sys_float_exceptions); - - // Execute thread code - pThreadData->m_pThreadTask->ThreadEntry(); - - // Disable FPEs - gEnv->pThreadManager->EnableFloatExceptions(eFPE_None); - - // Signal imminent thread end - pThreadData->m_threadExitMutex.Lock(); - pThreadData->m_isRunning = false; - pThreadData->m_threadExitCondition.Notify(); - pThreadData->m_threadExitMutex.Unlock(); - - // Unregister thread - // Note: Unregister after m_threadExitCondition.Notify() to ensure pThreadData is still valid - pThreadData->m_pThreadMngr->UnregisterThread(pThreadData->m_pThreadTask); - - CryThreadUtil::CryThreadExitCall(); - - return NULL; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::JoinThread(IThread* pThreadTask, EJoinMode eJoinMode) -{ - // Get thread object - _smart_ptr pThreadImpl = 0; - { - AUTO_LOCK(m_spawnedThreadsLock); - - SpawnedThreadMapIter res = m_spawnedThreads.find(pThreadTask); - if (res == m_spawnedThreads.end()) - { - // Thread has already finished and unregistered itself. - // As it is complete we cannot wait for it. - // Hence return true. - return true; - } - - pThreadImpl = res->second; // Keep object alive - } - - // On try join, exit if the thread is not in a state to exit - if (eJoinMode == eJM_TryJoin && pThreadImpl->m_isRunning) - { - return false; - } - - // Wait for completion of the target thread exit condition - pThreadImpl->m_threadExitMutex.Lock(); - while (pThreadImpl->m_isRunning) - { - pThreadImpl->m_threadExitCondition.Wait(pThreadImpl->m_threadExitMutex); - } - pThreadImpl->m_threadExitMutex.Unlock(); - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::UnregisterThread(IThread* pThreadTask) -{ - AUTO_LOCK(m_spawnedThreadsLock); - - SpawnedThreadMapIter res = m_spawnedThreads.find(pThreadTask); - if (res == m_spawnedThreads.end()) - { - // Duplicate thread deletion - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": UnregisterThread: Unable to unregister thread. Thread name could not be found. Double deletion? IThread pointer: %p", pThreadTask); - return false; - } - - m_spawnedThreads.erase(res); - return true; -} - -////////////////////////////////////////////////////////////////////////// -const char* CThreadManager::GetThreadName(threadID nThreadId) -{ - // Loop over internally spawned threads - { - AUTO_LOCK(m_spawnedThreadsLock); - - SpawnedThreadMapConstIter iter = m_spawnedThreads.begin(); - SpawnedThreadMapConstIter iterEnd = m_spawnedThreads.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadId == nThreadId) - { - return iter->second->m_threadName.c_str(); - } - } - } - - // Loop over third party threads - { - AUTO_LOCK(m_spawnedThirdPartyThreadsLock); - - SpawnedThirdPartyThreadMapConstIter iter = m_spawnedThirdPartyThread.begin(); - SpawnedThirdPartyThreadMapConstIter iterEnd = m_spawnedThirdPartyThread.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadId == nThreadId) - { - return iter->second->m_threadName.c_str(); - } - } - } - - return ""; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadManager::ForEachOtherThread(IThreadManager::ThreadModifFunction fpThreadModiFunction, void* pFuncData) -{ - threadID nCurThreadId = CryThreadUtil::CryGetCurrentThreadId(); - - // Loop over internally spawned threads - { - AUTO_LOCK(m_spawnedThreadsLock); - - SpawnedThreadMapConstIter iter = m_spawnedThreads.begin(); - SpawnedThreadMapConstIter iterEnd = m_spawnedThreads.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadId != nCurThreadId) - { - fpThreadModiFunction(iter->second->m_threadId, pFuncData); - } - } - } - - // Loop over third party threads - { - AUTO_LOCK(m_spawnedThirdPartyThreadsLock); - - SpawnedThirdPartyThreadMapConstIter iter = m_spawnedThirdPartyThread.begin(); - SpawnedThirdPartyThreadMapConstIter iterEnd = m_spawnedThirdPartyThread.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadId != nCurThreadId) - { - fpThreadModiFunction(iter->second->m_threadId, pFuncData); - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::SpawnThread(IThread* pThreadTask, const char* sThreadName, ...) -{ - va_list args; - va_start(args, sThreadName); - - // Format thread name - char strThreadName[THREAD_NAME_LENGTH_MAX]; - const int cNumCharsNeeded = azvsnprintf(strThreadName, CRY_ARRAY_COUNT(strThreadName), sThreadName, args); - if (cNumCharsNeeded > THREAD_NAME_LENGTH_MAX - 1 || cNumCharsNeeded < 0) - { - strThreadName[THREAD_NAME_LENGTH_MAX - 1] = '\0'; // The WinApi only null terminates if strLen < bufSize - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": ThreadName \"%s\" has been truncated. Max characters allowed: %i. ", strThreadName, THREAD_NAME_LENGTH_MAX - 1); - } - - // Spawn thread - bool ret = SpawnThreadImpl(pThreadTask, strThreadName); - - if (!ret) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": CSystem::SpawnThread error spawning thread: \"%s\" ", strThreadName); - } - - va_end(args); - return ret; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::SpawnThreadImpl(IThread* pThreadTask, const char* sThreadName) -{ - if (pThreadTask == NULL) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, ": SpawnThread '%s' ThreadTask is NULL : ignoring", sThreadName); - return false; - } - - // Init thread meta data - SThreadMetaData* pThreadMetaData = new SThreadMetaData(); - pThreadMetaData->m_pThreadTask = pThreadTask; - pThreadMetaData->m_pThreadMngr = this; - pThreadMetaData->m_threadName = sThreadName; - - // Add thread to map - { - AUTO_LOCK(m_spawnedThreadsLock); - SpawnedThreadMapIter res = m_spawnedThreads.find(pThreadTask); - if (res != m_spawnedThreads.end()) - { - // Thread with same name already spawned - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": SpawnThread: Thread \"%s\" already exists.", sThreadName); - delete pThreadMetaData; - return false; - } - - // Insert thread data - m_spawnedThreads.insert(ThreadMapPair(pThreadTask, pThreadMetaData)); - } - - // Load config if we can and if no config has been defined to be loaded - const SThreadConfig* pThreadConfig = gEnv->pThreadManager->GetThreadConfigManager()->GetThreadConfig(sThreadName); - - // Create thread description - CryThreadUtil::SThreadCreationDesc desc = {sThreadName, RunThread, pThreadMetaData, pThreadConfig->paramActivityFlag & SThreadConfig::eThreadParamFlag_StackSize ? pThreadConfig->stackSizeBytes : 0}; - - // Spawn new thread - pThreadMetaData->m_isRunning = CryThreadUtil::CryCreateThread(&(pThreadMetaData->m_threadHandle), desc); - - // Validate thread creation - if (!pThreadMetaData->m_isRunning) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": SpawnThread: Could not spawn thread \"%s\" .", sThreadName); - - // Remove thread from map (also releases SThreadMetaData _smart_ptr) - m_spawnedThreads.erase(m_spawnedThreads.find(pThreadTask)); - return false; - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::RegisterThirdPartyThread(void* pThreadHandle, const char* sThreadName, ...) -{ - if (!pThreadHandle) - { - pThreadHandle = reinterpret_cast(CryThreadUtil::CryGetCurrentThreadHandle()); - } - - va_list args; - va_start(args, sThreadName); - - // Format thread name - char strThreadName[THREAD_NAME_LENGTH_MAX]; - const int cNumCharsNeeded = azvsnprintf(strThreadName, CRY_ARRAY_COUNT(strThreadName), sThreadName, args); - if (cNumCharsNeeded > THREAD_NAME_LENGTH_MAX - 1) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": ThreadName \"%s\" has been truncated. Max characters allowed: %i. ", strThreadName, THREAD_NAME_LENGTH_MAX - 1); - } - - // Register 3rd party thread - bool ret = RegisterThirdPartyThreadImpl(reinterpret_cast(pThreadHandle), strThreadName); - - va_end(args); - return ret; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::RegisterThirdPartyThreadImpl(CryThreadUtil::TThreadHandle threadHandle, const char* sThreadName) -{ - if (strcmp(sThreadName, "") == 0) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": CThreadManager::RegisterThirdPartyThread error registering third party thread. No name provided."); - return false; - } - // Init thread meta data - SThreadMetaData* pThreadMetaData = new SThreadMetaData(); - pThreadMetaData->m_pThreadTask = 0; - pThreadMetaData->m_pThreadMngr = this; - pThreadMetaData->m_threadName = sThreadName; - pThreadMetaData->m_threadHandle = CryThreadUtil::CryDuplicateThreadHandle(threadHandle); // Ensure that we are not storing a pseudo handle - pThreadMetaData->m_threadId = CryThreadUtil::CryGetThreadId(pThreadMetaData->m_threadHandle); - - { - AUTO_LOCK(m_spawnedThirdPartyThreadsLock); - - // Check for duplicate - SpawnedThirdPartyThreadMapConstIter res = m_spawnedThirdPartyThread.find(sThreadName); - if (res != m_spawnedThirdPartyThread.end()) - { - CryFatalError("CThreadManager::RegisterThirdPartyThread - Unable to register thread \"%s\"" - "because another third party thread with the same name \"%s\" has already been registered with ThreadHandle: %p", - sThreadName, res->second->m_threadName.c_str(), reinterpret_cast(threadHandle)); - - delete pThreadMetaData; - return false; - } - - // Insert thread data - m_spawnedThirdPartyThread.insert(ThirdPartyThreadMapPair(pThreadMetaData->m_threadName.c_str(), pThreadMetaData)); - } - - // Get thread config - const SThreadConfig* pThreadConfig = gEnv->pThreadManager->GetThreadConfigManager()->GetThreadConfig(sThreadName); - - // Apply config (if not default config) - if (strcmp(pThreadConfig->szThreadName, sThreadName) == 0) - { - ApplyThreadConfig(threadHandle, *pThreadConfig); - } - - // Update FP exception mask for 3rd party thread - if (pThreadMetaData->m_threadId) - { - CryThreadUtil::EnableFloatExceptions(pThreadMetaData->m_threadId, (EFPE_Severity)g_cvars.sys_float_exceptions); - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::UnRegisterThirdPartyThread(const char* sThreadName, ...) -{ - va_list args; - va_start(args, sThreadName); - - // Format thread name - char strThreadName[THREAD_NAME_LENGTH_MAX]; - const int cNumCharsNeeded = azvsnprintf(strThreadName, CRY_ARRAY_COUNT(strThreadName), sThreadName, args); - if (cNumCharsNeeded > THREAD_NAME_LENGTH_MAX - 1) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": ThreadName \"%s\" has been truncated. Max characters allowed: %i. ", strThreadName, THREAD_NAME_LENGTH_MAX - 1); - } - - // Unregister 3rd party thread - bool ret = UnRegisterThirdPartyThreadImpl(strThreadName); - - va_end(args); - return ret; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::UnRegisterThirdPartyThreadImpl(const char* sThreadName) -{ - AUTO_LOCK(m_spawnedThirdPartyThreadsLock); - - SpawnedThirdPartyThreadMapIter res = m_spawnedThirdPartyThread.find(sThreadName); - if (res == m_spawnedThirdPartyThread.end()) - { - // Duplicate thread deletion - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": UnRegisterThirdPartyThread: Unable to unregister thread. Thread name \"%s\" could not be found. Double deletion? ", sThreadName); - return false; - } - - // Close thread handle - CryThreadUtil::CryCloseThreadHandle(res->second->m_threadHandle); - - // Delete reference from container - m_spawnedThirdPartyThread.erase(res); - return true; -} - -////////////////////////////////////////////////////////////////////////// -threadID CThreadManager::GetThreadId(const char* sThreadName, ...) -{ - va_list args; - va_start(args, sThreadName); - - // Format thread name - char strThreadName[THREAD_NAME_LENGTH_MAX]; - const int cNumCharsNeeded = azvsnprintf(strThreadName, CRY_ARRAY_COUNT(strThreadName), sThreadName, args); - if (cNumCharsNeeded > THREAD_NAME_LENGTH_MAX - 1) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": ThreadName \"%s\" has been truncated. Max characters allowed: %i. ", strThreadName, THREAD_NAME_LENGTH_MAX - 1); - } - - // Get thread name - threadID ret = GetThreadIdImpl(strThreadName); - - va_end(args); - return ret; -} - -////////////////////////////////////////////////////////////////////////// -threadID CThreadManager::GetThreadIdImpl(const char* sThreadName) -{ - // Loop over internally spawned threads - { - AUTO_LOCK(m_spawnedThreadsLock); - - SpawnedThreadMapConstIter iter = m_spawnedThreads.begin(); - SpawnedThreadMapConstIter iterEnd = m_spawnedThreads.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadName.compare(sThreadName) == 0) - { - return iter->second->m_threadId; - } - } - } - - // Loop over third party threads - { - AUTO_LOCK(m_spawnedThirdPartyThreadsLock); - - SpawnedThirdPartyThreadMapConstIter iter = m_spawnedThirdPartyThread.begin(); - SpawnedThirdPartyThreadMapConstIter iterEnd = m_spawnedThirdPartyThread.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadName.compare(sThreadName) == 0) - { - return iter->second->m_threadId; - } - } - } - - return 0; -} - -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -static void EnableFPExceptionsForThread(threadID nThreadId, void* pData) -{ - EFPE_Severity eFPESeverity = *(EFPE_Severity*)pData; - CryThreadUtil::EnableFloatExceptions(nThreadId, eFPESeverity); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadManager::EnableFloatExceptions(EFPE_Severity eFPESeverity, threadID nThreadId /*=0*/) -{ - CryThreadUtil::EnableFloatExceptions(nThreadId, eFPESeverity); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadManager::EnableFloatExceptionsForEachOtherThread(EFPE_Severity eFPESeverity) -{ - ForEachOtherThread(EnableFPExceptionsForThread, &eFPESeverity); -} - -////////////////////////////////////////////////////////////////////////// -uint CThreadManager::GetFloatingPointExceptionMask() -{ - return CryThreadUtil::GetFloatingPointExceptionMask(); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadManager::SetFloatingPointExceptionMask(uint nMask) -{ - CryThreadUtil::SetFloatingPointExceptionMask(nMask); -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::InitThreadSystem() -{ - m_pThreadManager = new CThreadManager(); - m_env.pThreadManager = m_pThreadManager; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::ShutDownThreadSystem() -{ - SAFE_DELETE(m_pThreadManager); -} diff --git a/Code/CryEngine/CrySystem/SystemWin32.cpp b/Code/CryEngine/CrySystem/SystemWin32.cpp index c694979a14..72c43bceed 100644 --- a/Code/CryEngine/CrySystem/SystemWin32.cpp +++ b/Code/CryEngine/CrySystem/SystemWin32.cpp @@ -46,8 +46,6 @@ #include #endif -#include "IDebugCallStack.h" - #if defined(APPLE) || defined(LINUX) #include #endif @@ -752,13 +750,6 @@ void CSystem::FatalError(const char* format, ...) } // Dump callstack. -#endif -#if defined (WIN32) - //Triggers a fatal error, so the DebugCallstack can create the error.log and terminate the application - IDebugCallStack::instance()->FatalError(szBuffer); -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMWIN32_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(SystemWin32_cpp) #endif CryDebugBreak(); @@ -800,8 +791,6 @@ void CSystem::ReportBug([[maybe_unused]] const char* format, ...) va_start(ArgList, format); azvsnprintf(szBuffer + strlen(sPrefix), MAX_WARNING_LENGTH - strlen(sPrefix), format, ArgList); va_end(ArgList); - - IDebugCallStack::instance()->ReportBug(szBuffer); #endif } @@ -910,10 +899,6 @@ void CSystem::LogSystemInfo() OSVERSIONINFO OSVerInfo; OSVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - // log Windows type - Win32SysInspect::GetOS(m_env.pi.winVer, m_env.pi.win64Bit, szBuffer, sizeof(szBuffer)); - CryLogAlways(szBuffer); - // log system language GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SENGLANGUAGE, szLanguageBuffer, sizeof(szLanguageBuffer)); azsprintf(szBuffer, "System language: %s", szLanguageBuffer); diff --git a/Code/CryEngine/CrySystem/ThreadConfigManager.cpp b/Code/CryEngine/CrySystem/ThreadConfigManager.cpp deleted file mode 100644 index b582aac578..0000000000 --- a/Code/CryEngine/CrySystem/ThreadConfigManager.cpp +++ /dev/null @@ -1,577 +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 "CrySystem_precompiled.h" -#include "ThreadConfigManager.h" -#include "IConsole.h" -#include "System.h" -#include -#include -#include "CryUtils.h" -namespace -{ - const char* sCurThreadConfigFilename = ""; - const uint32 sPlausibleStackSizeLimitKB = (1024 * 100); // 100mb -} - -////////////////////////////////////////////////////////////////////////// -CThreadConfigManager::CThreadConfigManager() -{ - m_defaultConfig.szThreadName = "CryThread_Unnamed"; - m_defaultConfig.stackSizeBytes = 0; - m_defaultConfig.affinityFlag = -1; - m_defaultConfig.priority = THREAD_PRIORITY_NORMAL; - m_defaultConfig.bDisablePriorityBoost = false; - m_defaultConfig.paramActivityFlag = (SThreadConfig::TThreadParamFlag)~0; -} - -////////////////////////////////////////////////////////////////////////// -const SThreadConfig* CThreadConfigManager::GetThreadConfig(const char* szThreadName, ...) -{ - va_list args; - va_start(args, szThreadName); - - // Format thread name - char strThreadName[THREAD_NAME_LENGTH_MAX]; - const int cNumCharsNeeded = azvsnprintf(strThreadName, CRY_ARRAY_COUNT(strThreadName), szThreadName, args); - if (cNumCharsNeeded > THREAD_NAME_LENGTH_MAX - 1) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": ThreadName \"%s\" has been truncated. Max characters allowed: %i. ", strThreadName, THREAD_NAME_LENGTH_MAX - 1); - } - - // Get Thread Config - const SThreadConfig* retThreasdConfig = GetThreadConfigImpl(strThreadName); - - va_end(args); - return retThreasdConfig; -} - -////////////////////////////////////////////////////////////////////////// -const SThreadConfig* CThreadConfigManager::GetThreadConfigImpl(const char* szThreadName) -{ - // Get thread config for platform - ThreadConfigMapConstIter threatRet = m_threadConfig.find(CryFixedStringT(szThreadName)); - if (threatRet == m_threadConfig.end()) - { - // Search in wildcard setups - ThreadConfigMapConstIter wildCardIter = m_wildcardThreadConfig.begin(); - ThreadConfigMapConstIter wildCardIterEnd = m_wildcardThreadConfig.end(); - for (; wildCardIter != wildCardIterEnd; ++wildCardIter) - { - if (CryStringUtils::MatchWildcard(szThreadName, wildCardIter->second.szThreadName)) - { - // Store new thread config - SThreadConfig threadConfig = wildCardIter->second; - std::pair res; - res = m_threadConfig.insert(ThreadConfigMapPair(CryFixedStringT(szThreadName), threadConfig)); - - // Store name (ref to key) - SThreadConfig& rMapThreadConfig = res.first->second; - rMapThreadConfig.szThreadName = res.first->first.c_str(); - - // Return new thread config - return &res.first->second; - } - } - - // Failure case, no match found - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": Unable to find config for thread:%s", szThreadName); - return &m_defaultConfig; - } - - // Return thread config - return &threatRet->second; -} - -////////////////////////////////////////////////////////////////////////// -const SThreadConfig* CThreadConfigManager::GetDefaultThreadConfig() const -{ - return &m_defaultConfig; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadConfigManager::LoadConfig(const char* pcPath) -{ - // Adjust filename for OnDisk or in .pak file loading - char szFullPathBuf[AZ::IO::IArchive::MaxPath]; - gEnv->pCryPak->AdjustFileName(pcPath, szFullPathBuf, AZ_ARRAY_SIZE(szFullPathBuf), 0); - - // Open file - XmlNodeRef xmlRoot = GetISystem()->LoadXmlFromFile(szFullPathBuf); - if (!xmlRoot) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": File \"%s\" not found!", pcPath); - return false; - } - - // Load config for active platform - sCurThreadConfigFilename = pcPath; - const char* strPlatformId = IdentifyPlatform(); - CryFixedStringT<32> tmpPlatformStr; - bool retValue = false; - - // Try load common platform settings - tmpPlatformStr.Format("%s_Common", strPlatformId); - LoadPlatformConfig(xmlRoot, tmpPlatformStr.c_str()); - -#if defined(CRY_PLATFORM_DESKTOP) - // Handle PC specifically as we do not know the core setup of the executing machine. - // Try and find the next power of 2 core setup. Otherwise fallback to a lower power of 2 core setup spec - - // Try and load next pow of 2 setup for active pc core configuration - const unsigned int numCPUs = ((CSystem*)GetISystem())->GetCPUFeatures()->GetLogicalCPUCount(); - uint32 i = numCPUs; - for (; i > 0; --i) - { - tmpPlatformStr.Format("%s_%i", strPlatformId, i); - retValue = LoadPlatformConfig(xmlRoot, tmpPlatformStr.c_str()); - if (retValue) - { - break; - } - } - - if (retValue && i != numCPUs) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": (%s: %u core) Unable to find platform config \"%s\". Next valid config found was %s_%u.", - strPlatformId, numCPUs, tmpPlatformStr.c_str(), strPlatformId, i); - } - -#else - tmpPlatformStr.Format("%s", strPlatformId); - retValue = LoadPlatformConfig(xmlRoot, strPlatformId); -#endif - - // Print out info - if (retValue) - { - CryLogAlways(": Thread profile loaded: \"%s\" (%s) ", tmpPlatformStr.c_str(), pcPath); - } - else - { - // Could not find any matching platform - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": Active platform identifier string \"%s\" not found in config \"%s\".", strPlatformId, sCurThreadConfigFilename); - } - - sCurThreadConfigFilename = ""; - return retValue; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadConfigManager::ConfigLoaded() const -{ - return !m_threadConfig.empty(); -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadConfigManager::LoadPlatformConfig(const XmlNodeRef& rXmlRoot, const char* sPlatformId) -{ - // Validate node - if (!rXmlRoot->isTag("ThreadConfig")) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": Unable to find root xml node \"ThreadConfig\""); - return false; - } - - // Find active platform - const uint32 numPlatforms = rXmlRoot->getChildCount(); - for (uint32 i = 0; i < numPlatforms; ++i) - { - const XmlNodeRef xmlPlatformNode = rXmlRoot->getChild(i); - - // Is platform node - if (!xmlPlatformNode->isTag("Platform")) - { - continue; - } - - // Is has Name attribute - if (!xmlPlatformNode->haveAttr("Name")) - { - continue; - } - - // Is platform of interest - const char* platformName = xmlPlatformNode->getAttr("Name"); - if (_stricmp(sPlatformId, platformName) == 0) - { - // Load platform - LoadThreadDefaultConfig(xmlPlatformNode); - LoadPlatformThreadConfigs(xmlPlatformNode); - return true; - } - } - - return false; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadPlatformThreadConfigs(const XmlNodeRef& rXmlPlatformRef) -{ - // Get thread configurations for active platform - const uint32 numThreads = rXmlPlatformRef->getChildCount(); - for (uint32 j = 0; j < numThreads; ++j) - { - const XmlNodeRef xmlThreadNode = rXmlPlatformRef->getChild(j); - - if (!xmlThreadNode->isTag("Thread")) - { - continue; - } - - // Ensure thread config has name - if (!xmlThreadNode->haveAttr("Name")) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Thread node without \"name\" attribute encountered."); - continue; - } - - // Load thread config - SThreadConfig loadedThreadConfig = SThreadConfig(m_defaultConfig); - LoadThreadConfig(xmlThreadNode, loadedThreadConfig); - - // Get thread name and check if it contains wildcard characters - const char* szThreadName = xmlThreadNode->getAttr("Name"); - bool bWildCard = strchr(szThreadName, '*') ? true : false; - ThreadConfigMap& threadConfig = bWildCard ? m_wildcardThreadConfig : m_threadConfig; - - // Check for duplicate and override it with new config if found - if (threadConfig.find(szThreadName) != threadConfig.end()) - { - CryLogAlways(": [XML Parsing] Thread with name \"%s\" already loaded. Overriding with new configuration", szThreadName); - threadConfig[szThreadName] = loadedThreadConfig; - continue; - } - - // Store new thread config - std::pair res; - res = threadConfig.insert(ThreadConfigMapPair(CryFixedStringT(szThreadName), loadedThreadConfig)); - - // Store name (ref to key) - SThreadConfig& rMapThreadConfig = res.first->second; - rMapThreadConfig.szThreadName = res.first->first.c_str(); - } -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadConfigManager::LoadThreadDefaultConfig(const XmlNodeRef& rXmlPlatformRef) -{ - // Find default thread config node - const uint32 numNodes = rXmlPlatformRef->getChildCount(); - for (uint32 j = 0; j < numNodes; ++j) - { - const XmlNodeRef xmlNode = rXmlPlatformRef->getChild(j); - - // Load default config - if (xmlNode->isTag("ThreadDefault")) - { - LoadThreadConfig(xmlNode, m_defaultConfig); - return true; - } - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadAffinity(const XmlNodeRef& rXmlThreadRef, uint32& rAffinity, SThreadConfig::TThreadParamFlag& rParamActivityFlag) -{ - const char* szValidCharacters = "-,0123456789"; - uint32 affinity = 0; - - // Validate node - if (!rXmlThreadRef->haveAttr("Affinity")) - { - return; - } - - // Validate token - CryFixedStringT<32> affinityRawStr(rXmlThreadRef->getAttr("Affinity")); - if (affinityRawStr.empty()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Empty attribute \"Affinity\" encountered"); - return; - } - - if (affinityRawStr.compareNoCase("ignore") == 0) - { - // Param is inactive, clear bit - rParamActivityFlag &= ~SThreadConfig::eThreadParamFlag_Affinity; - return; - } - - CryFixedStringT<32>::size_type nPos = affinityRawStr.find_first_not_of(" -,0123456789"); - if (nPos != CryFixedStringT<32>::npos) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, - ": [XML Parsing] Invalid character \"%c\" encountered in \"Affinity\" attribute. Valid characters:\"%s\" Offending token:\"%s\"", affinityRawStr.at(nPos), - szValidCharacters, affinityRawStr.c_str()); - return; - } - - // Tokenize comma separated string - int pos = 0; - CryFixedStringT<32> affnityTokStr = affinityRawStr.Tokenize(",", pos); - while (!affnityTokStr.empty()) - { - affnityTokStr.Trim(); - - long affinityId = strtol(affnityTokStr.c_str(), NULL, 10); - if (affinityId == LONG_MAX || affinityId == LONG_MIN) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Unknown value \"%s\" encountered for attribute \"Affinity\"", affnityTokStr.c_str()); - return; - } - - // Allow scheduler to pick thread - if (affinityId == -1) - { - affinity = ~0; - break; - } - - // Set affinity bit - affinity |= BIT(affinityId); - - // Move to next token - affnityTokStr = affinityRawStr.Tokenize(",", pos); - } - - // Set affinity reference - rAffinity = affinity; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadPriority(const XmlNodeRef& rXmlThreadRef, int32& rPriority, SThreadConfig::TThreadParamFlag& rParamActivityFlag) -{ - const char* szValidCharacters = "-,0123456789"; - - // Validate node - if (!rXmlThreadRef->haveAttr("Priority")) - { - return; - } - - // Validate token - CryFixedStringT<32> threadPrioStr(rXmlThreadRef->getAttr("Priority")); - threadPrioStr.Trim(); - if (threadPrioStr.empty()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Empty attribute \"Priority\" encountered"); - return; - } - - if (threadPrioStr.compareNoCase("ignore") == 0) - { - // Param is inactive, clear bit - rParamActivityFlag &= ~SThreadConfig::eThreadParamFlag_Priority; - return; - } - - // Test for character string (no numbers allowed) - if (threadPrioStr.find_first_of(szValidCharacters) == CryFixedStringT<32>::npos) - { - threadPrioStr.MakeLower(); - - // Set priority - if (threadPrioStr.compare("below_normal") == 0) - { - rPriority = THREAD_PRIORITY_BELOW_NORMAL; - } - else if (threadPrioStr.compare("normal") == 0) - { - rPriority = THREAD_PRIORITY_NORMAL; - } - else if (threadPrioStr.compare("above_normal") == 0) - { - rPriority = THREAD_PRIORITY_ABOVE_NORMAL; - } - else if (threadPrioStr.compare("idle") == 0) - { - rPriority = THREAD_PRIORITY_IDLE; - } - else if (threadPrioStr.compare("lowest") == 0) - { - rPriority = THREAD_PRIORITY_LOWEST; - } - else if (threadPrioStr.compare("highest") == 0) - { - rPriority = THREAD_PRIORITY_HIGHEST; - } - else if (threadPrioStr.compare("time_critical") == 0) - { - rPriority = THREAD_PRIORITY_TIME_CRITICAL; - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Platform unsupported value \"%s\" encountered for attribute \"Priority\"", threadPrioStr.c_str()); - return; - } - } - // Test for number string (no alphabetical characters allowed) - else if (threadPrioStr.find_first_not_of(szValidCharacters) == CryFixedStringT<32>::npos) - { - long numValue = strtol(threadPrioStr.c_str(), NULL, 10); - if (numValue == LONG_MAX || numValue == LONG_MIN) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Unsupported number type \"%s\" for for attribute \"Priority\"", threadPrioStr.c_str()); - return; - } - - // Set priority - rPriority = numValue; - } - else - { - // String contains characters and numbers - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Unsupported type \"%s\" encountered for attribute \"Priority\". Token containers numbers and characters", threadPrioStr.c_str()); - return; - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadDisablePriorityBoost(const XmlNodeRef& rXmlThreadRef, bool& rPriorityBoost, SThreadConfig::TThreadParamFlag& rParamActivityFlag) -{ - // Validate node - if (!rXmlThreadRef->haveAttr("DisablePriorityBoost")) - { - return; - } - - // Extract bool info - CryFixedStringT<16> sAttribToken(rXmlThreadRef->getAttr("DisablePriorityBoost")); - sAttribToken.Trim(); - sAttribToken.MakeLower(); - - if (sAttribToken.compare("ignore") == 0) - { - // Param is inactive, clear bit - rParamActivityFlag &= ~SThreadConfig::eThreadParamFlag_PriorityBoost; - return; - } - else if (sAttribToken.compare("true") == 0 || sAttribToken.compare("1") == 0) - { - rPriorityBoost = true; - } - else if (sAttribToken.compare("false") == 0 || sAttribToken.compare("0") == 0) - { - rPriorityBoost = false; - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Unsupported bool type \"%s\" encountered for attribute \"DisablePriorityBoost\"", - rXmlThreadRef->getAttr("DisablePriorityBoost")); - return; - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadStackSize(const XmlNodeRef& rXmlThreadRef, uint32& rStackSize, SThreadConfig::TThreadParamFlag& rParamActivityFlag) -{ - const char* sValidCharacters = "0123456789"; - - if (rXmlThreadRef->haveAttr("StackSizeKB")) - { - // Read stack size - CryFixedStringT<32> stackSize(rXmlThreadRef->getAttr("StackSizeKB")); - - // Validate stack size - if (stackSize.empty()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Empty attribute \"StackSize\" encountered"); - return; - } - else if (stackSize.compareNoCase("ignore") == 0) - { - // Param is inactive, clear bit - rParamActivityFlag &= ~SThreadConfig::eThreadParamFlag_StackSize; - return; - } - else if (stackSize.find_first_not_of(sValidCharacters) == CryFixedStringT<32>::npos) - { - // Convert string to long - long stackSizeVal = strtol(stackSize.c_str(), NULL, 10); - if (stackSizeVal == LONG_MAX || stackSizeVal == LONG_MIN) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Invalid number for \"StackSize\" encountered. \"%s\"", stackSize.c_str()); - return; - } - else if (stackSizeVal <= 0 || stackSizeVal > sPlausibleStackSizeLimitKB) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] \"StackSize\" value not plausible \"%" PRId64 "KB\"", (int64)stackSizeVal); - return; - } - - // Set stack size - rStackSize = stackSizeVal * 1024; // Convert to bytes - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadThreadConfig(const XmlNodeRef& rXmlThreadRef, SThreadConfig& rThreadConfig) -{ - LoadAffinity(rXmlThreadRef, rThreadConfig.affinityFlag, rThreadConfig.paramActivityFlag); - LoadPriority(rXmlThreadRef, rThreadConfig.priority, rThreadConfig.paramActivityFlag); - LoadDisablePriorityBoost(rXmlThreadRef, rThreadConfig.bDisablePriorityBoost, rThreadConfig.paramActivityFlag); - LoadStackSize(rXmlThreadRef, rThreadConfig.stackSizeBytes, rThreadConfig.paramActivityFlag); -} - -////////////////////////////////////////////////////////////////////////// -const char* CThreadConfigManager::IdentifyPlatform() -{ -#if defined(AZ_RESTRICTED_PLATFORM) -#include AZ_RESTRICTED_FILE(ThreadConfigManager_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(ANDROID) - return "android"; -#elif defined(LINUX) - return "linux"; -#elif defined(APPLE) - return "mac"; -#elif defined(WIN32) || defined(WIN64) - return "pc"; -#else -#error "Undefined platform" -#endif -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::DumpThreadConfigurationsToLog() -{ -#if !defined(RELEASE) - - // Print header - CryLogAlways("== Thread Startup Config List (\"%s\") ==", IdentifyPlatform()); - - // Print loaded default config - CryLogAlways(" (Default) 1. \"%s\" (StackSize:%uKB | Affinity:%u | Priority:%i | PriorityBoost:\"%s\")", m_defaultConfig.szThreadName, m_defaultConfig.stackSizeBytes / 1024, - m_defaultConfig.affinityFlag, m_defaultConfig.priority, m_defaultConfig.bDisablePriorityBoost ? "disabled" : "enabled"); - - // Print loaded thread configs - int listItemCounter = 1; - ThreadConfigMapConstIter iter = m_threadConfig.begin(); - ThreadConfigMapConstIter iterEnd = m_threadConfig.end(); - for (; iter != iterEnd; ++iter) - { - const SThreadConfig& threadConfig = iter->second; - CryLogAlways("%3d.\"%s\" %s (StackSize:%uKB %s | Affinity:%u %s | Priority:%i %s | PriorityBoost:\"%s\" %s)", ++listItemCounter, - threadConfig.szThreadName, (threadConfig.paramActivityFlag & SThreadConfig::eThreadParamFlag_ThreadName) ? "" : "(ignored)", - threadConfig.stackSizeBytes / 1024u, (threadConfig.paramActivityFlag & SThreadConfig::eThreadParamFlag_StackSize) ? "" : "(ignored)", - threadConfig.affinityFlag, (threadConfig.paramActivityFlag & SThreadConfig::eThreadParamFlag_Affinity) ? "" : "(ignored)", - threadConfig.priority, (threadConfig.paramActivityFlag & SThreadConfig::eThreadParamFlag_Priority) ? "" : "(ignored)", - !threadConfig.bDisablePriorityBoost ? "enabled" : "disabled", (threadConfig.paramActivityFlag & SThreadConfig::eThreadParamFlag_PriorityBoost) ? "" : "(ignored)"); - } -#endif -} diff --git a/Code/CryEngine/CrySystem/ThreadConfigManager.h b/Code/CryEngine/CrySystem/ThreadConfigManager.h deleted file mode 100644 index ef0c9dca3d..0000000000 --- a/Code/CryEngine/CrySystem/ThreadConfigManager.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include -#include "IThreadConfigManager.h" - -/* -ThreadConfigManager: -Loads a thread configuration from an xml file and stores them. - -== XML File Layout and Rules: === - -= Platform names = -(case insensitive) -"ANDROID" -"PC" -"MAC" -etc. - -= Basic Layout = - - - - - -... - - - -... - - - -= Parser Order for Platform = -1. PlatformName_Common (valid for all potential platform configurations. Can be overridden by concert platform configuration) -2. PlatformName or PlatformName_X (for platforms with unknown CPU count where X is the number of potential cores. The equal or next lower matching configuration for the identified core count at runtime will be taken) - -Note: Overriding of thread configuration by later parsed configuration allowed. - -= and XML attributes = - -!!! -Note: Use "ignore" as value if you do not want the thread system to set the value specifically! - If a value is not defines the value of the parameter will be used. - This is useful when dealing with 3rdParty threads where you are not in control of the parameter setup. -!!! - -Name: - "x" (string) : Name of thread - "x*y" (string) : Name of thread with wildcard character - -Affinity: - "-1" : Put SW thread affinity in the hands of the scheduler - (default) - - "x" : Run thread on specified core - "x, y, ..." : Run thread on specified cores - -Priority: - "idle" : Hint to CryEngine to run thread with pre-set priority - "below_normal" : Hint to CryEngine to run thread with pre-set priority - "normal" : Hint to CryEngine to run thread with pre-set priority - (default) - - "above_normal" : Hint to CryEngine to run thread with pre-set priority - "highest" : Hint to CryEngine to run thread with pre-set priority - "time_critical" : Hint to CryEngine to run thread with pre-set priority - "x" (number) : User defined thread priority number - -StackSizeKB: - "0" : Let platform decide on the stack size - (default) - - "x" : Create thread with "x" KB of stack size - -DisablePriorityBoost: - "true" : Disable priority boosting - (default) - - "false" : Enable priority boosting -*/ - -class CThreadConfigManager - : public IThreadConfigManager -{ -public: - typedef std::map, SThreadConfig> ThreadConfigMap; - typedef std::pair, SThreadConfig> ThreadConfigMapPair; - typedef std::map, SThreadConfig>::iterator ThreadConfigMapIter; - typedef std::map, SThreadConfig>::const_iterator ThreadConfigMapConstIter; - -public: - CThreadConfigManager(); - ~CThreadConfigManager() - { - } - - // Called once during System startup. - // Loads the thread configuration for the executing platform from file. - virtual bool LoadConfig(const char* pcPath) override; - - // Returns true if a config has been loaded - virtual bool ConfigLoaded() const override; - - // Gets the thread configuration for the specified thread on the active platform. - // If no matching config is found a default configuration is returned - // (which does not have the same name as the search string). - virtual const SThreadConfig* GetThreadConfig(const char* sThreadName, ...) override; - virtual const SThreadConfig* GetDefaultThreadConfig() const override; - - virtual void DumpThreadConfigurationsToLog() override; - -private: - const char* IdentifyPlatform(); - - const SThreadConfig* GetThreadConfigImpl(const char* cThreadName); - - bool LoadPlatformConfig(const XmlNodeRef& rXmlRoot, const char* sPlatformId); - - void LoadPlatformThreadConfigs(const XmlNodeRef& rXmlPlatformRef); - bool LoadThreadDefaultConfig(const XmlNodeRef& rXmlPlatformRef); - void LoadThreadConfig(const XmlNodeRef& rXmlThreadRef, SThreadConfig& rThreadConfig); - - void LoadAffinity(const XmlNodeRef& rXmlThreadRef, uint32& rAffinity, SThreadConfig::TThreadParamFlag& rParamActivityFlag); - void LoadPriority(const XmlNodeRef& rXmlThreadRef, int32& rPriority, SThreadConfig::TThreadParamFlag& rParamActivityFlag); - void LoadDisablePriorityBoost(const XmlNodeRef& rXmlThreadRef, bool& rPriorityBoost, SThreadConfig::TThreadParamFlag& rParamActivityFlag); - void LoadStackSize(const XmlNodeRef& rXmlThreadRef, uint32& rStackSize, SThreadConfig::TThreadParamFlag& rParamActivityFlag); - -private: - ThreadConfigMap m_threadConfig; // Note: The map key is referenced by as const char* by the value's storage class. Other containers may not support this behaviour as they will re-allocate memory as they grow/shrink. - ThreadConfigMap m_wildcardThreadConfig; - SThreadConfig m_defaultConfig; -}; diff --git a/Code/CryEngine/CrySystem/ThreadInfo.cpp b/Code/CryEngine/CrySystem/ThreadInfo.cpp deleted file mode 100644 index 14285215b8..0000000000 --- a/Code/CryEngine/CrySystem/ThreadInfo.cpp +++ /dev/null @@ -1,123 +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 "CrySystem_precompiled.h" -#include "ThreadInfo.h" -#include "System.h" - -//////////////////////////////////////////////////////////////////////////// - - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define THREADINFO_CPP_SECTION_1 1 -#define THREADINFO_CPP_SECTION_2 2 -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION THREADINFO_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(ThreadInfo_cpp) -#endif - -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -#if AZ_LEGACY_CRYSYSTEM_TRAIT_THREADINFO_WINDOWS_STYLE -//////////////////////////////////////////////////////////////////////////// -void SThreadInfo::GetCurrentThreads(TThreadInfo& threadsOut) -{ - HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); - DWORD currProcessId = GetCurrentProcessId(); - if (h != INVALID_HANDLE_VALUE) - { - THREADENTRY32 te; - te.dwSize = sizeof(te); - if (Thread32First(h, &te)) - { - do - { - if (te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(te.th32OwnerProcessID)) - { - if (te.th32OwnerProcessID == currProcessId) - { - threadsOut[te.th32ThreadID] = CryThreadGetName(te.th32ThreadID); - } - } - te.dwSize = sizeof(te); - } while (Thread32Next(h, &te)); - } - CloseHandle(h); - } -} - -//////////////////////////////////////////////////////////////////////////// -void SThreadInfo::OpenThreadHandles(TThreads& threadsOut, const TThreadIds& threadIds /* = TThreadIds()*/, bool ignoreCurrThread /* = true*/) -{ - TThreadIds threadids = threadIds; - if (threadids.empty()) - { - TThreadInfo threads; - GetCurrentThreads(threads); - DWORD currThreadId = GetCurrentThreadId(); - for (TThreadInfo::iterator it = threads.begin(), end = threads.end(); it != end; ++it) - { - if (!ignoreCurrThread || it->first != currThreadId) - { - threadids.push_back(it->first); - } - } - } - for (TThreadIds::iterator it = threadids.begin(), end = threadids.end(); it != end; ++it) - { - SThreadHandle thread; - thread.Id = *it; - thread.Handle = OpenThread(THREAD_ALL_ACCESS, FALSE, *it); - threadsOut.push_back(thread); - } -} - -//////////////////////////////////////////////////////////////////////////// -void SThreadInfo::CloseThreadHandles(const TThreads& threads) -{ - for (TThreads::const_iterator it = threads.begin(), end = threads.end(); it != end; ++it) - { - CloseHandle(it->Handle); - } -} - -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION THREADINFO_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(ThreadInfo_cpp) -#elif defined(LINUX) || defined(APPLE) -void SThreadInfo::GetCurrentThreads(TThreadInfo& threadsOut) -{ - assert(false); // not implemented! -} - -//////////////////////////////////////////////////////////////////////////// -void SThreadInfo::OpenThreadHandles(TThreads& threadsOut, const TThreadIds& threadIds /* = TThreadIds()*/, bool ignoreCurrThread /* = true*/) -{ - assert(false); // not implemented! -} - -//////////////////////////////////////////////////////////////////////////// -void SThreadInfo::CloseThreadHandles(const TThreads& threads) -{ - assert(false); // not implemented! -} - -//////////////////////////////////////////////////////////////////////////// -#endif diff --git a/Code/CryEngine/CrySystem/ThreadInfo.h b/Code/CryEngine/CrySystem/ThreadInfo.h deleted file mode 100644 index 4bcacf71d5..0000000000 --- a/Code/CryEngine/CrySystem/ThreadInfo.h +++ /dev/null @@ -1,43 +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_CRYSYSTEM_THREADINFO_H -#define CRYINCLUDE_CRYSYSTEM_THREADINFO_H -#pragma once - - -struct SThreadInfo -{ -public: - struct SThreadHandle - { - HANDLE Handle; - uint32 Id; - }; - - typedef std::vector TThreadIds; - typedef std::vector TThreads; - typedef std::map TThreadInfo; - - // returns thread info - static void GetCurrentThreads(TThreadInfo& threadsOut); - - // fills threadsOut vector with thread handles of given thread ids; if threadIds vector is emtpy it fills all running threads - // if ignoreCurrThread is true it will not return the current thread - static void OpenThreadHandles(TThreads& threadsOut, const TThreadIds& threadIds = TThreadIds(), bool ignoreCurrThread = true); - - // closes thread handles; should be called whenever GetCurrentThreads was called! - static void CloseThreadHandles(const TThreads& threads); -}; - -#endif // CRYINCLUDE_CRYSYSTEM_THREADINFO_H diff --git a/Code/CryEngine/CrySystem/ThreadTask.cpp b/Code/CryEngine/CrySystem/ThreadTask.cpp deleted file mode 100644 index d1ae7304e6..0000000000 --- a/Code/CryEngine/CrySystem/ThreadTask.cpp +++ /dev/null @@ -1,1046 +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 "CrySystem_precompiled.h" -#include "ThreadTask.h" -#include "CPUDetect.h" -#include "IConsole.h" -#include "System.h" - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define THREADTASK_CPP_SECTION_1 1 -#define THREADTASK_CPP_SECTION_2 2 -#endif - -#ifdef WIN32 -#define WIN32_LEAN_AND_MEAN -#include -#endif //WIN32 - -#include "BitFiddling.h" - -#if defined(ANDROID) -#include -#include -#endif -#if defined(LINUX) - -#endif -#if defined(APPLE) -// include for thread_policy_set -#include -#include -#endif - -#include - -////////////////////////////////////////////////////////////////////////// -CThreadTask_Thread::CThreadTask_Thread(CThreadTaskManager* pTaskMgr, const char* sName, - int nIndex, int nProcessor, int nThreadPriority, ThreadPoolHandle poolHandle /* = -1*/) - : tasks(64) -{ - m_nThreadPriority = nThreadPriority; - m_pTaskManager = pTaskMgr; - m_sThreadName = sName; - bStopThread = false; - bRunning = false; - m_hThreadHandle = 0; - m_nThreadIndex = nIndex; - m_nProcessor = nProcessor; - m_poolHandle = poolHandle; -} - -CThreadTask_Thread::~CThreadTask_Thread() -{ - while (!tasks.empty()) - { - tasks.pop()->m_pThread = 0; - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::SingleUpdate() -{ - while (true) - { - m_pProcessingTask = NULL; - - { - if (tasks.empty()) - { - break; - } - // remove from queue - m_pProcessingTask = tasks.pop(); - } - - if (m_pProcessingTask) - { - m_pProcessingTask->m_pTask->OnUpdate(); - } - - if (m_pProcessingTask) // push it back - { - tasks.push(m_pProcessingTask); - } - - if (bStopThread) - { - break; - } - } - - if (m_poolHandle != -1) // if this thread is in the pool, we need to reassign some tasks for it - { - m_pTaskManager->BalanceThreadInPool(this); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::Run() -{ - Init(); - - bRunning = true; - while (!bStopThread) - { - while (tasks.empty() && !bStopThread) - { - m_waitForTasks.Wait(); - } - - if (!bStopThread) - { - SingleUpdate(); - } - } - bRunning = false; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::Cancel() -{ - bStopThread = true; - m_waitForTasks.Set(); - Stop(); - - // for blocking thread notify the blocking task - if (m_nThreadIndex == -1) - { - if (m_pProcessingTask && m_pProcessingTask->m_params.nFlags & THREAD_TASK_BLOCKING) // check if we have a blocking task - { - if (m_pProcessingTask->m_pTask) // cancel it - { - m_pProcessingTask->m_pTask->Stop(); - } - } - } - - WaitForThread(); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::Terminate() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::AddTask(SThreadTaskInfo* pTaskInfo) -{ - pTaskInfo->m_pThread = this; - tasks.push(pTaskInfo); - m_waitForTasks.Set(); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::RemoveTask(SThreadTaskInfo* pTaskInfo) -{ - if (!pTaskInfo) - { - return; - } - - if (m_pProcessingTask == pTaskInfo) - { - pTaskInfo->m_pThread = NULL; - m_pProcessingTask = NULL; - return; - } - - // search for task(mirrored search because of locklessness) - bool bFound = false; - Tasks newTasks; - while (!tasks.empty()) - { - SThreadTaskInfo* pTask = tasks.pop(); - if (pTask == pTaskInfo) - { - pTaskInfo->m_pThread = NULL; - bFound = true; - break; - } - if (pTask) - { - newTasks.push(pTask); - } - } - (void)bFound; - // Don't assert if newTasks is empty. There is a thread race condition between - // the thread shutting down and this code being executed (both update/use - // m_pProcessTask with no locks). newTasks will be empty - // and bFound == false when the race condition is won by the task thread and - // not by the thread that is executing this code - CRY_ASSERT(bFound || newTasks.empty()); - - // fill back - while (!newTasks.empty()) - { - tasks.push(newTasks.pop()); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::RemoveAllTasks() -{ - while (!tasks.empty()) - { - tasks.pop()->m_pThread = NULL; - } -} - -void CThreadTask_Thread::Init() -{ -#if AZ_TRAIT_OS_USE_WINDOWS_THREADS - m_hThreadHandle = GetCurrentThread(); -#endif - - // Name this thread. - CryThreadSetName(GetCurrentThreadId(), m_sThreadName); - - // Set affinity - if (m_nProcessor > 0) - { - ChangeProcessor(m_nProcessor); - } -#if defined(WIN32) - ((CSystem*)gEnv->pSystem)->EnableFloatExceptions(g_cvars.sys_float_exceptions); -#endif -} - -void CThreadTask_Thread::ChangeProcessor(int nProcessor) -{ - // note this function is not thread-safe - m_nProcessor = nProcessor; -#if defined(WIN32) - DWORD_PTR mask1, mask2; - GetProcessAffinityMask(GetCurrentProcess(), &mask1, &mask2); - if (BIT64(m_nProcessor) & mask1) // Check if we have this affinity - { - SetThreadAffinityMask(m_hThreadHandle, BIT64(m_nProcessor)); - } - else // Reserve CPU 1 for main thread. - { - SetThreadAffinityMask(m_hThreadHandle, (mask1 & (~1))); - } - assert(THREAD_PRIORITY_IDLE <= m_nThreadPriority && m_nThreadPriority <= THREAD_PRIORITY_TIME_CRITICAL); - SetThreadPriority(m_hThreadHandle, m_nThreadPriority); -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION THREADTASK_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(ThreadTask_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(ANDROID) - int err, syscallres; - pid_t pid = gettid(); - syscallres = syscall(__NR_sched_setaffinity, pid, sizeof(nProcessor), &nProcessor); - if (syscallres) - { - err = errno; - CryLog("Error in the syscall setaffinity: mask=%d=0x%x sysconf#=%ld err=%d=0x%x", nProcessor, nProcessor, sysconf(_SC_NPROCESSORS_ONLN), err, err); - } -#elif defined(LINUX) - // Check if the processor is valid - assert(nProcessor < sysconf(_SC_NPROCESSORS_ONLN)); - cpu_set_t cpuset; - CPU_ZERO(&cpuset); - CPU_SET(nProcessor, &cpuset); - pthread_t current_thread = pthread_self(); - int ret = pthread_setaffinity_np(current_thread, sizeof(cpu_set_t), &cpuset); - (void) ret; - // check if the operation completed succesfully - assert(ret == 0 && "ChangeProcessor operation failed"); -#elif defined(APPLE) - assert(nProcessor != 0 && "CThreadTask_Thread::ChangeProcessor - If " - "nProcessor is equal to 0, the default afinity will be applied " - "to the thread. Can be fixed by incrementing nProcess by 1."); - thread_affinity_policy_data_t thread_affinity; - thread_affinity.affinity_tag = nProcessor; - thread_policy_set(pthread_mach_thread_np(pthread_self()), THREAD_AFFINITY_POLICY, (thread_policy_t)&thread_affinity, THREAD_AFFINITY_POLICY_COUNT); - //CryWarning(VALIDATOR_MODULE_SYSTEM,VALIDATOR_WARNING, "CThreadTask_Thread::ChangeProcessor: Feature is not supported on Mac OS X."); -#else - assert(0); -#endif -} - -////////////////////////////////////////////////////////////////////////// -CThreadTaskManager::CThreadTaskManager() -{ - m_nMaxThreads = 1; - - SetThreadName(GetCurrentThreadId(), "Main"); - - m_systemThreads.push_back(GetCurrentThreadId()); -} - -////////////////////////////////////////////////////////////////////////// -CThreadTaskManager::~CThreadTaskManager() -{ - CloseThreads(); - - AUTO_MODIFYLOCK(m_threadsPoolsLock); - while (!m_threadsPools.empty()) - { -#if !defined(NDEBUG) - bool res = -#endif - DestroyThreadsPool(m_threadsPools.begin()->m_hHandle); - assert(res); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::StopAllThreads() -{ - if (m_threads.empty()) - { - return; - } - - size_t i; - // Start from 2nd thread, 1st is main thread. - for (i = 1; i < m_threads.size(); i++) - { - CThreadTask_Thread* pThread = m_threads[i]; - pThread->Cancel(); - } - bool bAllStoped = true; - do - { - bAllStoped = true; - CrySleep(10); - for (i = 1; i < m_threads.size(); i++) - { - CThreadTask_Thread* pThread = m_threads[i]; - // Needs ReadWriteBarrier here. - if (pThread->bRunning) - { - bAllStoped = false; - } - } - } - while (!bAllStoped); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::CloseThreads() -{ - if (m_threads.size() > 0) - { - StopAllThreads(); - } - for (size_t i = MAIN_THREAD_INDEX, numThreads = m_threads.size(); i < numThreads; i++) - { - delete m_threads[i]; - } - m_threads.clear(); - //make sure blocking threads are cancelled - for (bool repeat = true; repeat; ) - { - CThreadTask_Thread* thr = NULL; - { - CryAutoCriticalSection lock(m_threadRemove); - - if (!m_blockingThreads.empty()) - { - thr = *m_blockingThreads.rbegin(); - m_blockingThreads.pop_back(); - } - } - - if (thr) - { - thr->Cancel(); - delete thr; - } - else - { - repeat = false; - } - } - - m_blockingThreads.clear(); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::InitThreads() -{ - m_nMaxThreads = gEnv->IsDedicated() ? 1 : 4; - CloseThreads(); - - // Create a dummy thread that is used for main thread. - m_threads.resize(1); - m_threads[0] = new CThreadTask_Thread(this, "Main Thread", 0, AFFINITY_MASK_MAINTHREAD, THREAD_PRIORITY_NORMAL); - - CCpuFeatures* pCPU = ((CSystem*)gEnv->pSystem)->GetCPUFeatures(); - - int nThreads = min((int)m_nMaxThreads, (int)pCPU->GetCPUCount()); - - if (nThreads < 1) - { - nThreads = 1; - } - int nAddThreads = nThreads - 1; - - char str[32]; - m_threads.resize(1 + nAddThreads); - for (int i = 0; i < nAddThreads; i++) - { - int nIndex = i + 1; - int nCPU = i + 1; - sprintf_s(str, "TaskThread%d", i); - if (i < m_nMaxThreads) - { - nCPU = ((CSystem*)gEnv->pSystem)->m_sys_TaskThread_CPU[i]->GetIVal(); - } - - // Clamp to random thread between 1 and max, avoid cpu 0 with main thread - if (nCPU >= nThreads) - { - nCPU = (rand() % (nThreads - 1)) + 1; - } - m_threads[nIndex] = new CThreadTask_Thread(this, str, nIndex, nCPU, THREAD_PRIORITY_NORMAL); - m_threads[nIndex]->Start(0, str, THREAD_PRIORITY_NORMAL, SIMPLE_THREAD_STACK_SIZE_KB * 1024); - } - RescheduleTasks(); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::SetMaxThreadCount(int nMaxThreads) -{ - if (nMaxThreads == m_nMaxThreads) - { - return; - } - - m_nMaxThreads = nMaxThreads; - - bool bReallocateThreads = false; - if (m_nMaxThreads < (int)m_threads.size()) - { - bReallocateThreads = true; - } - if (m_nMaxThreads > (int)m_threads.size()) - { - CCpuFeatures* pCPU = ((CSystem*)gEnv->pSystem)->GetCPUFeatures(); - if (m_threads.size() < pCPU->GetCPUCount()) - { - bReallocateThreads = true; - } - } - if (bReallocateThreads) - { - CloseThreads(); - InitThreads(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::RegisterTask(IThreadTask* pTask, const SThreadTaskParams& options) -{ - if (!pTask) - { - assert(0); - return; - } - SThreadTaskInfo* pTaskInfo = pTask->GetTaskInfo(); - pTaskInfo->m_pTask = pTask; - pTaskInfo->m_params = options; - - if ((options.nFlags & THREAD_TASK_BLOCKING) == 0) - { - ScheduleTask(pTaskInfo); - } - else - { - CryAutoCriticalSection lock(m_threadRemove); - // Blocking task will need it`s own thread. - const int threadPriority = THREAD_PRIORITY_NORMAL; - CThreadTask_Thread* pThread = - new CThreadTask_Thread(this, options.name, -1, options.nPreferedThread, threadPriority); - pThread->Start(0, (char*)options.name, threadPriority, options.nStackSizeKB * 1024); - pThread->AddTask(pTaskInfo); - - m_blockingThreads.push_back(pThread); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::UnregisterTask(IThreadTask* pTask) -{ - assert(pTask); - if (!pTask) - { - return; - } - SThreadTaskInfo* pTaskInfo = pTask->GetTaskInfo(); - assert(pTaskInfo); - - IThreadTask_Thread* pThread = pTaskInfo->m_pThread; - uint32 flags = pTaskInfo->m_params.nFlags; - - // Remove from thread. - if (pThread) - { - pThread->RemoveTask(pTaskInfo); - } - - pTask->Stop(); - - if (flags & THREAD_TASK_BLOCKING) - { - CThreadTask_Thread* thr = NULL; - { - CryAutoCriticalSection lock(m_threadRemove); - Threads::iterator end = m_blockingThreads.end(); - Threads::iterator toErase = std::find(m_blockingThreads.begin(), end, pThread); - - if (toErase != end) // impossible to find anything. no push_back done on m_blockingThreads - { - thr = *toErase; - m_blockingThreads.erase(toErase); - } - } - - if (thr) - { - thr->Cancel(); - delete thr; - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::ScheduleTask(SThreadTaskInfo* pTaskInfo) -{ - size_t i; - - if (pTaskInfo->m_pThread) - { - assert(0); - pTaskInfo->m_pThread->RemoveTask(pTaskInfo); - } - - CThreadTask_Thread* pGoodThread = NULL; - - if (pTaskInfo->m_params.nFlags & THREAD_TASK_ASSIGN_TO_POOL) - { - AUTO_READLOCK(m_threadsPoolsLock); - - // find the pool - CThreadsPool* pool = NULL; - size_t nSize = m_threadsPools.size(); - for (i = 0; i < nSize; ++i) - { - if (m_threadsPools[i].m_hHandle == pTaskInfo->m_params.nThreadsGroupId) - { - pool = &m_threadsPools[i]; - } - } - - if (pool) - { - // Find available thread for the task. - for (i = 0; i < (int)pool->m_Threads.size(); ++i) - { - CThreadTask_Thread* pThread = pool->m_Threads[i]; - const bool threadIsFree = pThread->tasks.empty() && pThread->m_pProcessingTask == NULL; - if (threadIsFree || pGoodThread == NULL) - { - pGoodThread = pThread; - if (threadIsFree) - { - break; - } - } - } - } - else - { - gEnv->pLog->LogError("[Error]Task manager: threads pool not found!"); - assert(0); - } - } - else if (pTaskInfo->m_params.nPreferedThread >= 0 && pTaskInfo->m_params.nPreferedThread < (int)m_threads.size()) - { - assert((int)m_threads.size() > pTaskInfo->m_params.nPreferedThread); - // Assign task to desired thread. - pGoodThread = m_threads[pTaskInfo->m_params.nPreferedThread]; - } - else - { - // Find available thread for the task. - for (i = MAIN_THREAD_INDEX + 1; i < (int)m_threads.size(); i++) - { - CThreadTask_Thread* pThread = m_threads[i]; - PREFAST_ASSUME(pThread); - if (pThread->tasks.empty() || pGoodThread == NULL) - { - pGoodThread = pThread; - if (pThread->tasks.empty()) - { - break; - } - } - } - } - if (!pGoodThread && !m_threads.empty()) - { - // Assign to last thread. - pGoodThread = m_threads[m_threads.size() - 1]; - } - - if (pGoodThread) - { - pGoodThread->AddTask(pTaskInfo); - } - else - { - m_unassignedTasks.push(pTaskInfo); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::RescheduleTasks() -{ - // Un-schedule all tasks. - for (int i = 0; i < (int)m_threads.size(); i++) - { - while (!m_threads[i]->tasks.empty()) - { - SThreadTaskInfo* pTask = m_threads[i]->tasks.pop(); - if (!pTask) - { - break; - } - if (pTask->m_params.nFlags & THREAD_TASK_BLOCKING) // Do not schedule blocking tasks. - { - m_threads[i]->tasks.push(pTask); - break; - } - pTask->m_pThread = NULL; - m_unassignedTasks.push(pTask); - } - } - - while (!m_unassignedTasks.empty()) - { - ScheduleTask(m_unassignedTasks.pop()); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::OnUpdate() -{ - AZ_TRACE_METHOD(); - FUNCTION_PROFILER_LEGACYONLY(GetISystem(), PROFILE_SYSTEM); - - // Emulate single update of the main thread. - if (m_threads[0]) - { - m_threads[0]->SingleUpdate(); - } - - // assign unassigned tasks - while (!m_unassignedTasks.empty()) - { - ScheduleTask(m_unassignedTasks.pop()); - } - - // balance all pools - AUTO_READLOCK(m_threadsPoolsLock); - size_t nSize = m_threadsPools.size(); - for (size_t itPool = 0; itPool < nSize; ++itPool) - { - BalanceThreadsPool(m_threadsPools[itPool].m_hHandle); - } -} - -struct THREADNAME_INFO_TASK -{ - DWORD dwType; - LPCSTR szName; - DWORD dwThreadID; - DWORD dwFlags; -}; - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::SetThreadName(threadID dwThreadId, const char* sThreadName) -{ - if (dwThreadId == (THREADID_NULL)) - { - dwThreadId = GetCurrentThreadId(); - } - -#if defined(AZ_PROFILE_TELEMETRY) && AZ_TRAIT_OS_USE_WINDOWS_THREADS - AZStd::thread_desc desc; - desc.m_name = sThreadName; - // we broadcast to the "client" bus and then to the "driller" (profiling) bus - AZStd::ThreadEventBus::Broadcast(&AZStd::ThreadEventBus::Events::OnThreadEnter, AZStd::thread::id(dwThreadId), &desc); - AZStd::ThreadDrillerEventBus::Broadcast(&AZStd::ThreadDrillerEventBus::Events::OnThreadEnter, AZStd::thread::id(dwThreadId), &desc); -#endif - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_THREADTASK_EXCEPTIONS - ////////////////////////////////////////////////////////////////////////// - // Raise exception to set thread name for debugger. - ////////////////////////////////////////////////////////////////////////// - THREADNAME_INFO_TASK threadName; - threadName.dwType = 0x1000; - threadName.szName = sThreadName; - threadName.dwThreadID = dwThreadId; - threadName.dwFlags = 0; - - __try - { - RaiseException(0x406D1388, 0, sizeof(threadName) / sizeof(DWORD), (ULONG_PTR*)&threadName); - } - __except (EXCEPTION_CONTINUE_EXECUTION) - { - } -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION THREADTASK_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(ThreadTask_cpp) -#endif - - { - m_threadNameLock.Lock(); - m_threadNames[dwThreadId] = sThreadName; - m_threadNameLock.Unlock(); - } -} - -////////////////////////////////////////////////////////////////////////// -const char* CThreadTaskManager::GetThreadName(threadID dwThreadId) -{ - CryAutoCriticalSection lock(m_threadNameLock); - ThreadNames::const_iterator it = m_threadNames.find(dwThreadId); - if (it != m_threadNames.end()) - { - return it->second.c_str(); - } - - return ""; -} - -////////////////////////////////////////////////////////////////////////// -threadID CThreadTaskManager::GetThreadByName(const char* sThreadName) -{ - CryAutoCriticalSection lock(m_threadNameLock); - for (ThreadNames::const_iterator it = m_threadNames.begin(); it != m_threadNames.end(); ++it) - { - if (it->second.compareNoCase(sThreadName) == 0) - { - return it->first; - } - } - return 0; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::AddSystemThread(threadID nThreadId) -{ - CryAutoCriticalSection lock(m_systemThreadsLock); - m_systemThreads.push_back(nThreadId); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::RemoveSystemThread(threadID nThreadId) -{ - CryAutoCriticalSection lock(m_systemThreadsLock); - stl::find_and_erase(m_systemThreads, nThreadId); -} - -////////////////////////////////////////////////////////////////////////// -ThreadPoolHandle CThreadTaskManager::CreateThreadsPool(const ThreadPoolDesc& desc) -{ - AUTO_MODIFYLOCK(m_threadsPoolsLock); - - ThreadPoolHandle newId = m_threadsPools.empty() ? 0 : m_threadsPools.rbegin()->m_hHandle + 1; - - if (desc.AffinityMask == INVALID_AFFINITY) - { - assert(0); - return -1; - } - - // create the pool - m_threadsPools.push_back(CThreadsPool()); - CThreadsPool& rPool = m_threadsPools.back(); - - // assign the new handle - rPool.m_hHandle = newId; - - // fill up the desc - rPool.m_pDescription = desc; - - Threads& threads = rPool.m_Threads; - - size_t threadNameSize = desc.sPoolName.size() + 30; - std::vector threadName(threadNameSize); - uint32 iThread = 0; - for (uint32 nIndex = 0; nIndex < sizeof(desc.AffinityMask) * 8; ++nIndex) - { - // check if we have affinity mask bit set for this thread - if (!(desc.AffinityMask & (1 << nIndex))) - { - continue; - } - - const int32 nThreadPriority = (desc.nThreadPriority == -1) ? THREAD_PRIORITY_NORMAL : desc.nThreadPriority; - const int32 nThreadStackSizeKB = (desc.nThreadStackSizeKB == -1) ? SIMPLE_THREAD_STACK_SIZE_KB : desc.nThreadStackSizeKB; - - // create a thread - sprintf_s(&threadName[0], threadNameSize, "%s%d", desc.sPoolName.c_str(), iThread); - CThreadTask_Thread* thread = new CThreadTask_Thread(this, &threadName[0], iThread, nIndex, nThreadPriority, newId); - - // start thread - thread->Start(0, (char*)&threadName[0], nThreadPriority, nThreadStackSizeKB * 1024); - - // add to pool - threads.push_back(thread); - - iThread++; - } - - return newId; -} - -const bool CThreadTaskManager::DestroyThreadsPool(const ThreadPoolHandle& handle) -{ - AUTO_MODIFYLOCK(m_threadsPoolsLock); - - CThreadsPool* pPool = NULL; - size_t nSize = m_threadsPools.size(); - size_t iPool = 0; - for (; iPool < nSize; ++iPool) - { - if (m_threadsPools[iPool].m_hHandle == handle) - { - pPool = &m_threadsPools[iPool]; - break; - } - } - - if (pPool) - { - Threads& threads = pPool->m_Threads; - size_t nThreads = threads.size(); - for (size_t iThread = 0; iThread < nThreads; ++iThread) - { - CThreadTask_Thread* pThread = threads[iThread]; - PREFAST_ASSUME(pThread); - pThread->Cancel(); - assert(!(pThread->bRunning)); - delete pThread; - } - - m_threadsPools.erase(m_threadsPools.begin() + iPool); - return true; - } - return false; -} - -const bool CThreadTaskManager::GetThreadsPoolDesc(const ThreadPoolHandle handle, ThreadPoolDesc* pDesc) const -{ - AUTO_READLOCK(m_threadsPoolsLock); - - const CThreadsPool* pPool = NULL; - size_t iPool = 0, nSize = m_threadsPools.size(); - for (; iPool < nSize; ++iPool) - { - if (m_threadsPools[iPool].m_hHandle == handle) - { - pPool = &m_threadsPools[iPool]; - break; - } - } - - if (pPool) - { - if (pDesc) - { - *pDesc = pPool->m_pDescription; - return true; - } - } - - return false; -} - -const bool CThreadTaskManager::SetThreadsPoolAffinity(const ThreadPoolHandle handle, const ThreadPoolAffinityMask AffinityMask) -{ - CThreadsPool* pPool = NULL; - - AUTO_MODIFYLOCK(m_threadsPoolsLock); - - size_t iPool = 0, nSize = m_threadsPools.size(); - for (; iPool < nSize; ++iPool) - { - if (m_threadsPools[iPool].m_hHandle == handle) - { - pPool = &m_threadsPools[iPool]; - break; - } - } - - if (pPool) - { - return pPool->SetAffinity(AffinityMask); - } - - return false; -} - -void CThreadTaskManager::BalanceThreadsPool(const ThreadPoolHandle& handle) -{ - CThreadsPool* pPool = NULL; - - AUTO_READLOCK(m_threadsPoolsLock); - - size_t iPool = 0, nSize = m_threadsPools.size(); - for (; iPool < nSize; ++iPool) - { - if (m_threadsPools[iPool].m_hHandle == handle) - { - pPool = &m_threadsPools[iPool]; - break; - } - } - - if (pPool) - { - // balancing tasks in the pool - for (size_t itThread = 0, nThreads = pPool->m_Threads.size(); itThread < nThreads; ++itThread) - { - CThreadTask_Thread* pThread = pPool->m_Threads[itThread]; - if (pThread->tasks.empty()) // found free thread(without tasks) - { - BalanceThreadInPool(pThread, &pPool->m_Threads); - } - } - } - else - { - assert(0); - } -} - -void CThreadTaskManager::BalanceThreadInPool(CThreadTask_Thread* pFreeThread, Threads* pThreads /* = NULL */) -{ - assert(pFreeThread->m_poolHandle != -1); - - AUTO_READLOCK(m_threadsPoolsLock); - - if (pThreads == NULL) - { - CThreadsPool* pPool = NULL; - size_t iPool = 0, nSize = m_threadsPools.size(); - for (; iPool < nSize; ++iPool) - { - if (m_threadsPools[iPool].m_hHandle == pFreeThread->m_poolHandle) - { - pPool = &m_threadsPools[iPool]; - break; - } - } - - if (pPool) - { - pThreads = &pPool->m_Threads; - } - } - assert(pThreads); - PREFAST_ASSUME(pThreads); - // search for thread with tasks - for (size_t itAnotherThread = 0, nThreads = pThreads->size(); itAnotherThread < nThreads; ++itAnotherThread) - { - CThreadTask_Thread* pAnotherThread = (*pThreads)[itAnotherThread]; - if (pFreeThread == pAnotherThread) - { - continue; - } - if (pAnotherThread->tasks.empty()) - { - continue; - } - - // we found a thread with more than one task - SThreadTaskInfo* pTask = pAnotherThread->tasks.pop(); - if (pTask) - { - assert(pTask->m_pThread == pAnotherThread); - // reassign the last task to another thread - pFreeThread->AddTask(pTask); - break; // process next free thread - } - } -} - -void CThreadTaskManager::MarkThisThreadForDebugging(const char* name, bool bDump) -{ - bDump ? ::MarkThisThreadForDebugging(name) : ::UnmarkThisThreadFromDebugging(); -} - - -const bool CThreadTaskManager::CThreadsPool::SetAffinity(const ThreadPoolAffinityMask AffinityMask) -{ - // check if all threads in the pool are covered by the bits of this mask - if (CountBits(AffinityMask) != m_Threads.size()) - { - // wrong arguments - return false; - } - - // update affinity mask - m_pDescription.AffinityMask = AffinityMask; - - size_t itThread = 0; - for (uint32 nProcessorIndex = 0; nProcessorIndex < sizeof(AffinityMask) * 8; ++nProcessorIndex) - { - assert(itThread < m_Threads.size()); - // check if we have affinity mask bit set for this thread - if (!(AffinityMask & (1 << nProcessorIndex))) - { - continue; - } - - // changin thread's affinity in the pool - m_Threads[itThread]->ChangeProcessor(nProcessorIndex); - ++itThread; - } - return true; -} diff --git a/Code/CryEngine/CrySystem/ThreadTask.h b/Code/CryEngine/CrySystem/ThreadTask.h deleted file mode 100644 index e528fedf5f..0000000000 --- a/Code/CryEngine/CrySystem/ThreadTask.h +++ /dev/null @@ -1,181 +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_CRYSYSTEM_THREADTASK_H -#define CRYINCLUDE_CRYSYSTEM_THREADTASK_H -#pragma once - - -#include -#include -#include - -#define MAIN_THREAD_INDEX 0 - -class CThreadTask_Thread; - - -void MarkThisThreadForDebugging(const char* name); -void UnmarkThisThreadFromDebugging(); -void UpdateFPExceptionsMaskForThreads(); - - -class CThreadTaskManager; -/// -struct IThreadTaskRunnable -{ - virtual ~IThreadTaskRunnable(){} - virtual void Run() = 0; - virtual void Cancel() = 0; -}; -////////////////////////////////////////////////////////////////////////// -class CThreadTask_Thread - : public CryThread - , public IThreadTask_Thread -{ -protected: - void Init(); -public: - CThreadTask_Thread(CThreadTaskManager* pTaskMgr, const char* sName, int nThreadIndex, int nProcessor, int nThreadPriority, ThreadPoolHandle poolHandle = -1); - ~CThreadTask_Thread(); - - // see IThreadTaskRunnable, CryThread<> - void Run() override; - void Cancel() override; - - // see CryThread<> - void Terminate() override; - - // IThreadTask_Thread - void AddTask(SThreadTaskInfo* pTaskInfo) override; - void RemoveTask(SThreadTaskInfo* pTaskInfo) override; - void RemoveAllTasks() override; - void SingleUpdate() override; - - void ChangeProcessor(int nProcessor); -public: - CThreadTaskManager* m_pTaskManager; - string m_sThreadName; - int m_nThreadIndex; // -1 means the thread is blocking - int m_nProcessor; - int m_nThreadPriority; - - THREAD_HANDLE m_hThreadHandle; - - // Tasks running on this thread. - typedef CryMT::CLocklessPointerQueue > Tasks; - Tasks tasks; - - // The task is being processing now - SThreadTaskInfo* m_pProcessingTask; - - CryEvent m_waitForTasks; - - // Set to true when thread must stop. - volatile bool bStopThread; - volatile bool bRunning; - - // handle of threads pool which this thread belongs to(if any) - ThreadPoolHandle m_poolHandle; -}; - -////////////////////////////////////////////////////////////////////////// -class CThreadTaskManager - : public IThreadTaskManager -{ -private: - typedef std::vector > Threads; - // note: this struct is auxilary and NOT thread-safe - // it is only for internal use inside the task manager - struct CThreadsPool - { - ThreadPoolHandle m_hHandle; - Threads m_Threads; - ThreadPoolDesc m_pDescription; - const bool SetAffinity(const ThreadPoolAffinityMask AffinityMask); - const bool operator < (const CThreadsPool& p) const { return m_hHandle < p.m_hHandle; } - const bool operator == (const CThreadsPool& p) const { return m_hHandle == p.m_hHandle; } - }; - - typedef std::vector ThreadsPools; - -public: - CThreadTaskManager(); - ~CThreadTaskManager(); - - void InitThreads(); - void CloseThreads(); - void StopAllThreads(); - - ////////////////////////////////////////////////////////////////////////// - // IThreadTaskManager - ////////////////////////////////////////////////////////////////////////// - virtual void RegisterTask(IThreadTask* pTask, const SThreadTaskParams& options); - virtual void UnregisterTask(IThreadTask* pTask); - virtual void SetMaxThreadCount(int nMaxThreads); - virtual void SetThreadName(threadID dwThreadId, const char* sThreadName); - virtual const char* GetThreadName(threadID dwThreadId); - virtual threadID GetThreadByName(const char* sThreadName); - - // Thread pool framework - virtual ThreadPoolHandle CreateThreadsPool(const ThreadPoolDesc& desc); - virtual const bool DestroyThreadsPool(const ThreadPoolHandle& handle); - virtual const bool GetThreadsPoolDesc(const ThreadPoolHandle handle, ThreadPoolDesc* pDesc) const; - virtual const bool SetThreadsPoolAffinity(const ThreadPoolHandle handle, const ThreadPoolAffinityMask AffinityMask); - - virtual void MarkThisThreadForDebugging(const char* name, bool bDump); - ////////////////////////////////////////////////////////////////////////// - - // This is on update function of the main thread. - void OnUpdate(); - - void AddSystemThread(threadID nThreadId); - void RemoveSystemThread(threadID nThreadId); - - // Balancing tasks in the pool between threads - void BalanceThreadsPool(const ThreadPoolHandle& handle); - void BalanceThreadInPool(CThreadTask_Thread* pFreeThread, Threads* pThreads = NULL); - -private: - void ScheduleTask(SThreadTaskInfo* pTaskInfo); - void RescheduleTasks(); -private: - - // User created threads pools - mutable CryReadModifyLock m_threadsPoolsLock; - ThreadsPools m_threadsPools; - - // Physical threads available to system. - Threads m_threads; - - // Threads with single blocking task attached. - Threads m_blockingThreads; - - typedef CryMT::CLocklessPointerQueue Tasks; - - Tasks m_unassignedTasks; - - mutable CryCriticalSection m_threadNameLock; - mutable CryCriticalSection m_threadRemove; - typedef std::map ThreadNames; - ThreadNames m_threadNames; - - mutable CryCriticalSection m_systemThreadsLock; - std::vector m_systemThreads; - - // Max threads that can be executed at same time. - int m_nMaxThreads; -}; - - -#endif // CRYINCLUDE_CRYSYSTEM_THREADTASK_H diff --git a/Code/CryEngine/CrySystem/UnitTests/CryMathTests.cpp b/Code/CryEngine/CrySystem/UnitTests/CryMathTests.cpp deleted file mode 100644 index 6fc9ae7830..0000000000 --- a/Code/CryEngine/CrySystem/UnitTests/CryMathTests.cpp +++ /dev/null @@ -1,46 +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 "CrySystem_precompiled.h" -#include -#include - -namespace UnitTest -{ - class CryMathTestFixture - : public ::testing::Test - {}; - -#if AZ_TRAIT_DISABLE_FAILED_MATH_TESTS - TEST_F(CryMathTestFixture, DISABLED_InverserSqrt_HasAtLeast22BitsOfAccuracy) -#else - TEST_F(CryMathTestFixture, InverserSqrt_HasAtLeast22BitsOfAccuracy) -#endif - { - float testFloat(0.336950600); - const float result = isqrt_safe_tpl(testFloat * testFloat); - const float epsilon = 0.00001f; - EXPECT_NEAR(2.96779, result, epsilon); - } - -#if AZ_TRAIT_DISABLE_FAILED_MATH_TESTS - TEST_F(CryMathTestFixture, DISABLED_SimdSqrt_HasAtLeast23BitsOfAccuracy) -#else - TEST_F(CryMathTestFixture, SimdSqrt_HasAtLeast23BitsOfAccuracy) -#endif - { - float testFloat(3434.34839439); - const float result = sqrt_tpl(testFloat); - const float epsilon = 0.00001f; - EXPECT_NEAR(58.60331, result, epsilon); - } -} diff --git a/Code/CryEngine/CrySystem/UnitTests/CryPakUnitTests.cpp b/Code/CryEngine/CrySystem/UnitTests/CryPakUnitTests.cpp deleted file mode 100644 index 1935196570..0000000000 --- a/Code/CryEngine/CrySystem/UnitTests/CryPakUnitTests.cpp +++ /dev/null @@ -1,141 +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 "CrySystem_precompiled.h" - -#include -#include - -#include -#include // for max path decl -#include -#include -#include // for function<> in the find files callback. -#include -#include -#include -#include -#include - -namespace CryPakUnitTests -{ - -#if defined(AZ_PLATFORM_WINDOWS) - - // Note: none of the below is really a unit test, its all basic feature tests - // for critical functionality - - class Integ_CryPakUnitTests - : public ::testing::Test - { - protected: - bool IsPackValid(const char* path) - { - AZ::IO::IArchive* pak = gEnv->pCryPak; - if (!pak) - { - return false; - } - - if (!pak->OpenPack(path, AZ::IO::IArchive::FLAGS_PATH_REAL)) - { - return false; - } - - pak->ClosePack(path); - return true; - } - }; - - TEST_F(Integ_CryPakUnitTests, TestCryPakModTime) - { - AZ::IO::FileIOBase* fileIo = AZ::IO::FileIOBase::GetInstance(); - ASSERT_NE(nullptr, fileIo); - - AZ::IO::IArchive* pak = gEnv->pCryPak; - // repeat the following test multiple times, since timing (seconds) can affect it and it involves time! - for (int iteration = 0; iteration < 10; ++iteration) - { - AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds{ 100 }); - - // helper paths and strings - AZStd::string gameFolder = fileIo->GetAlias("@usercache@"); - - AZStd::string testFile = "unittest.bin"; - AZStd::string testFilePath = gameFolder + "\\" + testFile; - AZStd::string testPak = "unittest.pak"; - AZStd::string testPakPath = gameFolder + "\\" + testPak; - AZStd::string zipCmd = "-zip=" + testPakPath; - - // delete test files in case they already exist - fileIo->Remove(testFilePath.c_str()); - pak->ClosePack(testPakPath); - fileIo->Remove(testPakPath.c_str()); - - // create a test file - char data[] = "unittest"; - FILE* f = nullptr; - azfopen(&f, testFilePath.c_str(), "wb"); - EXPECT_TRUE(f != nullptr); // file successfully opened for writing - EXPECT_TRUE(fwrite(data, sizeof(char), sizeof(data), f) == sizeof(data)); // file written to successfully - EXPECT_TRUE(fclose(f) == 0); // file closed successfully - - AZ::IO::HandleType fDisk = pak->FOpen(testFilePath.c_str(), "rb"); - EXPECT_TRUE(fDisk > 0); // opened file on disk successfully - uint64_t modTimeDisk = pak->GetModificationTime(fDisk); // high res mod time extracted from file on disk - EXPECT_TRUE(pak->FClose(fDisk) == 0); // file closed successfully - - // create a low res copy of disk file's mod time - uint64_t absDiff, maxDiff = 20000000ul; - uint16_t dosDate, dosTime; - FILETIME ft; - LARGE_INTEGER lt; - - ft.dwHighDateTime = modTimeDisk >> 32; - ft.dwLowDateTime = modTimeDisk & 0xFFFFFFFF; - EXPECT_TRUE(FileTimeToDosDateTime(&ft, &dosDate, &dosTime) != FALSE); // converted to DOSTIME successfully - ft.dwHighDateTime = 0; - ft.dwLowDateTime = 0; - EXPECT_TRUE(DosDateTimeToFileTime(dosDate, dosTime, &ft) != FALSE); // converted to FILETIME successfully - lt.HighPart = ft.dwHighDateTime; - lt.LowPart = ft.dwLowDateTime; - uint64_t modTimeDiskLowRes = lt.QuadPart; - - absDiff = modTimeDiskLowRes >= modTimeDisk ? modTimeDiskLowRes - modTimeDisk : modTimeDisk - modTimeDiskLowRes; - EXPECT_LE(absDiff, maxDiff); // FILETIME (high res) and DOSTIME (low res) should be at most 2 seconds apart - - gEnv->pResourceCompilerHelper->CallResourceCompiler(testFilePath.c_str(), zipCmd.c_str()); - EXPECT_EQ(AZ::IO::ResultCode::Success, fileIo->Remove(testFilePath.c_str())); // test file on disk deleted successfully - - EXPECT_TRUE(pak->OpenPack(testPakPath)); // opened pak successfully - - AZ::IO::HandleType fPak = pak->FOpen(testFilePath.c_str(), "rb"); - EXPECT_GT(fPak, 0); // file (in pak) opened correctly - uint64_t modTimePak = pak->GetModificationTime(fPak); // low res mod time extracted from file in pak - EXPECT_EQ(0, pak->FClose(fPak)); // file closed successfully - - EXPECT_TRUE(pak->ClosePack(testPakPath)); // closed pak successfully - EXPECT_EQ(AZ::IO::ResultCode::Success, fileIo->Remove(testPakPath.c_str())); // test pak file deleted successfully - - absDiff = modTimePak >= modTimeDisk ? modTimePak - modTimeDisk : modTimeDisk - modTimePak; - // compare mod times. They are allowed to be up to 2 seconds apart but no more - EXPECT_LE(absDiff, maxDiff); // FILETIME (disk) and DOSTIME (pak) should be at most 2 seconds apart - // note: Do not directly compare the disk time and pack time, the resolution drops the last digit off in some cases in pak - // it only has a 2 second resolution. you may compare to make sure that the pak time is WITHIN 2 seconds (as above) but not equal. - - // we depend on the fact that crypak is rounding up, instead of down - EXPECT_GE(modTimePak, modTimeDisk); - } - } - - -#endif -} diff --git a/Code/CryEngine/CrySystem/UnixConsole.cpp b/Code/CryEngine/CrySystem/UnixConsole.cpp index d0a7bc15ff..5ec186b8b8 100644 --- a/Code/CryEngine/CrySystem/UnixConsole.cpp +++ b/Code/CryEngine/CrySystem/UnixConsole.cpp @@ -783,12 +783,6 @@ void CUNIXConsole::KeyEnter() if (pushCommand) { - CSystem* pSystem = static_cast(gEnv->pSystem); -#if defined(CVARS_WHITELIST) - ICVarsWhitelist* pCVarsWhitelist = pSystem->GetCVarsWhiteList(); - bool execute = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(m_InputLine, false) : true; - if (execute) -#endif // defined(CVARS_WHITELIST) { m_CommandQueue.push_back(m_InputLine); } diff --git a/Code/CryEngine/CrySystem/XConsole.cpp b/Code/CryEngine/CrySystem/XConsole.cpp index 3b30a7eeed..32fe67dcc0 100644 --- a/Code/CryEngine/CrySystem/XConsole.cpp +++ b/Code/CryEngine/CrySystem/XConsole.cpp @@ -140,147 +140,6 @@ void Command_SetWaitFrames(IConsoleCmdArgs* pCmd) } } -/* - - CNotificationNetworkConsole - -*/ - -#include -class CNotificationNetworkConsole - : public INotificationNetworkListener -{ -private: - static const uint32 LENGTH_MAX = 256; - static CNotificationNetworkConsole* s_pInstance; - -public: - static bool Initialize() - { - if (s_pInstance) - { - return true; - } - - INotificationNetwork* pNotificationNetwork = gEnv->pSystem->GetINotificationNetwork(); - if (!pNotificationNetwork) - { - return false; - } - - s_pInstance = new CNotificationNetworkConsole(); - pNotificationNetwork->ListenerBind("Command", s_pInstance); - return true; - } - - static void Shutdown() - { - if (!s_pInstance) - { - return; - } - - delete s_pInstance; - s_pInstance = NULL; - } - - static void Update() - { - if (s_pInstance) - { - s_pInstance->ProcessCommand(); - } - } - -private: - CNotificationNetworkConsole() - { - m_pConsole = NULL; - - m_commandBuffer[0][0] = '\0'; - m_commandBuffer[1][0] = '\0'; - m_commandBufferIndex = 0; - m_commandCriticalSection = ::CryCreateCriticalSection(); - } - - ~CNotificationNetworkConsole() - { - if (m_commandCriticalSection) - { - ::CryDeleteCriticalSection(m_commandCriticalSection); - } - } - -private: - void ProcessCommand() - { - if (!ValidateConsole()) - { - return; - } - - char* command = NULL; - ::CryEnterCriticalSection(m_commandCriticalSection); - if (*m_commandBuffer[m_commandBufferIndex]) - { - command = m_commandBuffer[m_commandBufferIndex]; - } - ++m_commandBufferIndex &= 1; - ::CryLeaveCriticalSection(m_commandCriticalSection); - - if (command) - { - m_pConsole->ExecuteString(command); - *command = '\0'; - } - } - - bool ValidateConsole() - { - if (m_pConsole) - { - return true; - } - - if (!gEnv->pConsole) - { - return false; - } - - m_pConsole = gEnv->pConsole; - return true; - } - - // INotificationNetworkListener -public: - void OnNotificationNetworkReceive(const void* pBuffer, size_t length) - { - if (!ValidateConsole()) - { - return; - } - - if (length > LENGTH_MAX) - { - length = LENGTH_MAX; - } - - ::CryEnterCriticalSection(m_commandCriticalSection); - ::memcpy(m_commandBuffer[m_commandBufferIndex], pBuffer, length); - m_commandBuffer[m_commandBufferIndex][LENGTH_MAX - 1] = '\0'; - ::CryLeaveCriticalSection(m_commandCriticalSection); - } - -private: - IConsole* m_pConsole; - - char m_commandBuffer[2][LENGTH_MAX]; - size_t m_commandBufferIndex; - void* m_commandCriticalSection; -}; - -CNotificationNetworkConsole* CNotificationNetworkConsole::s_pInstance = NULL; - void ConsoleShow(IConsoleCmdArgs*) { gEnv->pConsole->ShowConsole(true); @@ -359,8 +218,6 @@ CXConsole::CXConsole() m_waitSeconds = 0.0f; m_blockCounter = 0; - CNotificationNetworkConsole::Initialize(); - AzFramework::ConsoleRequestBus::Handler::BusConnect(); AzFramework::CommandRegistrationBus::Handler::BusConnect(); @@ -379,8 +236,6 @@ CXConsole::~CXConsole() gEnv->pSystem->GetIRemoteConsole()->UnregisterListener(this); } - CNotificationNetworkConsole::Shutdown(); - if (!m_mapVariables.empty()) { while (!m_mapVariables.empty()) @@ -1205,8 +1060,6 @@ void CXConsole::Update() } } } - - CNotificationNetworkConsole::Update(); } //enable this for now, we need it for profiling etc @@ -1749,11 +1602,6 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) int devOnlyMask = VF_DEV_ONLY; int dediOnlyMask = VF_DEDI_ONLY; int excludeMask = cheatMask | constMask | readOnlyMask | devOnlyMask | dediOnlyMask; -#if defined(CVARS_WHITELIST) - CSystem* pSystem = static_cast(gEnv->pSystem); - ICVarsWhitelist* pCVarsWhitelist = pSystem->GetCVarsWhiteList(); - bool excludeWhitelist = true; -#endif // defined(CVARS_WHITELIST) if (numArgs > 1) { @@ -1786,13 +1634,6 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) excludeMask &= ~dediOnlyMask; } -#if defined(CVARS_WHITELIST) - if (azstricmp(arg, "whitelist") == 0) - { - excludeWhitelist = false; - } -#endif // defined(CVARS_WHITELIST) - --numArgs; } } @@ -1810,11 +1651,6 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) int devOnlyFlags = (command.m_nFlags & devOnlyMask); int dediOnlyFlags = (command.m_nFlags & dediOnlyMask); bool shouldLog = ((cheatFlags | devOnlyFlags | dediOnlyFlags) == 0) || (((cheatFlags | devOnlyFlags | dediOnlyFlags) & ~excludeMask) != 0); -#if defined(CVARS_WHITELIST) - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(command.m_sName, true) : true; - shouldLog &= (!whitelisted || (whitelisted & !excludeWhitelist)); -#endif // defined(CVARS_WHITELIST) - if (shouldLog) { CryLogAlways("[CVARS]: [COMMAND] %s%s%s%s%s", @@ -1822,11 +1658,7 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) (cheatFlags != 0) ? " [VF_CHEAT]" : "", (devOnlyFlags != 0) ? " [VF_DEV_ONLY]" : "", (dediOnlyFlags != 0) ? " [VF_DEDI_ONLY]" : "", -#if defined(CVARS_WHITELIST) - (whitelisted == true) ? " [WHITELIST]" : "" -#else "" -#endif // defined(CVARS_WHITELIST) ); ++commandCount; } @@ -1843,11 +1675,6 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) int devOnlyFlags = (flags & devOnlyMask); int dediOnlyFlags = (flags & dediOnlyMask); bool shouldLog = ((cheatFlags | constFlags | readOnlyFlags | devOnlyFlags | dediOnlyFlags) == 0) || (((cheatFlags | constFlags | readOnlyFlags | devOnlyFlags | dediOnlyFlags) & ~excludeMask) != 0); -#if defined(CVARS_WHITELIST) - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(pVariable->GetName(), true) : true; - shouldLog &= (!whitelisted || (whitelisted & !excludeWhitelist)); -#endif // defined(CVARS_WHITELIST) - if (shouldLog) { CryLogAlways("[CVARS]: [VARIABLE] %s%s%s%s%s%s%s", @@ -1857,11 +1684,7 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) (readOnlyFlags != 0) ? " [VF_READONLY]" : "", (devOnlyFlags != 0) ? " [VF_DEV_ONLY]" : "", (dediOnlyFlags != 0) ? " [VF_DEDI_ONLY]" : "", -#if defined(CVARS_WHITELIST) - (whitelisted == true) ? " [WHITELIST]" : "" -#else "" -#endif // defined(CVARS_WHITELIST) ); ++cvarCount; } @@ -2520,11 +2343,6 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer) } } //try to search in command list - -#if defined(CVARS_WHITELIST) - CSystem* pSystem = static_cast(gEnv->pSystem); - ICVarsWhitelist* pCVarsWhitelist = pSystem->GetCVarsWhiteList(); -#endif // defined(CVARS_WHITELIST) bool bArgumentAutoComplete = false; std::vector matches; @@ -2565,10 +2383,6 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer) string cmd = string(sVar) + " " + pArgumentAutoComplete->GetValue(i); if (_strnicmp(m_sPrevTab.c_str(), cmd.c_str(), m_sPrevTab.length()) == 0) { -#if defined(CVARS_WHITELIST) - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(cmd, true) : true; - if (whitelisted) -#endif // defined(CVARS_WHITELIST) { bArgumentAutoComplete = true; matches.push_back(cmd); @@ -2590,10 +2404,6 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer) { if (_strnicmp(m_sPrevTab.c_str(), itrCmds->first.c_str(), m_sPrevTab.length()) == 0) { -#if defined(CVARS_WHITELIST) - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(itrCmds->first, true) : true; - if (whitelisted) -#endif // defined(CVARS_WHITELIST) { matches.push_back((char* const)itrCmds->first.c_str()); } @@ -2613,10 +2423,6 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer) {//if(itrVars->first.compare(0,m_sPrevTab.length(),m_sPrevTab)==0) if (_strnicmp(m_sPrevTab.c_str(), itrVars->first, m_sPrevTab.length()) == 0) { -#if defined(CVARS_WHITELIST) - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(itrVars->first, true) : true; - if (whitelisted) -#endif // defined(CVARS_WHITELIST) { matches.push_back((char* const)itrVars->first); } @@ -2990,12 +2796,6 @@ void CXConsole::ExecuteInputBuffer() AddCommandToHistory(sTemp.c_str()); -#if defined(CVARS_WHITELIST) - CSystem* pSystem = static_cast(gEnv->pSystem); - ICVarsWhitelist* pCVarsWhitelist = pSystem->GetCVarsWhiteList(); - bool execute = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(sTemp, false) : true; - if (execute) -#endif // defined(CVARS_WHITELIST) { ExecuteStringInternal(sTemp.c_str(), true); // from console } diff --git a/Code/CryEngine/CrySystem/XML/xml.cpp b/Code/CryEngine/CrySystem/XML/xml.cpp index 601b14eeb3..438b35b6c8 100644 --- a/Code/CryEngine/CrySystem/XML/xml.cpp +++ b/Code/CryEngine/CrySystem/XML/xml.cpp @@ -1809,8 +1809,6 @@ XmlNodeRef XmlParserImp::ParseFile(const char* filename, XmlString& errorString, ParseEnd(); } - SYNCHRONOUS_LOADING_TICK(); - delete [] pFileContents; return root; diff --git a/Code/CryEngine/CrySystem/crysystem_files.cmake b/Code/CryEngine/CrySystem/crysystem_files.cmake index 5dc8a68f8b..50cbdc24e4 100644 --- a/Code/CryEngine/CrySystem/crysystem_files.cmake +++ b/Code/CryEngine/CrySystem/crysystem_files.cmake @@ -19,14 +19,11 @@ set(FILES ConsoleBatchFile.cpp ConsoleHelpGen.cpp CryAsyncMemcpy.cpp - DebugCallStack.cpp GeneralMemoryHeap.cpp HandlerBase.cpp - IDebugCallStack.cpp AsyncPakManager.cpp Log.cpp SystemRender.cpp - NotificationNetwork.cpp PhysRenderer.cpp ResourceManager.cpp ServerHandler.cpp @@ -36,7 +33,6 @@ set(FILES SystemCFG.cpp SystemEventDispatcher.cpp SystemInit.cpp - SystemScheduler.cpp SystemWin32.cpp Timer.cpp UnixConsole.cpp @@ -52,7 +48,6 @@ set(FILES ServerHandler.h ServerThrottle.h SyncLock.h - SystemScheduler.h UnixConsole.h SystemInit.h XML/ReadWriteXMLSink.h @@ -63,12 +58,8 @@ set(FILES ConsoleBatchFile.h ConsoleHelpGen.h CryWaterMark.h - DebugCallStack.h GeneralMemoryHeap.h - IDebugCallStack.h - IThreadConfigManager.h Log.h - NotificationNetwork.h resource.h SimpleStringPool.h CrySystem_precompiled.h @@ -107,24 +98,12 @@ set(FILES XML/WriteXMLSource.cpp ZipFile.h ZipFileFormat_info.h - ProfileLogSystem.cpp Sampler.cpp - ProfileLogSystem.h Sampler.h LocalizedStringManager.cpp LocalizedStringManager.h - CryThreadUtil_win32_thread.h - ThreadInfo.cpp - ThreadInfo.h - ThreadTask.h - ThreadTask.cpp - ThreadConfigManager.h - ThreadConfigManager.cpp - SystemThreading.cpp ZLibCompressor.cpp ZLibCompressor.h - SoftCode/SoftCodeMgr.cpp - SoftCode/SoftCodeMgr.h Huffman.cpp Huffman.h RemoteConsole/RemoteConsole.cpp diff --git a/Code/CryEngine/CrySystem/crysystem_test_files.cmake b/Code/CryEngine/CrySystem/crysystem_test_files.cmake index a57ba57f77..d8f6887da6 100644 --- a/Code/CryEngine/CrySystem/crysystem_test_files.cmake +++ b/Code/CryEngine/CrySystem/crysystem_test_files.cmake @@ -18,7 +18,5 @@ set(FILES Tests/Test_Localization.cpp Tests/test_Main.cpp Tests/test_MaterialUtils.cpp - UnitTests/CryMathTests.cpp - UnitTests/CryPakUnitTests.cpp DllMain.cpp ) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserComponent.cpp index 8d3513cbcb..c505639338 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserComponent.cpp @@ -263,8 +263,6 @@ namespace AzToolsFramework return SourceFileDetails("Icons/AssetBrowser/XML_16.svg"); } - - // this is here to prevent having to include IResourceCompilerHelper, which is in CryCommon. static const char* sourceFormats[] = { ".tif", ".bmp", ".gif", ".jpg", ".jpeg", ".jpe", ".tga", ".png" }; for (unsigned int sourceImageFormatIndex = 0, numSources = AZ_ARRAY_SIZE(sourceFormats); sourceImageFormatIndex < numSources; ++sourceImageFormatIndex) diff --git a/Code/LauncherUnified/Launcher.cpp b/Code/LauncherUnified/Launcher.cpp index 033169ac6d..1f29478399 100644 --- a/Code/LauncherUnified/Launcher.cpp +++ b/Code/LauncherUnified/Launcher.cpp @@ -573,11 +573,6 @@ namespace O3DELauncher systemInitParams.hWnd = mainInfo.m_window; systemInitParams.pPrintSync = mainInfo.m_printSink; - if (strstr(mainInfo.m_commandLine, "-norandom")) - { - systemInitParams.bNoRandom = true; - } - systemInitParams.bDedicatedServer = IsDedicatedServer(); if (IsDedicatedServer()) { diff --git a/Code/Sandbox/Editor/BackgroundScheduleManager.cpp b/Code/Sandbox/Editor/BackgroundScheduleManager.cpp deleted file mode 100644 index 23eee6daf4..0000000000 --- a/Code/Sandbox/Editor/BackgroundScheduleManager.cpp +++ /dev/null @@ -1,629 +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 "BackgroundScheduleManager.h" - -namespace BackgroundScheduleManager -{ - //----------------------------------------------------------------------------- - - CScheduleItem::CScheduleItem(const char* szName) - : m_name(szName) - , m_refCount(1) - , m_state(eScheduleItemState_Pending) - { - } - - CScheduleItem::~CScheduleItem() - { - CRY_ASSERT(m_refCount == 0); - - for (TWorkItems::const_iterator it = m_workItems.begin(); - it != m_workItems.end(); ++it) - { - (*it)->Release(); - } - } - - const char* CScheduleItem::GetDescription() const - { - return m_name.c_str(); - } - - EScheduleItemState CScheduleItem::GetState() const - { - return m_state; - } - - const float CScheduleItem::GetProgress() const - { - if (m_workItems.empty()) - { - return 1.0f; - } - else - { - float totalProgress = 0.0f; - - for (TWorkItems::const_iterator it = m_workItems.begin(); - it != m_workItems.end(); ++it) - { - totalProgress += (*it)->GetProgress(); - } - - return totalProgress / (float)m_workItems.size(); - } - } - - const uint32 CScheduleItem::GetNumWorkItems() const - { - return m_workItems.size(); - } - - IBackgroundScheduleItemWork* CScheduleItem::GetWorkItem(const uint32 index) const - { - return m_workItems[index]; - } - - void CScheduleItem::AddWorkItem(IBackgroundScheduleItemWork* pWork) - { - // cannot add new work items when item has finished or failed - if (m_state == eScheduleItemState_Failed || m_state == eScheduleItemState_Completed) - { - CryFatalError("Cannot add new work items when item has finished or failed"); - return; - } - - // add to the work list - if (m_state == eScheduleItemState_Processing) - { - m_addedWorkItems.push_back(pWork); - } - else - { - m_workItems.push_back(pWork); - } - } - - void CScheduleItem::AddRef() - { - CryInterlockedIncrement(&m_refCount); - } - - void CScheduleItem::Release() - { - const int nCount = CryInterlockedDecrement(&m_refCount); - assert(nCount >= 0); - if (nCount == 0) - { - delete this; - } - else if (nCount < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } - } - - void CScheduleItem::RequestStop() - { - if (m_state == eScheduleItemState_Pending) - { - // we can stop right away :) - m_state = eScheduleItemState_Failed; - } - else if (m_state == eScheduleItemState_Processing) - { - m_state = eScheduleItemState_Stopping; - - // signal all pending work to stop - uint32 curIndex = 0; - while (curIndex < m_processedWorkItems.size()) - { - IBackgroundScheduleItemWork* pWork = m_processedWorkItems[curIndex]; - if (pWork->OnStop()) - { - // if the work was stopped remove it from list - m_processedWorkItems.erase(m_processedWorkItems.begin() + curIndex); - continue; - } - else - { - // this work item cannot be stopped this frame - curIndex += 1; - } - } - - // if all pending work has been stopped we can assume the failed state - if (m_processedWorkItems.empty()) - { - m_state = eScheduleItemState_Failed; - } - } - } - - EScheduleWorkItemStatus CScheduleItem::Update() - { - EScheduleWorkItemStatus retStatus = eScheduleWorkItemStatus_NotFinished; - - switch (m_state) - { - // finial state - work failed - case eScheduleItemState_Failed: - { - retStatus = eScheduleWorkItemStatus_Failed; - break; - } - - // final state - work completed - case eScheduleItemState_Completed: - { - retStatus = eScheduleWorkItemStatus_Finished; - break; - } - - // first update, start all the work items - case eScheduleItemState_Pending: - { - // start all of the tasks - bool bHasFailedStarts = false; - for (TWorkItems::const_iterator it = m_workItems.begin(); - it != m_workItems.end(); ++it) - { - IBackgroundScheduleItemWork* pWork = (*it); - - if (pWork->OnStart()) - { - m_processedWorkItems.push_back(pWork); - } - else - { - bHasFailedStarts = true; - break; - } - } - - if (bHasFailedStarts) - { - m_state = eScheduleItemState_Stopping; - break; - } - else - { - m_state = eScheduleItemState_Processing; - /* FALLS THROUGHT TO PROCESSING STATE */ - } - } - - // work processing state - case eScheduleItemState_Processing: - { - // process new work items that were added while the schedule was created - if (!m_addedWorkItems.empty()) - { - for (TWorkItems::const_iterator it = m_addedWorkItems.begin(); - it != m_addedWorkItems.end(); ++it) - { - IBackgroundScheduleItemWork* pWork = (*it); - pWork->OnStart(); - m_processedWorkItems.push_back(pWork); - m_workItems.push_back(pWork); - } - - m_addedWorkItems.clear(); - } - - // update work items - bool bHasFailedItems = false; - TWorkItems completedItems; - for (TWorkItems::const_iterator it = m_processedWorkItems.begin(); - it != m_processedWorkItems.end(); ++it) - { - IBackgroundScheduleItemWork* pWork = (*it); - - // update given work item - const EScheduleWorkItemStatus status = pWork->OnUpdate(); - if (status == eScheduleWorkItemStatus_Finished) - { - completedItems.push_back(pWork); - continue; - } - - // item failed - we need to stop other tasks - if (status == eScheduleWorkItemStatus_Failed) - { - bHasFailedItems = true; - break; - } - } - - // cleanup completed items - for (TWorkItems::iterator it = completedItems.begin(); - it != completedItems.end(); ++it) - { - IBackgroundScheduleItemWork* pWork = (*it); - TWorkItems::iterator jt = std::find(m_processedWorkItems.begin(), m_processedWorkItems.end(), pWork); - m_processedWorkItems.erase(jt); - } - - if (!bHasFailedItems) - { - // all work has finished - if (m_processedWorkItems.empty()) - { - retStatus = eScheduleWorkItemStatus_Finished; - m_state = eScheduleItemState_Completed; - } - - break; - } - else - { - // some of the items failed - m_state = eScheduleItemState_Stopping; - /* FALL THROUGH TO STOPPING STATE */ - } - } - - // We are stopping failed work - case eScheduleItemState_Stopping: - { - uint32 curIndex = 0; - while (curIndex < m_processedWorkItems.size()) - { - IBackgroundScheduleItemWork* pWork = m_processedWorkItems[curIndex]; - if (pWork->OnStop()) - { - // if the work was stopped remove it from list - m_processedWorkItems.erase(m_processedWorkItems.begin() + curIndex); - continue; - } - else - { - // this work item cannot be stopped this frame - curIndex += 1; - } - } - - // if all pending work has been stopped we can assume the failed state - if (m_processedWorkItems.empty()) - { - m_state = eScheduleItemState_Failed; - return eScheduleWorkItemStatus_Failed; - } - } - } - - return retStatus; - } - - //----------------------------------------------------------------------------- - - CSchedule::CSchedule(const char* szName) - : m_name(szName) - , m_refCount(1) - , m_bCanceled(false) - , m_currentItem(0) - , m_state(eScheduleState_Pending) - { - } - - CSchedule::~CSchedule() - { - CRY_ASSERT(m_refCount == 0); - - for (TItems::const_iterator it = m_items.begin(); - it != m_items.end(); ++it) - { - CScheduleItem* pItem = *it; - SAFE_RELEASE(pItem); - } - - m_items.clear(); - } - - const char* CSchedule::GetDescription() const - { - return m_name.c_str(); - } - - float CSchedule::GetProgress() const - { - if (m_currentItem >= m_items.size()) - { - return 1.0f; - } - else - { - const float itemProgress = 1.0f / (float)(m_items.size()); - const IBackgroundScheduleItem* pItem = m_items[m_currentItem]; - return (m_currentItem + pItem->GetProgress()) * itemProgress; - } - } - - IBackgroundScheduleItem* CSchedule::GetProcessedItem() const - { - if (m_currentItem >= m_items.size()) - { - return NULL; - } - else - { - IBackgroundScheduleItem* pItem = m_items[m_currentItem]; - return pItem; - } - } - - const uint32 CSchedule::GetNumItems() const - { - return m_items.size(); - } - - IBackgroundScheduleItem* CSchedule::GetItem(const uint32 index) const - { - return m_items[index]; - } - - EScheduleState CSchedule::GetState() const - { - return m_state; - } - - void CSchedule::Cancel() - { - m_bCanceled = true; - } - - bool CSchedule::IsCanceled() const - { - return m_bCanceled; - } - - void CSchedule::AddItem(IBackgroundScheduleItem* pItem) - { - if (NULL == pItem) - { - return; - } - - // we can add items only in the "pending" state - if (pItem->GetState() != eScheduleItemState_Pending) - { - CryFatalError("Schedule items can be added to schedule only before their work starts"); - return; - } - - // item has no jobs, do not add - if (pItem->GetNumWorkItems() == 0) - { - return; - } - - m_items.push_back(static_cast(pItem)); - pItem->AddRef(); - } - - void CSchedule::AddRef() - { - CryInterlockedIncrement(&m_refCount); - } - - void CSchedule::Release() - { - const int nCount = CryInterlockedDecrement(&m_refCount); - assert(nCount >= 0); - if (nCount == 0) - { - delete this; - } - else if (nCount < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } - } - - EScheduleWorkItemStatus CSchedule::Update() - { - EScheduleWorkItemStatus retStatus = eScheduleWorkItemStatus_NotFinished; - - // we have a cancel request - if (m_bCanceled) - { - CryLog("Schedule '%s' was canceled", GetDescription()); - - if (m_state == eScheduleState_Processing && m_currentItem < m_items.size()) - { - // stop the current item - CScheduleItem* pItem = m_items[m_currentItem]; - pItem->RequestStop(); - m_state = eSccheduleState_Stopping; - } - else if (m_state != eScheduleState_Completed) - { - m_state = eScheduleState_Failed; - return eScheduleWorkItemStatus_Failed; - } - } - - // process internal state machine - switch (m_state) - { - // final state - work failed - case eScheduleState_Failed: - { - retStatus = eScheduleWorkItemStatus_Failed; - break; - } - - // final state - work completed - case eScheduleState_Completed: - { - retStatus = eScheduleWorkItemStatus_Finished; - break; - } - - // stopping current task - case eSccheduleState_Stopping: - { - if (m_currentItem < m_items.size()) - { - CScheduleItem* pItem = m_items[m_currentItem]; - if (pItem->Update() != eScheduleWorkItemStatus_NotFinished) - { - // task was finally stopped - m_state = eScheduleState_Failed; - retStatus = eScheduleWorkItemStatus_Failed; - } - } - - break; - } - - // first update, switch to processing - case eScheduleState_Pending: - { - m_state = eScheduleState_Processing; - m_currentItem = 0; - /* FALLS THROUGHT */ - } - - // if we were in the processing phase inform the current schedule item to stop all it's work - case eScheduleState_Processing: - { - // update schedule items - while (m_currentItem < m_items.size()) - { - CScheduleItem* pItem = m_items[m_currentItem]; - - const EScheduleWorkItemStatus itemStatus = pItem->Update(); - if (itemStatus == eScheduleWorkItemStatus_Finished) - { - m_currentItem += 1; - continue; - } - else if (itemStatus == eScheduleWorkItemStatus_Failed) - { - m_state = eScheduleState_Failed; - retStatus = eScheduleWorkItemStatus_Failed; - gEnv->pLog->LogWarning("Schedule '%s' failed on item '%s'.", GetDescription(), pItem->GetDescription()); - } - - break; - } - - // all items updated - if (m_currentItem >= m_items.size()) - { - // empty schedule, complete in one tick - m_state = eScheduleState_Completed; - retStatus = eScheduleWorkItemStatus_Finished; - CryLog("Schedule '%s' completed", GetDescription()); - } - - break; - } - } - - return retStatus; - } - - //----------------------------------------------------------------------------- - - CScheduleManager::CScheduleManager() - { - GetIEditor()->RegisterNotifyListener(this); - } - - CScheduleManager::~CScheduleManager() - { - GetIEditor()->UnregisterNotifyListener(this); - - for (TSchedules::const_iterator it = m_schedules.begin(); - it != m_schedules.end(); ++it) - { - CSchedule* pSchedule = *it; - SAFE_RELEASE(pSchedule); - } - - m_schedules.clear(); - } - - IBackgroundSchedule* CScheduleManager::CreateSchedule(const char* szName) - { - return new CSchedule(szName); - } - - IBackgroundScheduleItem* CScheduleManager::CreateScheduleItem(const char* szName) - { - return new CScheduleItem(szName); - } - - void CScheduleManager::SubmitSchedule(IBackgroundSchedule* pSchedule) - { - if (NULL != pSchedule) - { - if (pSchedule->GetState() != eScheduleState_Pending) - { - CryFatalError("Only schedules with pending state can be submitted"); - return; - } - - pSchedule->AddRef(); - m_schedules.push_back(static_cast(pSchedule)); - } - } - - const uint32 CScheduleManager::GetNumSchedules() const - { - return m_schedules.size(); - } - - IBackgroundSchedule* CScheduleManager::GetSchedule(const uint32 index) const - { - return m_schedules[index]; - } - - void CScheduleManager::Update() - { - while (!m_schedules.empty()) - { - CSchedule* pSchedule = m_schedules[0]; - - const EScheduleWorkItemStatus status = pSchedule->Update(); - if (status == eScheduleWorkItemStatus_NotFinished) - { - // we need more work next frame - break; - } - - // schedule has finished, remove current reference - m_schedules.erase(m_schedules.begin()); - SAFE_RELEASE(pSchedule); - } - } - - void CScheduleManager::OnEditorNotifyEvent(EEditorNotifyEvent ev) - { - switch (ev) - { - case eNotify_OnQuit: - GetIEditor()->UnregisterNotifyListener(this); - break; - } - } - - //----------------------------------------------------------------------------- -} // BackgroundScheduleManager diff --git a/Code/Sandbox/Editor/BackgroundScheduleManager.h b/Code/Sandbox/Editor/BackgroundScheduleManager.h deleted file mode 100644 index 4deeaba64f..0000000000 --- a/Code/Sandbox/Editor/BackgroundScheduleManager.h +++ /dev/null @@ -1,117 +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_BACKGROUNDSCHEDULEMANAGER_H -#define CRYINCLUDE_EDITOR_BACKGROUNDSCHEDULEMANAGER_H -#pragma once - -#include "Include/IBackgroundScheduleManager.h" - -namespace BackgroundScheduleManager -{ - class CScheduleItem - : public IBackgroundScheduleItem - { - private: - std::string m_name; - volatile int m_refCount; - - EScheduleItemState m_state; - - typedef std::vector TWorkItems; - TWorkItems m_workItems; - TWorkItems m_addedWorkItems; - TWorkItems m_processedWorkItems; - - public: - CScheduleItem(const char* szName); - virtual ~CScheduleItem(); - - // IBackgroundScheduleItem interface - virtual const char* GetDescription() const; - virtual EScheduleItemState GetState() const; - virtual const float GetProgress() const; - virtual const uint32 GetNumWorkItems() const; - virtual IBackgroundScheduleItemWork* GetWorkItem(const uint32 index) const; - virtual void AddWorkItem(IBackgroundScheduleItemWork* pWork); - virtual void AddRef(); - virtual void Release(); - - // Update schedule item - EScheduleWorkItemStatus Update(); - - // Request to stop work in this item - void RequestStop(); - }; - - class CSchedule - : public IBackgroundSchedule - { - private: - std::string m_name; - volatile int m_refCount; - bool m_bCanceled; - - EScheduleState m_state; - - typedef std::vector TItems; - TItems m_items; - - uint32 m_currentItem; - - public: - CSchedule(const char* szName); - virtual ~CSchedule(); - - // IBackgroundSchedule interface - virtual const char* GetDescription() const; - virtual float GetProgress() const; - virtual IBackgroundScheduleItem* GetProcessedItem() const; - virtual const uint32 GetNumItems() const; - virtual IBackgroundScheduleItem* GetItem(const uint32 index) const; - virtual EScheduleState GetState() const; - virtual void Cancel(); - virtual bool IsCanceled() const; - virtual void AddItem(IBackgroundScheduleItem* pItem); - virtual void AddRef(); - virtual void Release(); - - // Update schedule item - EScheduleWorkItemStatus Update(); - }; - - class CScheduleManager - : public IBackgroundScheduleManager - , public IEditorNotifyListener - { - private: - typedef std::vector TSchedules; - TSchedules m_schedules; - - public: - CScheduleManager(); - virtual ~CScheduleManager(); - - // IBackgroundScheduleManager interface - virtual IBackgroundSchedule* CreateSchedule(const char* szName); - virtual IBackgroundScheduleItem* CreateScheduleItem(const char* szName); - virtual void SubmitSchedule(IBackgroundSchedule* pSchedule); - virtual const uint32 GetNumSchedules() const; - virtual IBackgroundSchedule* GetSchedule(const uint32 index) const; - virtual void Update(); - - // IEditorNotifyListener interface implementation - virtual void OnEditorNotifyEvent(EEditorNotifyEvent ev) override; - }; -} -#endif // CRYINCLUDE_EDITOR_BACKGROUNDSCHEDULEMANAGER_H diff --git a/Code/Sandbox/Editor/BackgroundTaskManager.cpp b/Code/Sandbox/Editor/BackgroundTaskManager.cpp deleted file mode 100644 index c05e709fd0..0000000000 --- a/Code/Sandbox/Editor/BackgroundTaskManager.cpp +++ /dev/null @@ -1,410 +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 "BackgroundTaskManager.h" - -namespace BackgroundTaskManager -{ - //----------------------------------------------------------------------------- - - CTaskManager::CThread::CThread(class CTaskManager* pManager, CQueue* pQueue) - : m_pManager(pManager) - , m_pQueue(pQueue) - { - start(); - } - - CTaskManager::CThread::~CThread() - { - } - - void CTaskManager::CThread::WaitForThread() - { - wait(); - } - - void CTaskManager::CThread::run() - { - CryThreadSetName(-1, "BackgroundTaskThread"); - - while (!m_pManager->IsStopped()) - { - STaskHandle taskHandle; - - // This blocks on Semaphore waiting for task from queue - m_pQueue->PopTask(taskHandle); - - // Should not happen but it's a stupid way to crash :) - if (NULL == taskHandle.pTask) - { - continue; - } - - if (taskHandle.pTask->IsCanceled()) - { - // Task was canceled before we got here - m_pManager->AddCompletedTask(taskHandle, eTaskResult_Canceled); - } - else - { - const ETaskResult state = taskHandle.pTask->Work(); - - if (state == eTaskResult_Resume) - { - // Put it back into queue, so more important task can take over. - m_pManager->AddTask(taskHandle); - } - else - { - // Finish task - m_pManager->AddCompletedTask(taskHandle, state); - } - } - } - } - - //----------------------------------------------------------------------------- - - CTaskManager::CQueue::CQueue() - : m_semaphore(INT_MAX, 0) // no good maximum value, assume worst case - { - } - - void CTaskManager::CQueue::AddTask(const STaskHandle& taskHandle) - { - { - CryAutoLock lock(m_lock); - - // TODO: use heap? - m_pendingTasks.insert(m_pendingTasks.begin(), taskHandle); - std::stable_sort(m_pendingTasks.begin(), m_pendingTasks.end()); - } - - taskHandle.pTask->SetState(eTaskState_Pending); - - // release internal semaphore so threads can pick up the work - m_semaphore.Release(); - } - - void CTaskManager::CQueue::PopTask(STaskHandle& outTaskHandle) - { - // wait for job - m_semaphore.Acquire(); - - { - CryAutoLock lock(m_lock); - - if (m_pendingTasks.empty()) - { - outTaskHandle.pTask = NULL; - } - else - { - outTaskHandle = m_pendingTasks.back(); - outTaskHandle.pTask->SetState(eTaskState_Working); - m_pendingTasks.pop_back(); - } - } - } - - void CTaskManager::CQueue::ReleaseSemaphore() - { - m_semaphore.Release(); - } - - void CTaskManager::CQueue::Clear() - { - CryAutoLock lock(m_lock); - for (uint i = 0; i < m_pendingTasks.size(); ++i) - { - m_pendingTasks[i].pTask->Release(); - } - - m_pendingTasks.clear(); - } - - //----------------------------------------------------------------------------- - - CTaskManager::CTaskManager() - : m_bStop(false) - , m_nextTaskID(1) - , m_listeners(1) - { - GetIEditor()->RegisterNotifyListener(this); - } - - CTaskManager::~CTaskManager() - { - if (!m_bStop) - { - Stop(); - } - } - - void CTaskManager::Start(const uint32 threadCount /*=kDefaultThreadCount*/) - { - m_bStop = false; - - if (m_pThreads.empty()) - { - // Always create one IO thread - { - CThread* pThread = new CThread(this, &m_pendingTasks[ eTaskThreadMask_IO ]); - m_pThreads.push_back(pThread); - } - - // We also need at least one generic thread - const uint32 numGenericThreads = max(threadCount, 1); - for (uint32 i = 0; i < numGenericThreads; ++i) - { - CThread* pThread = new CThread(this, &m_pendingTasks[ eTaskThreadMask_Any ]); - m_pThreads.push_back(pThread); - } - } - } - - void CTaskManager::StartScheduledTasks() - { - CryAutoLock lock(m_tasksLock); - - if (!m_scheduledTasks.empty()) - { - const unsigned int time = GetTickCount(); - while (!m_scheduledTasks.empty()) - { - const int delta = (int)(time - m_scheduledTasks[0].time); - if (delta > 0) - { - // the soonest task on the list is still in the future, no point in looking at the next entries in the list - break; - } - - // promote the scheduled task to be a full task - AddTask(m_scheduledTasks[0].handle); - - // We held a reference to the task on list, release it - m_scheduledTasks[0].handle.pTask->Release(); - - m_scheduledTasks.erase(m_scheduledTasks.begin()); - } - } - } - - void CTaskManager::Stop() - { - if (!m_bStop) - { - m_bStop = true; - GetIEditor()->UnregisterNotifyListener(this); - - // clear queues - no new tasks will be processed - for (uint32 i = 0; i < eTaskThreadMask_COUNT; ++i) - { - m_pendingTasks[i].Clear(); - } - - // kick all the threads to allow them to quit - for (uint32 j = 0; j < m_pThreads.size(); ++j) - { - for (uint32 i = 0; i < eTaskThreadMask_COUNT; ++i) - { - m_pendingTasks[i].ReleaseSemaphore(); - } - } - - // Stop threads - for (TWorkerThreads::iterator it = m_pThreads.begin(); - it != m_pThreads.end(); ++it) - { - (*it)->WaitForThread(); - delete *it; - } - - m_pThreads.clear(); - } - } - - void CTaskManager::AddListener(IBackgroundTaskManagerListener* pListener, const char* name) - { - m_listeners.Add(pListener, name); - } - - void CTaskManager::RemoveListener(IBackgroundTaskManagerListener* pListener) - { - m_listeners.Remove(pListener); - } - - void CTaskManager::AddTask(IBackgroundTask* pTask, ETaskPriority priority, ETaskThreadMask threadMask) - { - MAKE_SURE(pTask != 0, return ); - - // keep an extra reference to the task in the manager - pTask->AddRef(); - - STaskHandle handle; - handle.id = CryInterlockedIncrement(&m_nextTaskID); - handle.priority = priority; - handle.threadMask = threadMask; - handle.pTask = pTask; - - AddTask(handle); - - for (TListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next()) - { - notifier->OnBackgroundTaskAdded(pTask->Description()); - } - } - - void CTaskManager::ScheduleTask(IBackgroundTask* pTask, ETaskPriority priority, int delayMilliseconds, ETaskThreadMask threadMask) - { - MAKE_SURE(delayMilliseconds >= 0, return ); - MAKE_SURE(pTask != 0, return ); - - // keep an extra reference to the task in the manager - pTask->AddRef(); - - SScheduledTask task; - task.time = GetTickCount() + delayMilliseconds; - task.handle.pTask = pTask; - task.handle.id = CryInterlockedIncrement(&m_nextTaskID); - task.handle.threadMask = threadMask; - task.handle.priority = priority; - - { - CryAutoLock lock(m_tasksLock); - m_scheduledTasks.push_back(task); - } - - for (TListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next()) - { - notifier->OnBackgroundTaskAdded(pTask->Description()); - } - } - - void CTaskManager::AddTask(const STaskHandle& handle) - { - MAKE_SURE(handle.pTask != 0, return ); - MAKE_SURE(handle.id != 0, return ); - - // add task to appropriate queue (every thread mask has it's own queue) - m_pendingTasks[handle.threadMask].AddTask(handle); - } - - void CTaskManager::AddCompletedTask(const STaskHandle& handle, ETaskResult resultState) - { - CryAutoLock lock(m_tasksLock); - - CRY_ASSERT(handle.pTask->GetState() == eTaskState_Working); - CRY_ASSERT(resultState != eTaskResult_Resume); - - // Update task state - switch (resultState) - { - case eTaskResult_Canceled: - { - handle.pTask->SetState(eTaskState_Canceled); - break; - } - - case eTaskResult_Completed: - { - handle.pTask->SetState(eTaskState_Completed); - break; - } - - case eTaskResult_Failed: - { - handle.pTask->SetState(eTaskState_Failed); - break; - } - } - - // add to the list of completed tasks (for calling the Finalize) - // TODO: some of the tasks do not require Finalize() and they could be released here instead of the main thread - SCompletedTask info; - info.pTask = handle.pTask; - info.id = handle.id; - info.state = resultState; - m_completedTasks.push_back(info); - } - - void CTaskManager::Update() - { - std::vector completedTasks; - { - CryAutoLock lock(m_tasksLock); - m_completedTasks.swap(completedTasks); - } - - // call finalize for the completed tasks - for (size_t i = 0; i < completedTasks.size(); ++i) - { - SCompletedTask& handle = completedTasks[i]; - - if (NULL != handle.pTask) - { - string description = handle.pTask->Description(); // copy string as the description is used after pTask is destroyed - - if (handle.state == eTaskResult_Completed) - { - if (description && description[0] != '\0') - { - gEnv->pLog->Log("Task Completed: %s", description.c_str()); - } - } - else if (handle.state == eTaskResult_Failed) - { - if (description && description[0] != '\0' && !handle.pTask->FailReported()) - { - gEnv->pLog->LogError("Task Failed: %s ", description.c_str()); - - const char* errorMessage = handle.pTask->ErrorMessage(); - if (errorMessage && errorMessage[0] != '\0') - { - gEnv->pLog->LogError("\tReason: [%s]", errorMessage); - } - } - } - - handle.pTask->Finalize(); - - // release the internal (task manager) reference. - // Tthis is usually the last reference to the task so it gets deleted here. - handle.pTask->Release(); - - for (TListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next()) - { - notifier->OnBackgroundTaskCompleted(handle.state, description.c_str()); - } - } - } - } - - void CTaskManager::OnEditorNotifyEvent(EEditorNotifyEvent ev) - { - switch (ev) - { - case eNotify_OnInit: - Start(); - break; - case eNotify_OnIdleUpdate: - Update(); - break; - case eNotify_OnQuit: - Stop(); - break; - } - } -} diff --git a/Code/Sandbox/Editor/BackgroundTaskManager.h b/Code/Sandbox/Editor/BackgroundTaskManager.h deleted file mode 100644 index b440c66f1a..0000000000 --- a/Code/Sandbox/Editor/BackgroundTaskManager.h +++ /dev/null @@ -1,161 +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_BACKGROUNDTASKMANAGER_H -#define CRYINCLUDE_EDITOR_BACKGROUNDTASKMANAGER_H -#pragma once - -#include "Include/IBackgroundTaskManager.h" -#include "CryListenerSet.h" - -#include - -namespace BackgroundTaskManager -{ - typedef int TTaskID; - - struct STaskHandle - { - ETaskPriority priority; - ETaskThreadMask threadMask; - TTaskID id; - IBackgroundTask* pTask; - - bool operator<(const STaskHandle& rhs) const - { - if (priority < rhs.priority) - { - return true; - } - if (priority > rhs.priority) - { - return false; - } - return id < rhs.id; - } - }; - - struct SCompletedTask - { - ETaskResult state; - TTaskID id; - ETaskThreadMask threadMask; - IBackgroundTask* pTask; - }; - - struct SScheduledTask - { - unsigned int time; - STaskHandle handle; - }; - - class CTaskManager - : public IBackgroundTaskManager - , public IEditorNotifyListener - { - public: - CTaskManager(); - ~CTaskManager(); - - // IBackgroundTaskManager interface implementation - virtual void AddTask(IBackgroundTask* pTask, ETaskPriority priority, ETaskThreadMask threadMask) override; - virtual void ScheduleTask(IBackgroundTask* pTask, ETaskPriority priority, int delayMilliseconds, ETaskThreadMask threadMask) override; - void AddListener(IBackgroundTaskManagerListener* pListener, const char* name) override; - void RemoveListener(IBackgroundTaskManagerListener* pListener) override; - - private: - // IEditorNotifyListener interface implementation - virtual void OnEditorNotifyEvent(EEditorNotifyEvent ev) override; - - void Start(const uint32 threadCount = kDefaultThreadCount); - void Stop(); - void StartScheduledTasks(); - void AddTask(const STaskHandle& outTask); - void AddCompletedTask(const STaskHandle& outTask, ETaskResult resultState); - void Update(); - - inline bool IsStopped() const - { - return m_bStop; - } - - private: - // Internal queue (per thread mask) - class CQueue - { - public: - CQueue(); - - // Add task to list - void AddTask(const STaskHandle& taskHandle); - - // Pop task from list - void PopTask(STaskHandle& outTaskHandle); - - // Release thread semaphore without adding a task - void ReleaseSemaphore(); - - // Remove all pending tasks - void Clear(); - - private: - CrySemaphore m_semaphore; - std::vector m_pendingTasks; - CryMutex m_lock; - }; - - // Worker thread class implementation - class CThread : public QThread - { - public: - CThread(CTaskManager* pManager, CQueue* pQueue); - ~CThread(); - - void WaitForThread(); - - private: - void run() override; - - private: - CTaskManager* m_pManager; - CQueue* m_pQueue; - }; - - private: - static const uint32 kMaxThreadCloseWaitTime = 10000; // ms - static const uint32 kDefaultThreadCount = 4; // good enough for LiveCreate (main user right now), do not set to less than 2 - - CQueue m_pendingTasks[ eTaskThreadMask_COUNT ]; - - // Task scheduled for execution in the future - std::vector m_scheduledTasks; - - // Completed tasks (waiting for the "finalize" call) - std::vector m_completedTasks; - - volatile TTaskID m_nextTaskID; - - typedef std::vector TWorkerThreads; - TWorkerThreads m_pThreads; - - CryMutex m_tasksLock; - bool m_bStop; - - typedef CListenerSet TListeners; - TListeners m_listeners; - }; -} - -//----------------------------------------------------------------------------- - -#endif // CRYINCLUDE_EDITOR_BACKGROUNDTASKMANAGER_H diff --git a/Code/Sandbox/Editor/CMakeLists.txt b/Code/Sandbox/Editor/CMakeLists.txt index 726f7ac2c7..7d89717391 100644 --- a/Code/Sandbox/Editor/CMakeLists.txt +++ b/Code/Sandbox/Editor/CMakeLists.txt @@ -112,7 +112,6 @@ ly_add_target( 3rdParty::zlib 3rdParty::AWSNativeSDK::STS Legacy::CryCommon - Legacy::CryCommon.EngineSettings.Static Legacy::EditorCommon AZ::AzCore AZ::AzToolsFramework diff --git a/Code/Sandbox/Editor/CryEdit.cpp b/Code/Sandbox/Editor/CryEdit.cpp index 6e33d32c6e..0bbc48d5f9 100644 --- a/Code/Sandbox/Editor/CryEdit.cpp +++ b/Code/Sandbox/Editor/CryEdit.cpp @@ -85,7 +85,6 @@ AZ_POP_DISABLE_WARNING // Editor #include "Settings.h" -#include "Include/IBackgroundScheduleManager.h" #include "GameExporter.h" #include "GameResourcesExporter.h" @@ -2314,15 +2313,6 @@ int CCryEditApp::IdleProcessing(bool bBackgroundUpdate) #endif } - // process the work schedule - regardless if the app is active or not - GetIEditor()->GetBackgroundScheduleManager()->Update(); - - // if there are active schedules keep updating the application - if (GetIEditor()->GetBackgroundScheduleManager()->GetNumSchedules() > 0) - { - bActive = true; - } - m_bPrevActive = bActive; AZStd::chrono::system_clock::time_point now = AZStd::chrono::system_clock::now(); diff --git a/Code/Sandbox/Editor/GameEngine.cpp b/Code/Sandbox/Editor/GameEngine.cpp index 1c91ce58aa..2112d00d64 100644 --- a/Code/Sandbox/Editor/GameEngine.cpp +++ b/Code/Sandbox/Editor/GameEngine.cpp @@ -420,7 +420,6 @@ AZ::Outcome CGameEngine::Init( #else sip.hWnd = hwndForInputSystem; #endif - sip.hWndForInputSystem = hwndForInputSystem; sip.pLogCallback = &m_logFile; sip.sLogFileName = "@log@/Editor.log"; @@ -503,7 +502,6 @@ AZ::Outcome CGameEngine::Init( bool CGameEngine::InitGame(const char*) { - // in editor we do it later, bExecuteCommandLine was set to false m_pISystem->ExecuteCommandLine(); return true; @@ -608,8 +606,6 @@ void CGameEngine::SwitchToInGame() GetIEditor()->Notify(eNotify_OnBeginGameMode); - m_pISystem->SetThreadState(ESubsys_Physics, false); - m_pISystem->GetIMovieSystem()->EnablePhysicsEvents(true); m_bInGameMode = true; @@ -646,8 +642,6 @@ void CGameEngine::SwitchToInEditor() } m_pISystem->GetIMovieSystem()->Reset(false, false); - m_pISystem->SetThreadState(ESubsys_Physics, false); - CViewport* pGameViewport = GetIEditor()->GetViewManager()->GetGameViewport(); m_pISystem->GetIMovieSystem()->EnablePhysicsEvents(m_bSimulationMode); @@ -791,8 +785,6 @@ void CGameEngine::SetSimulationMode(bool enabled, bool bOnlyPhysics) // Enables engine to know about simulation mode. gEnv->SetIsEditorSimulationMode(enabled); - m_pISystem->SetThreadState(ESubsys_Physics, false); - if (m_bSimulationMode) { // [Anton] the order of the next 3 calls changed, since, EVENT_INGAME loads physics state (if any), @@ -903,19 +895,6 @@ void CGameEngine::Update() // [marco] check current sound and vis areas for music etc. // but if in game mode, 'cos is already done in the above call to game->update() unsigned int updateFlags = ESYSUPDATE_EDITOR; - - if (!m_bSimulationMode) - { - updateFlags |= ESYSUPDATE_IGNORE_PHYSICS; - } - - bool bUpdateAIPhysics = GetSimulationMode(); - - if (bUpdateAIPhysics) - { - updateFlags |= ESYSUPDATE_EDITOR_AI_PHYSICS; - } - GetIEditor()->GetAnimation()->Update(); GetIEditor()->GetSystem()->UpdatePreTickBus(updateFlags); componentApplication->Tick(gEnv->pTimer->GetFrameTime(ITimer::ETIMER_GAME)); diff --git a/Code/Sandbox/Editor/IEditor.h b/Code/Sandbox/Editor/IEditor.h index 62672a6505..af98158037 100644 --- a/Code/Sandbox/Editor/IEditor.h +++ b/Code/Sandbox/Editor/IEditor.h @@ -550,7 +550,6 @@ struct IEditor virtual class CViewManager* GetViewManager() = 0; virtual class CViewport* GetActiveView() = 0; virtual void SetActiveView(CViewport* viewport) = 0; - virtual struct IBackgroundTaskManager* GetBackgroundTaskManager() = 0; virtual struct IEditorFileMonitor* GetFileMonitor() = 0; // These are needed for Qt integration: @@ -720,7 +719,6 @@ struct IEditor virtual ESystemConfigPlatform GetEditorConfigPlatform() const = 0; virtual void ReloadTemplates() = 0; virtual IResourceSelectorHost* GetResourceSelectorHost() = 0; - virtual struct IBackgroundScheduleManager* GetBackgroundScheduleManager() = 0; virtual void ShowStatusText(bool bEnable) = 0; // Provides a way to extend the context menu of an object. The function gets called every time the menu is opened. diff --git a/Code/Sandbox/Editor/IEditorImpl.cpp b/Code/Sandbox/Editor/IEditorImpl.cpp index fb9b737733..380fc80e66 100644 --- a/Code/Sandbox/Editor/IEditorImpl.cpp +++ b/Code/Sandbox/Editor/IEditorImpl.cpp @@ -66,8 +66,6 @@ AZ_POP_DISABLE_WARNING #include "Objects/SelectionGroup.h" #include "Objects/ObjectManager.h" -#include "BackgroundTaskManager.h" -#include "BackgroundScheduleManager.h" #include "EditorFileMonitor.h" #include "MainStatusBar.h" @@ -176,8 +174,6 @@ CEditorImpl::CEditorImpl() regCtx.pCommandManager = m_pCommandManager; regCtx.pClassFactory = m_pClassFactory; m_pEditorFileMonitor.reset(new CEditorFileMonitor()); - m_pBackgroundTaskManager.reset(new BackgroundTaskManager::CTaskManager); - m_pBackgroundScheduleManager.reset(new BackgroundScheduleManager::CScheduleManager); m_pUIEnumsDatabase = new CUIEnumsDatabase; m_pDisplaySettings = new CDisplaySettings; m_pDisplaySettings->LoadRegistry(); @@ -843,16 +839,6 @@ IIconManager* CEditorImpl::GetIconManager() return m_pIconManager; } -IBackgroundTaskManager* CEditorImpl::GetBackgroundTaskManager() -{ - return m_pBackgroundTaskManager.get(); -} - -IBackgroundScheduleManager* CEditorImpl::GetBackgroundScheduleManager() -{ - return m_pBackgroundScheduleManager.get(); -} - IEditorFileMonitor* CEditorImpl::GetFileMonitor() { return m_pEditorFileMonitor.get(); diff --git a/Code/Sandbox/Editor/IEditorImpl.h b/Code/Sandbox/Editor/IEditorImpl.h index 7ad97d79e5..0ebd02b5fd 100644 --- a/Code/Sandbox/Editor/IEditorImpl.h +++ b/Code/Sandbox/Editor/IEditorImpl.h @@ -43,15 +43,12 @@ class CGameEngine; class CExportManager; class CErrorsDlg; class CIconManager; -class CBackgroundTaskManager; class CTrackViewSequenceManager; class CEditorFileMonitor; class AzAssetWindow; class AzAssetBrowserRequestHandler; class AssetEditorRequestsHandler; class CAlembicCompiler; -struct IBackgroundTaskManager; -struct IBackgroundScheduleManager; struct IEditorFileMonitor; class CVegetationMap; @@ -61,16 +58,6 @@ namespace Editor class EditorQtApplication; } -namespace BackgroundScheduleManager -{ - class CScheduleManager; -} - -namespace BackgroundTaskManager -{ - class CTaskManager; -} - namespace WinWidget { class WinWidgetManager; @@ -179,8 +166,6 @@ public: IDataBaseManager* GetDBItemManager(EDataBaseItemType itemType); CMusicManager* GetMusicManager() { return m_pMusicManager; }; - IBackgroundTaskManager* GetBackgroundTaskManager() override; - IBackgroundScheduleManager* GetBackgroundScheduleManager() override; IEditorFileMonitor* GetFileMonitor() override; void RegisterEventLoopHook(IEventLoopHook* pHook) override; void UnregisterEventLoopHook(IEventLoopHook* pHook) override; @@ -394,8 +379,6 @@ protected: //! Export manager for exporting objects and a terrain from the game to DCC tools CExportManager* m_pExportManager; - std::unique_ptr m_pBackgroundTaskManager; - std::unique_ptr m_pBackgroundScheduleManager; std::unique_ptr m_pEditorFileMonitor; std::unique_ptr m_pResourceSelectorHost; QString m_selectFileBuffer; diff --git a/Code/Sandbox/Editor/Include/IBackgroundScheduleManager.h b/Code/Sandbox/Editor/Include/IBackgroundScheduleManager.h deleted file mode 100644 index bfa9eb6333..0000000000 --- a/Code/Sandbox/Editor/Include/IBackgroundScheduleManager.h +++ /dev/null @@ -1,207 +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. - -// -// IBackgroundScheduleManager manages schedule of group of larger operations that should be run in sequence -// -// Schedules are derived from IBackgroundSchedule and consist of a list of IBackgroundScheduleItems. -// Each schedule item is executed IN ORDER for the previous item to complete first. -// Each IBackgroundScheduleItems consists of list of user defined work via IBackgroundScheduleItemsWork classes. -// Each schedule item work is executed IN PARALEL (they are all started when the item starts). -// -// Whenever a work item fails to complete the other work items are stopped, the schedule item is marked as "failed" -// and so is the whole schedule. -// -// All logic is performed on the main thread although schedule items are free to use threads. -// It is recommended to use IBackgroundTaskManager for dispatching a task list for every schedule work item. -// -// All objects in the schedule system are reference counted. -// - -// State of the whole schedule - -#ifndef CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDSCHEDULEMANAGER_H -#define CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDSCHEDULEMANAGER_H -#pragma once -enum EScheduleState -{ - // Item has not started yet but is on the list - eScheduleState_Pending, - - // We are processing this item - eScheduleState_Processing, - - // We are stopping the schedule - eSccheduleState_Stopping, - - // Schedule item has failed - eScheduleState_Failed, - - // Schedule item was canceled - eScheduleState_Canceled, - - // Schedule item has completed it's work - eScheduleState_Completed, -}; - -// State of the single schedule item -enum EScheduleItemState -{ - // Item has not started yet but is on the list - eScheduleItemState_Pending, - - // We are processing this item - eScheduleItemState_Processing, - - // We are stopping this item - eScheduleItemState_Stopping, - - // Schedule item has failed - eScheduleItemState_Failed, - - // Schedule item has completed it's work - eScheduleItemState_Completed, -}; - -// Work item status -enum EScheduleWorkItemStatus -{ - // Work is still not finished - eScheduleWorkItemStatus_NotFinished, - - // Work has failed - eScheduleWorkItemStatus_Failed, - - // Work has finished - eScheduleWorkItemStatus_Finished, -}; - -struct IBackgroundScheduleItemWork -{ - // Get human readable description - virtual const char* GetDescription() const = 0; - - // Get work item progress - virtual float GetProgress() const = 0; - - // Called when the schedule item containing this work piece has started - // If the work cannot be started for any reason return false. - virtual bool OnStart() = 0; - - // Called when the schedule item containing this work piece has been canceled or failed externally - // Not called when schedule item completed without errors. - // If the work cannot be stopped this frame return false. - virtual bool OnStop() = 0; - - // Called every frame to advance and check the work state - // Should return one of the EBackgroundScheduleWorkItemStatus value - virtual EScheduleWorkItemStatus OnUpdate() = 0; - - // Reference counting - virtual void AddRef() = 0; - virtual void Release() = 0; - -protected: - virtual ~IBackgroundScheduleItemWork() {}; -}; - -struct IBackgroundScheduleItem -{ - // Get name of the schedule (debug & display) - virtual const char* GetDescription() const = 0; - - // Get interal state - virtual EScheduleItemState GetState() const = 0; - - // Get overall progress of this schedule item - virtual const float GetProgress() const = 0; - - // Get number of work items in this schedule item - virtual const uint32 GetNumWorkItems() const = 0; - - // Get n-th work item from the schedule item - virtual IBackgroundScheduleItemWork* GetWorkItem(const uint32 index) const = 0; - - // Add work item to the schedule item - virtual void AddWorkItem(IBackgroundScheduleItemWork* pWork) = 0; - - // Reference counting - virtual void AddRef() = 0; - virtual void Release() = 0; - -protected: - virtual ~IBackgroundScheduleItem() {}; -}; - -struct IBackgroundSchedule -{ - // Get name of the schedule (debug & display) - virtual const char* GetDescription() const = 0; - - // Get overall progress of the whole schedule - virtual float GetProgress() const = 0; - - // Get item being currently processed - virtual IBackgroundScheduleItem* GetProcessedItem() const = 0; - - // Get number of items in the schedule - virtual const uint32 GetNumItems() const = 0; - - // Get single schedule item - virtual IBackgroundScheduleItem* GetItem(const uint32 index) const = 0; - - // Get schedule item - virtual EScheduleState GetState() const = 0; - - // Cancel the whole schedule - virtual void Cancel() = 0; - - // Is the schedule canceled ? - virtual bool IsCanceled() const = 0; - - // Add schedule item at the end of the list - virtual void AddItem(IBackgroundScheduleItem* pItem) = 0; - - // Reference counting - virtual void AddRef() = 0; - virtual void Release() = 0; - -protected: - virtual ~IBackgroundSchedule() {}; -}; - -struct IBackgroundScheduleManager -{ - virtual ~IBackgroundScheduleManager() {}; - - // Create empty schedule - virtual IBackgroundSchedule* CreateSchedule(const char* szName) = 0; - - // Create empty schedule item - virtual IBackgroundScheduleItem* CreateScheduleItem(const char* szName) = 0; - - // Issue a schedule to the list (will start processing it) - virtual void SubmitSchedule(IBackgroundSchedule* pSchedule) = 0; - - // Get number of schedules on the list - virtual const uint32 GetNumSchedules() const = 0; - - // Get n-th schedule - virtual IBackgroundSchedule* GetSchedule(const uint32 index) const = 0; - - // Advance work on the schedules - virtual void Update() = 0; -}; - - -#endif // CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDSCHEDULEMANAGER_H diff --git a/Code/Sandbox/Editor/Include/IBackgroundTaskManager.h b/Code/Sandbox/Editor/Include/IBackgroundTaskManager.h deleted file mode 100644 index b586e3022f..0000000000 --- a/Code/Sandbox/Editor/Include/IBackgroundTaskManager.h +++ /dev/null @@ -1,230 +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. - -// -// IBackgroundTaskManager runs background tasks in worker thread. -// -// Tasks are derived from IBackgroundTask. Each task is split in two parts for: -// Work - done in background thread. -// Finalize - called afterward in main thread to apply results. -// -// Task objects are reference counted. Task manager will hold its own reference to the task object -// for as long as the task is pending or being executed. If you want to keep the task object around -// in your code you will have to call AddRef() and Release() on the task object by yourself so there -// will be an extra reference to the task object held by your code. -// -// Work returns the state of the task. Task can be resumed, then the Work -// method will be called again. Other tasks can work between calls to Work. -// It is possible to Cancel task. Work method is not invoked any more for -// Canceled tasks. -// - -#ifndef CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDTASKMANAGER_H -#define CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDTASKMANAGER_H -#pragma once - -enum ETaskPriority -{ - eTaskPriority_FileUpdateFinal, - eTaskPriority_BackgroundScan, - eTaskPriority_FileUpdate, - eTaskPriority_RealtimePreview -}; - -// Result code returned by task Work() function -enum ETaskResult -{ - // Task has not yet completed, add it back to the task queue with the same parameters (priority and thread mask) - eTaskResult_Resume, - - // Task has completed without errors (it's assumed that the result the task was supposed to achieve was achieved) - eTaskResult_Completed, - - // Task was canceled - eTaskResult_Canceled, - - // Task has failed to complete it's work - eTaskResult_Failed, -}; - -// Internal task tracking state -enum ETaskState -{ - // Task was just created. - eTaskState_Created, - - // Task was scheduled to be executed in the future. - eTaskState_Scheduled, - - // Task was added to the task queue and is waiting for it's time to be executed. - eTaskState_Pending, - - // Task is being processed right now. - eTaskState_Working, - - // Task was canceled before it has finished (indication that TaskManager has seen the Cancel() call). - eTaskState_Canceled, - - // Task Work() function was called but it ended with an error code. - eTaskState_Failed, - - // Task has completed it's Work() function without errors. - eTaskState_Completed, -}; - -// Thread mask controls which on which threads given task can be executed. -enum ETaskThreadMask -{ - // Task can run only on the IO thread (default) - // There is only one IO thread so all task with this flag are run in a sequence. - eTaskThreadMask_IO, - - // Task can run on any thread (concurrent tasks allowed) - // There can be many threads with this mask so there's no limit on the concurrent task count. - eTaskThreadMask_Any, - - eTaskThreadMask_COUNT, -}; - -struct IBackgroundTask -{ -public: - IBackgroundTask() - : m_bCanceled(false) - , m_state(eTaskState_Created) - , m_progress(-1.0f) - , m_refCount(0) - , m_bFailReported(false) - {} - - void Cancel() - { - m_bCanceled = true; - } - - bool IsCanceled() const - { - return m_bCanceled; - } - - bool HasFinished() const - { - return (m_state == eTaskState_Canceled) || - (m_state == eTaskState_Completed) || - (m_state == eTaskState_Failed); - } - - bool HasFinishedWithoutError() const - { - return (m_state == eTaskState_Completed); - } - - ETaskState GetState() const - { - return m_state; - } - - void SetState(ETaskState state) - { - m_state = state; - } - - float GetProgress() const - { - return m_progress; - } - - int AddRef() - { - return CryInterlockedIncrement(&m_refCount); - } - - int Release() - { - const int nCount = CryInterlockedDecrement(&m_refCount); - assert(nCount >= 0); - if (nCount == 0) - { - Delete(); - } - else if (nCount < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } - return nCount; - } - - bool FailReported() const{ return m_bFailReported; } - - // Get the user readable description (name) of this task, used for logging - virtual const char* Description() const { return ""; } - - // Get the user readable error message (in case when the task fails), used for logging the errors - virtual const char* ErrorMessage() const { return ""; } - - // Called from main thread after task is completed just before the task gets destroyed - virtual void Finalize() {} - - // Since there's a possibility that task object were created using different allocator - // we need a way to delete the task object once we are done with it - virtual void Delete() = 0; - - // Invoked from worker thread, actual work is done here - virtual ETaskResult Work() = 0; - -protected: - void SetProgress(float progress) { m_progress = progress; } - void SetFailReported() { m_bFailReported = true; } - - // destructor is hidden to indicate that we should use Release() method - virtual ~IBackgroundTask() {} - -private: - volatile int m_refCount; - ETaskState m_state; - float m_progress; - bool m_bCanceled; - bool m_bFailReported; -}; - -struct IBackgroundTaskManagerListener -{ - virtual ~IBackgroundTaskManagerListener() {} - - virtual void OnBackgroundTaskAdded(const char* description) = 0; - virtual void OnBackgroundTaskCompleted(ETaskResult taskResult, const char* description) = 0; -}; - -struct IBackgroundTaskManager -{ - enum - { - BACKGROUND_TASK_ID_INVALID = 0 - }; - - virtual ~IBackgroundTaskManager() {} - - // Add task to the queue with given priority and thread mask - virtual void AddTask(IBackgroundTask* pTask, ETaskPriority priority, ETaskThreadMask threadMask) = 0; - - // Schedule task to be executed in the future - virtual void ScheduleTask(IBackgroundTask* pTask, ETaskPriority priority, int delayMilliseconds, ETaskThreadMask threadMask) = 0; - - virtual void AddListener(IBackgroundTaskManagerListener* pListener, const char* name) = 0; - - virtual void RemoveListener(IBackgroundTaskManagerListener* pListener) = 0; -}; - - -#endif // CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDTASKMANAGER_H diff --git a/Code/Sandbox/Editor/LevelInfo.cpp b/Code/Sandbox/Editor/LevelInfo.cpp index 81441a3797..55c432094a 100644 --- a/Code/Sandbox/Editor/LevelInfo.cpp +++ b/Code/Sandbox/Editor/LevelInfo.cpp @@ -97,10 +97,6 @@ void CLevelInfo::ValidateObjects() pObject->Validate(m_pReport); - CUsedResources rs; - pObject->GatherUsedResources(rs); - rs.Validate(m_pReport); - m_pReport->SetCurrentValidatorObject(NULL); } diff --git a/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h b/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h index 38a35e6684..949bc72e03 100644 --- a/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h +++ b/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h @@ -102,7 +102,6 @@ public: MOCK_METHOD0(GetViewManager, class CViewManager* ()); MOCK_METHOD0(GetActiveView, class CViewport* ()); MOCK_METHOD1(SetActiveView, void(CViewport*)); - MOCK_METHOD0(GetBackgroundTaskManager, struct IBackgroundTaskManager* ()); MOCK_METHOD0(GetFileMonitor, struct IEditorFileMonitor* ()); MOCK_METHOD1(RegisterEventLoopHook, void(IEventLoopHook* )); MOCK_METHOD1(UnregisterEventLoopHook, void(IEventLoopHook* )); @@ -184,7 +183,6 @@ public: MOCK_CONST_METHOD0(GetEditorConfigPlatform, ESystemConfigPlatform()); MOCK_METHOD0(ReloadTemplates, void()); MOCK_METHOD0(GetResourceSelectorHost, IResourceSelectorHost* ()); - MOCK_METHOD0(GetBackgroundScheduleManager, struct IBackgroundScheduleManager* ()); MOCK_METHOD1(ShowStatusText, void(bool )); MOCK_METHOD1(RegisterObjectContextMenuExtension, void(TContextMenuExtensionFunc )); MOCK_METHOD0(GetEnv, SSystemGlobalEnvironment* ()); diff --git a/Code/Sandbox/Editor/MainStatusBarItems.h b/Code/Sandbox/Editor/MainStatusBarItems.h index 3f43f1818f..095183363f 100644 --- a/Code/Sandbox/Editor/MainStatusBarItems.h +++ b/Code/Sandbox/Editor/MainStatusBarItems.h @@ -13,7 +13,6 @@ #pragma once #include -#include #include #include #include diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index e9b27ee9b8..6f6b600a84 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -92,7 +92,6 @@ AZ_POP_DISABLE_WARNING #include "ErrorReportDialog.h" #include "Dialogs/PythonScriptsDialog.h" -#include "EngineSettingsManager.h" #include "AzAssetBrowser/AzAssetBrowserWindow.h" #include "AssetEditor/AssetEditorWindow.h" @@ -1941,12 +1940,6 @@ void MainWindow::ConnectivityStateChanged(const AzToolsFramework::SourceControlS } } -#if defined(CRY_ENABLE_RC_HELPER) - CEngineSettingsManager settingsManager; - settingsManager.SetModuleSpecificBoolEntry("RC_EnableSourceControl", connected); - settingsManager.StoreData(); -#endif - gSettings.enableSourceControl = connected; gSettings.SaveEnableSourceControlFlag(false); } diff --git a/Code/Sandbox/Editor/Objects/EntityObject.h b/Code/Sandbox/Editor/Objects/EntityObject.h index 85368f7804..b367384f08 100644 --- a/Code/Sandbox/Editor/Objects/EntityObject.h +++ b/Code/Sandbox/Editor/Objects/EntityObject.h @@ -35,7 +35,6 @@ class CEntityObject; class QMenu; -class IOpticsElementBase; /*! * CEntityEventTarget is an Entity event target and type. diff --git a/Code/Sandbox/Editor/UsedResources.cpp b/Code/Sandbox/Editor/UsedResources.cpp index 35384b0f34..013d35d4a7 100644 --- a/Code/Sandbox/Editor/UsedResources.cpp +++ b/Code/Sandbox/Editor/UsedResources.cpp @@ -27,38 +27,3 @@ void CUsedResources::Add(const char* pResourceFileName) files.insert(pResourceFileName); } } - -void CUsedResources::Validate(IErrorReport* pReport) -{ - auto pPak = gEnv->pCryPak; - - for (TResourceFiles::iterator it = files.begin(); it != files.end(); ++it) - { - const QString& filename = *it; - - bool fileExists = pPak->IsFileExist(filename.toUtf8().data()); - - if (!fileExists) - { - for (int i = 0; !fileExists && i < IResourceCompilerHelper::GetNumEngineImageFormats(); ++i) - { - fileExists = gEnv->pCryPak->IsFileExist(PathUtil::ReplaceExtension(filename.toUtf8().data(), IResourceCompilerHelper::GetEngineImageFormat(i, true)).c_str()); - } - for (int i = 0; !fileExists && i < IResourceCompilerHelper::GetNumSourceImageFormats(); ++i) - { - fileExists = gEnv->pCryPak->IsFileExist(PathUtil::ReplaceExtension(filename.toUtf8().data(), IResourceCompilerHelper::GetSourceImageFormat(i, true)).c_str()); - } - } - - - if (!fileExists) - { - CErrorRecord err; - - err.error = QObject::tr("Resource File %1 not found,").arg(filename); - err.severity = CErrorRecord::ESEVERITY_ERROR; - err.flags |= CErrorRecord::FLAG_NOFILE; - pReport->ReportError(err); - } - } -} diff --git a/Code/Sandbox/Editor/UsedResources.h b/Code/Sandbox/Editor/UsedResources.h index e22c672d30..acf8b79783 100644 --- a/Code/Sandbox/Editor/UsedResources.h +++ b/Code/Sandbox/Editor/UsedResources.h @@ -36,8 +36,6 @@ public: CUsedResources(); void Add(const char* pResourceFileName); - //! validate gathered resources, reports warning if resource is not found - void Validate(struct IErrorReport* pReport); AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING TResourceFiles files; diff --git a/Code/Sandbox/Editor/editor_lib_files.cmake b/Code/Sandbox/Editor/editor_lib_files.cmake index 3d6112d186..401b7c6e39 100644 --- a/Code/Sandbox/Editor/editor_lib_files.cmake +++ b/Code/Sandbox/Editor/editor_lib_files.cmake @@ -280,8 +280,6 @@ set(FILES Include/IAnimationCompressionManager.h Include/IAssetItem.h Include/IAssetItemDatabase.h - Include/IBackgroundScheduleManager.h - Include/IBackgroundTaskManager.h Include/ICommandManager.h Include/IConsoleConnectivity.h Include/IDataBaseItem.h @@ -343,10 +341,6 @@ set(FILES AssetEditor/AssetEditorWindow.cpp AssetEditor/AssetEditorWindow.h AssetEditor/AssetEditorWindow.ui - BackgroundTaskManager.cpp - BackgroundScheduleManager.cpp - BackgroundTaskManager.h - BackgroundScheduleManager.h Commands/CommandManager.cpp Commands/CommandManager.h Controls/BitmapToolTip.cpp diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index 33d4b5baf4..f38b295128 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -160,7 +160,6 @@ void SandboxIntegrationManager::Setup() AzToolsFramework::SliceEditorEntityOwnershipServiceNotificationBus::Handler::BusConnect(); AzFramework::DisplayContextRequestBus::Handler::BusConnect(); - SetupFileExtensionMap(); MainWindow::instance()->GetActionManager()->RegisterActionHandler(ID_FILE_SAVE_SLICE_TO_ROOT, [this]() { SaveSlice(false); @@ -1926,30 +1925,6 @@ void SandboxIntegrationManager::MakeSliceFromEntities(const AzToolsFramework::En AzToolsFramework::SliceUtilities::MakeNewSlice(entitiesAndDescendants, path, inheritSlices, setAsDynamic); } -void SandboxIntegrationManager::SetupFileExtensionMap() -{ - // There's no central registry for geometry file types. - const char* geometryFileExtensions[] = - { - CRY_GEOMETRY_FILE_EXT, // .cgf - CRY_SKEL_FILE_EXT, // .chr - CRY_CHARACTER_DEFINITION_FILE_EXT, // .cdf - }; - - // Cry geometry file extensions. - for (const char* extension : geometryFileExtensions) - { - m_extensionToFileType[AZ::Crc32(extension)] = IFileUtil::EFILE_TYPE_GEOMETRY; - } - - // Cry image file extensions. - for (size_t i = 0; i < IResourceCompilerHelper::GetNumSourceImageFormats(); ++i) - { - const char* extension = IResourceCompilerHelper::GetSourceImageFormat(i, false); - m_extensionToFileType[AZ::Crc32(extension)] = IFileUtil::EFILE_TYPE_TEXTURE; - } -} - void SandboxIntegrationManager::RegisterViewPane(const char* name, const char* category, const AzToolsFramework::ViewPaneOptions& viewOptions, const WidgetCreationFunc& widgetCreationFunc) { QtViewPaneManager::instance()->RegisterPane(name, category, widgetCreationFunc, viewOptions); diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h index b3c60bca45..14f52591a4 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h @@ -319,12 +319,10 @@ private: void OnLayerComponentDeactivated(AZ::EntityId entityId) override; private: - void SetupFileExtensionMap(); // Right click context menu when a layer is included in the selection. void SetupLayerContextMenu(QMenu* menu); void SetupSliceContextMenu(QMenu* menu); void SetupSliceContextMenu_Modify(QMenu* menu, const AzToolsFramework::EntityIdList& selectedEntities, const AZ::u32 numEntitiesInSlices); - void SetupScriptCanvasContextMenu(QMenu* menu); void SaveSlice(const bool& QuickPushToFirstLevel); void GetEntitiesInSlices(const AzToolsFramework::EntityIdList& selectedEntities, AZ::u32& entitiesInSlices, AZStd::vector& sliceInstances); @@ -348,9 +346,6 @@ private: }; private: - typedef AZStd::unordered_map ExtensionMap; - ExtensionMap m_extensionToFileType; - AZ::Vector2 m_contextMenuViewPoint; AZ::Vector3 m_sliceWorldPos; diff --git a/Code/Sandbox/Plugins/MaglevControlPanel/CloudCanvasPythonWorkerInterface.h b/Code/Sandbox/Plugins/MaglevControlPanel/CloudCanvasPythonWorkerInterface.h deleted file mode 100644 index 1d557e35f7..0000000000 --- a/Code/Sandbox/Plugins/MaglevControlPanel/CloudCanvasPythonWorkerInterface.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. -* -*/ - -#pragma once - -#include - -#include - -using PythonWorkerRequestId = int; - -//! Interface to signal the python worker output -class PythonWorkerEventsInterface -{ -protected: - PythonWorkerEventsInterface() = default; - virtual ~PythonWorkerEventsInterface() = default; - PythonWorkerEventsInterface(PythonWorkerEventsInterface&&) = delete; - PythonWorkerEventsInterface& operator=(PythonWorkerEventsInterface&&) = delete; - -public: - AZ_RTTI(PythonWorkerEventsInterface, "{60C83A5A-B8DD-4B98-B8C6-DC2F5914D7C4}"); - - // if any OnOutput returns true, it means the command was handled and the worker won't process any further - virtual bool OnPythonWorkerOutput(PythonWorkerRequestId requestId, const QString& key, const QVariant& value) = 0; -}; - -//! Interface to send the python worker requests -class PythonWorkerRequestsInterface -{ -protected: - PythonWorkerRequestsInterface() = default; - virtual ~PythonWorkerRequestsInterface() = default; - PythonWorkerRequestsInterface(PythonWorkerRequestsInterface&&) = delete; - PythonWorkerRequestsInterface& operator=(PythonWorkerRequestsInterface&&) = delete; - -public: - AZ_RTTI(PythonWorkerRequestsInterface, "{B0293028-3575-408E-8CE3-D1B7F3C59A6C}"); - - virtual PythonWorkerRequestId AllocateRequestId() = 0; - virtual void ExecuteAsync(PythonWorkerRequestId requestId, const char* command, const QVariantMap& args = QVariantMap{}) = 0; - virtual bool IsStarted() = 0; -}; - diff --git a/Code/Sandbox/Plugins/MaglevControlPanel/MaglevControlPanelPlugin_stub.cpp b/Code/Sandbox/Plugins/MaglevControlPanel/MaglevControlPanelPlugin_stub.cpp deleted file mode 100644 index 1508e9f7b0..0000000000 --- a/Code/Sandbox/Plugins/MaglevControlPanel/MaglevControlPanelPlugin_stub.cpp +++ /dev/null @@ -1,31 +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 "stdafx.h" -#include -#include - -const char* TAG = "MaglevControlPanelPlugin"; - -MaglevControlPanelPlugin::MaglevControlPanelPlugin(IEditor* editor) - : m_pluginSettings(QSettings::IniFormat, QSettings::UserScope, "Amazon", "Lumberyard") -{ - -} - -void MaglevControlPanelPlugin::Release() -{ -} - -void MaglevControlPanelPlugin::OnEditorNotify(EEditorNotifyEvent aEventId) -{ -} - diff --git a/Code/Tools/CryCommonTools/Export/AnimationData.cpp b/Code/Tools/CryCommonTools/Export/AnimationData.cpp deleted file mode 100644 index 2b2c5966a6..0000000000 --- a/Code/Tools/CryCommonTools/Export/AnimationData.cpp +++ /dev/null @@ -1,297 +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 "StdAfx.h" -#include "AnimationData.h" - -AnimationData::AnimationData(int modelCount, float fps, float startTime) - : m_entries(modelCount) - , m_frameCount(0) - , m_startTime(startTime) - , m_fps(fps) -{ -} - -void AnimationData::SetFrameData(int modelIndex, int frameIndex, float translation[3], float rotation[3], float scale[3]) -{ - State& state = m_entries[modelIndex].samples[frameIndex]; - state.translation[0] = translation[0]; - state.translation[1] = translation[1]; - state.translation[2] = translation[2]; - state.rotation[0] = rotation[0]; - state.rotation[1] = rotation[1]; - state.rotation[2] = rotation[2]; - state.scale[0] = scale[0]; - state.scale[1] = scale[1]; - state.scale[2] = scale[2]; -} - -void AnimationData::SetFrameCount(int frameCount) -{ - m_frameCount = frameCount; - for (int modelIndex = 0, modelCount = int(m_entries.size()); modelIndex < modelCount; ++modelIndex) - { - m_entries[modelIndex].samples.resize(frameCount); - } -} - -void AnimationData::SetModelFlags(int modelIndex, unsigned modelFlags) -{ - m_entries[modelIndex].flags = modelFlags; -} - -void AnimationData::GetFrameData(int modelIndex, int frameIndex, const float*& translation, const float*& rotation, const float*& scale) const -{ - translation = m_entries[modelIndex].samples[frameIndex].translation; - rotation = m_entries[modelIndex].samples[frameIndex].rotation; - scale = m_entries[modelIndex].samples[frameIndex].scale; -} - -void AnimationData::GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const -{ - translation = m_entries[modelIndex].samples[frameIndex].translation; -} - -void AnimationData::GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const -{ - rotation = m_entries[modelIndex].samples[frameIndex].rotation; -} - -void AnimationData::GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const -{ - scale = m_entries[modelIndex].samples[frameIndex].scale; -} - -int AnimationData::GetFrameCount() const -{ - return m_frameCount; -} - -unsigned AnimationData::GetModelFlags(int modelIndex) const -{ - return m_entries[modelIndex].flags; -} - -AnimationData::State::State() -{ - translation[0] = translation[1] = translation[2] = 0.0f; - rotation[0] = rotation[1] = rotation[2] = 0.0f; - scale[0] = scale[1] = scale[2] = 1.0f; -} - -AnimationData::ModelEntry::ModelEntry() - : flags(0) -{ -} - -/////////////////////////////////////////////////////////////////////////// -NonSkeletalAnimationData::NonSkeletalAnimationData(int modelCount) - : m_entries(modelCount) -{ -} - -void NonSkeletalAnimationData::SetModelFlags(int modelIndex, unsigned modelFlags) -{ - m_entries[modelIndex].flags = modelFlags; -} - -unsigned NonSkeletalAnimationData::GetModelFlags(int modelIndex) const -{ - return m_entries[modelIndex].flags; -} - -void NonSkeletalAnimationData::SetFrameTimePos(int modelIndex, int frameIndex, float time) -{ - State& state = m_entries[modelIndex].samplesPos[frameIndex]; - state.time = time; -} - -void NonSkeletalAnimationData::SetFrameDataPos(int modelIndex, int frameIndex, float translation[3]) -{ - State& state = m_entries[modelIndex].samplesPos[frameIndex]; - state.data[0] = translation[0]; - state.data[1] = translation[1]; - state.data[2] = translation[2]; -} - -void NonSkeletalAnimationData::SetFrameCountPos(int modelIndex, int frameCount) -{ - m_entries[modelIndex].samplesPos.resize(frameCount); -} - -void NonSkeletalAnimationData::SetFrameTimeRot(int modelIndex, int frameIndex, float time) -{ - State& state = m_entries[modelIndex].samplesRot[frameIndex]; - state.time = time; -} - -void NonSkeletalAnimationData::SetFrameDataRot(int modelIndex, int frameIndex, float rotation[3]) -{ - State& state = m_entries[modelIndex].samplesRot[frameIndex]; - state.data[0] = rotation[0]; - state.data[1] = rotation[1]; - state.data[2] = rotation[2]; -} - -void NonSkeletalAnimationData::SetFrameCountRot(int modelIndex, int frameCount) -{ - m_entries[modelIndex].samplesRot.resize(frameCount); -} - -void NonSkeletalAnimationData::SetFrameTimeScl(int modelIndex, int frameIndex, float time) -{ - State& state = m_entries[modelIndex].samplesScl[frameIndex]; - state.time = time; -} - -void NonSkeletalAnimationData::SetFrameDataScl(int modelIndex, int frameIndex, float scale[3]) -{ - State& state = m_entries[modelIndex].samplesScl[frameIndex]; - state.data[0] = scale[0]; - state.data[1] = scale[1]; - state.data[2] = scale[2]; -} - -void NonSkeletalAnimationData::SetFrameCountScl(int modelIndex, int frameCount) -{ - m_entries[modelIndex].samplesScl.resize(frameCount); -} - -float NonSkeletalAnimationData::GetFrameTimePos(int modelIndex, int frameIndex) const -{ - return m_entries[modelIndex].samplesPos[frameIndex].time; -} - -void NonSkeletalAnimationData::GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const -{ - translation = m_entries[modelIndex].samplesPos[frameIndex].data; -} - -int NonSkeletalAnimationData::GetFrameCountPos(int modelIndex) const -{ - return int(m_entries[modelIndex].samplesPos.size()); -} - -float NonSkeletalAnimationData::GetFrameTimeRot(int modelIndex, int frameIndex) const -{ - return m_entries[modelIndex].samplesRot[frameIndex].time; -} - -void NonSkeletalAnimationData::GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const -{ - rotation = m_entries[modelIndex].samplesRot[frameIndex].data; -} - -int NonSkeletalAnimationData::GetFrameCountRot(int modelIndex) const -{ - return int(m_entries[modelIndex].samplesRot.size()); -} - -float NonSkeletalAnimationData::GetFrameTimeScl(int modelIndex, int frameIndex) const -{ - return m_entries[modelIndex].samplesScl[frameIndex].time; -} - -void NonSkeletalAnimationData::GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const -{ - scale = m_entries[modelIndex].samplesScl[frameIndex].data; -} - -int NonSkeletalAnimationData::GetFrameCountScl(int modelIndex) const -{ - return int(m_entries[modelIndex].samplesScl.size()); -} - -void NonSkeletalAnimationData::SetFrameTCBPos(int modelIndex, int frameIndex, IAnimationData::TCB tcb) -{ - State& state = m_entries[modelIndex].samplesPos[frameIndex]; - state.tcb = tcb; -} - -void NonSkeletalAnimationData::SetFrameTCBRot(int modelIndex, int frameIndex, IAnimationData::TCB tcb) -{ - State& state = m_entries[modelIndex].samplesRot[frameIndex]; - state.tcb = tcb; -} - -void NonSkeletalAnimationData::SetFrameTCBScl(int modelIndex, int frameIndex, IAnimationData::TCB tcb) -{ - State& state = m_entries[modelIndex].samplesScl[frameIndex]; - state.tcb = tcb; -} - -void NonSkeletalAnimationData::SetFrameEaseInOutPos(int modelIndex, int frameIndex, IAnimationData::Ease ease) -{ - State& state = m_entries[modelIndex].samplesPos[frameIndex]; - state.ease = ease; -} - -void NonSkeletalAnimationData::SetFrameEaseInOutRot(int modelIndex, int frameIndex, IAnimationData::Ease ease) -{ - State& state = m_entries[modelIndex].samplesRot[frameIndex]; - state.ease = ease; -} - -void NonSkeletalAnimationData::SetFrameEaseInOutScl(int modelIndex, int frameIndex, IAnimationData::Ease ease) -{ - State& state = m_entries[modelIndex].samplesScl[frameIndex]; - state.ease = ease; -} - -void NonSkeletalAnimationData::GetFrameTCBPos(int modelIndex, int frameIndex, IAnimationData::TCB& tcb) const -{ - const State& state = m_entries[modelIndex].samplesPos[frameIndex]; - tcb = state.tcb; -} - -void NonSkeletalAnimationData::GetFrameTCBRot(int modelIndex, int frameIndex, IAnimationData::TCB& tcb) const -{ - const State& state = m_entries[modelIndex].samplesRot[frameIndex]; - tcb = state.tcb; -} - -void NonSkeletalAnimationData::GetFrameTCBScl(int modelIndex, int frameIndex, IAnimationData::TCB& tcb) const -{ - const State& state = m_entries[modelIndex].samplesScl[frameIndex]; - tcb = state.tcb; -} - -void NonSkeletalAnimationData::GetFrameEaseInOutPos(int modelIndex, int frameIndex, IAnimationData::Ease& ease) const -{ - const State& state = m_entries[modelIndex].samplesPos[frameIndex]; - ease = state.ease; -} - -void NonSkeletalAnimationData::GetFrameEaseInOutRot(int modelIndex, int frameIndex, IAnimationData::Ease& ease) const -{ - const State& state = m_entries[modelIndex].samplesRot[frameIndex]; - ease = state.ease; -} - -void NonSkeletalAnimationData::GetFrameEaseInOutScl(int modelIndex, int frameIndex, IAnimationData::Ease& ease) const -{ - const State& state = m_entries[modelIndex].samplesScl[frameIndex]; - ease = state.ease; -} - - -NonSkeletalAnimationData::State::State() -{ - time = 0.0f; - data[0] = data[1] = data[2] = 0.0f; -} - -NonSkeletalAnimationData::ModelEntry::ModelEntry() - : flags(0) -{ -} diff --git a/Code/Tools/CryCommonTools/Export/AnimationData.h b/Code/Tools/CryCommonTools/Export/AnimationData.h deleted file mode 100644 index 65b699e49b..0000000000 --- a/Code/Tools/CryCommonTools/Export/AnimationData.h +++ /dev/null @@ -1,211 +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_CRYCOMMONTOOLS_EXPORT_ANIMATIONDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ANIMATIONDATA_H -#pragma once - - -#include "IAnimationData.h" - -#include - -// Animation data class for skeletal animations -// It has a same count of samples for all models(bones) -// and always has translation/rotation/scaling data together as a set. -class AnimationData - : public IAnimationData -{ -public: - AnimationData(int modelCount, float fps, float startTime); - virtual ~AnimationData() {} - - // IAnimationData - virtual void SetFrameData(int modelIndex, int frameIndex, float translation[3], float rotation[3], float scale[3]); - virtual void SetFrameCount(int frameCount); - virtual void SetModelFlags(int modelIndex, unsigned modelFlags); - - virtual void SetFrameTimePos(int modelIndex, int frameIndex, float time) - { assert(0); } - virtual void SetFrameDataPos(int modelIndex, int frameIndex, float translation[3]) - { assert(0); } - virtual void SetFrameCountPos(int modelIndex, int frameCount) - { assert(0); } - virtual void SetFrameTimeRot(int modelIndex, int frameIndex, float time) - { assert(0); } - virtual void SetFrameDataRot(int modelIndex, int frameIndex, float rotation[3]) - { assert(0); } - virtual void SetFrameCountRot(int modelIndex, int frameCount) - { assert(0); } - virtual void SetFrameTimeScl(int modelIndex, int frameIndex, float time) - { assert(0); } - virtual void SetFrameDataScl(int modelIndex, int frameIndex, float scale[3]) - { assert(0); } - virtual void SetFrameCountScl(int modelIndex, int frameCount) - { assert(0); } - - virtual void GetFrameData(int modelIndex, int frameIndex, const float*& translation, const float*& rotation, const float*& scale) const; - virtual int GetFrameCount() const; - virtual unsigned GetModelFlags(int modelIndex) const; - - virtual float GetFrameTimePos(int modelIndex, int frameIndex) const - { return m_startTime + frameIndex / m_fps; } - virtual void GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const; - virtual int GetFrameCountPos(int) const - { return GetFrameCount(); } - virtual float GetFrameTimeRot(int modelIndex, int frameIndex) const - { return m_startTime + frameIndex / m_fps; } - virtual void GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const; - virtual int GetFrameCountRot(int) const - { return GetFrameCount(); } - virtual float GetFrameTimeScl(int modelIndex, int frameIndex) const - { return m_startTime + frameIndex / m_fps; } - virtual void GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const; - virtual int GetFrameCountScl(int) const - { return GetFrameCount(); } - - // TCB & Ease-In/-Out not supported for the skeletal animation. - virtual void SetFrameTCBPos(int modelIndex, int frameIndex, TCB tcb) - { assert(0); } - virtual void SetFrameTCBRot(int modelIndex, int frameIndex, TCB tcb) - { assert(0); } - virtual void SetFrameTCBScl(int modelIndex, int frameIndex, TCB tcb) - { assert(0); } - virtual void SetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease ease) - { assert(0); } - virtual void SetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease ease) - { assert(0); } - virtual void SetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease ease) - { assert(0); } - virtual void GetFrameTCBPos(int modelIndex, int frameIndex, TCB& tcb) const - { assert(0); } - virtual void GetFrameTCBRot(int modelIndex, int frameIndex, TCB& tcb) const - { assert(0); } - virtual void GetFrameTCBScl(int modelIndex, int frameIndex, TCB& tcb) const - { assert(0); } - virtual void GetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease& ease) const - { assert(0); } - virtual void GetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease& ease) const - { assert(0); } - virtual void GetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease& ease) const - { assert(0); } - -private: - struct State - { - public: - State(); - float translation[3]; - float rotation[3]; - float scale[3]; - }; - - struct ModelEntry - { - ModelEntry(); - - unsigned flags; - std::vector samples; - }; - - std::vector m_entries; - int m_frameCount; - float m_startTime; - float m_fps; -}; - -// Animation data class for non-skeletal animations -// It can have different counts of samples for each model -// and each channel of transformation data. -class NonSkeletalAnimationData - : public IAnimationData -{ -public: - NonSkeletalAnimationData(int modelCount); - virtual ~NonSkeletalAnimationData() {} - - // IAnimationData - virtual void SetFrameData(int modelIndex, int frameIndex, float translation[3], float rotation[3], float scale[3]) - { assert(0); } - virtual void SetFrameCount(int frameCount) - { assert(0); } - virtual void SetModelFlags(int modelIndex, unsigned modelFlags); - - virtual void SetFrameTimePos(int modelIndex, int frameIndex, float time); - virtual void SetFrameDataPos(int modelIndex, int frameIndex, float translation[3]); - virtual void SetFrameCountPos(int modelIndex, int frameCount); - virtual void SetFrameTimeRot(int modelIndex, int frameIndex, float time); - virtual void SetFrameDataRot(int modelIndex, int frameIndex, float rotation[3]); - virtual void SetFrameCountRot(int modelIndex, int frameCount); - virtual void SetFrameTimeScl(int modelIndex, int frameIndex, float time); - virtual void SetFrameDataScl(int modelIndex, int frameIndex, float scale[3]); - virtual void SetFrameCountScl(int modelIndex, int frameCount); - - virtual void GetFrameData(int modelIndex, int frameIndex, const float*& translation, const float*& rotation, const float*& scale) const - { assert(0); } - virtual int GetFrameCount() const - { - assert(0); - return 0; - } - virtual unsigned GetModelFlags(int modelIndex) const; - - virtual float GetFrameTimePos(int modelIndex, int frameIndex) const; - virtual void GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const; - virtual int GetFrameCountPos(int) const; - virtual float GetFrameTimeRot(int modelIndex, int frameIndex) const; - virtual void GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const; - virtual int GetFrameCountRot(int) const; - virtual float GetFrameTimeScl(int modelIndex, int frameIndex) const; - virtual void GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const; - virtual int GetFrameCountScl(int) const; - - virtual void SetFrameTCBPos(int modelIndex, int frameIndex, TCB tcb); - virtual void SetFrameTCBRot(int modelIndex, int frameIndex, TCB tcb); - virtual void SetFrameTCBScl(int modelIndex, int frameIndex, TCB tcb); - virtual void SetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease ease); - virtual void SetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease ease); - virtual void SetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease ease); - - virtual void GetFrameTCBPos(int modelIndex, int frameIndex, TCB& tcb) const; - virtual void GetFrameTCBRot(int modelIndex, int frameIndex, TCB& tcb) const; - virtual void GetFrameTCBScl(int modelIndex, int frameIndex, TCB& tcb) const; - virtual void GetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease& ease) const; - virtual void GetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease& ease) const; - virtual void GetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease& ease) const; - -private: - struct State - { - public: - State(); - float time; - float data[3]; - TCB tcb; - Ease ease; - }; - - struct ModelEntry - { - ModelEntry(); - - unsigned flags; - std::vector samplesPos; - std::vector samplesRot; - std::vector samplesScl; - }; - - std::vector m_entries; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ANIMATIONDATA_H diff --git a/Code/Tools/CryCommonTools/Export/CBAHelpers.cpp b/Code/Tools/CryCommonTools/Export/CBAHelpers.cpp deleted file mode 100644 index d724e349be..0000000000 --- a/Code/Tools/CryCommonTools/Export/CBAHelpers.cpp +++ /dev/null @@ -1,57 +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 "StdAfx.h" -#include "CBAHelpers.h" -#include "../PathHelpers.h" -#include "StringHelpers.h" - -static string FindRootContainingFileGoingUpwards(const char* filePath, const char* filePathToLookFor, IPakSystem* pakSystem) -{ - // Here we just search upwards from the current directory, looking for a directory that - // contains a file at the relative path "Animations/Animations.cba". This is designed to - // handle root Game paths that differ from the default "Game". - string rootDirCandidate = PathHelpers::GetDirectory(filePath); - string rootDir; - while (!rootDirCandidate.empty()) - { - string cbaCandidatePath = PathHelpers::Join(rootDirCandidate, filePathToLookFor); - if (PakSystemFile* file = pakSystem->Open(cbaCandidatePath.c_str(), "r")) - { - // File exists, we have found the correct root path. - pakSystem->Close(file); - - rootDir = rootDirCandidate; - break; - } - - string previousCandidate = rootDirCandidate; - rootDirCandidate = PathHelpers::GetDirectory(rootDirCandidate); - if (rootDirCandidate == previousCandidate) - { - break; - } - } - - return (rootDir.empty() ? rootDir : PathHelpers::Join(rootDir, filePathToLookFor)); -} - -string CBAHelpers::FindCBAFileForFile(const char* filePath, IPakSystem* pakSystem) -{ - return FindRootContainingFileGoingUpwards(filePath, "Animations/Animations.cba", pakSystem); -} - -string CBAHelpers::FindSkeletonListForFile(const char* filePath, IPakSystem* pakSystem) -{ - return FindRootContainingFileGoingUpwards(filePath, "Animations/SkeletonList.xml", pakSystem); -} diff --git a/Code/Tools/CryCommonTools/Export/CBAHelpers.h b/Code/Tools/CryCommonTools/Export/CBAHelpers.h deleted file mode 100644 index 48af5c74d2..0000000000 --- a/Code/Tools/CryCommonTools/Export/CBAHelpers.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_CBAHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_CBAHELPERS_H -#pragma once - - -#include "IPakSystem.h" - -namespace CBAHelpers -{ - string FindCBAFileForFile(const char* filePath, IPakSystem* pakSystem); - string FindSkeletonListForFile(const char* filePath, IPakSystem* pakSystem); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_CBAHELPERS_H diff --git a/Code/Tools/CryCommonTools/Export/ColladaExportWriter.cpp b/Code/Tools/CryCommonTools/Export/ColladaExportWriter.cpp deleted file mode 100644 index d0796a4838..0000000000 --- a/Code/Tools/CryCommonTools/Export/ColladaExportWriter.cpp +++ /dev/null @@ -1,556 +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 "StdAfx.h" - -#include "ColladaExportWriter.h" -#include "ColladaWriter.h" -#include "IExportSource.h" -#include "PathHelpers.h" -#include "ResourceCompilerHelper.h" -#include "SettingsManagerHelpers.h" -#include "IExportContext.h" -#include "ProgressRange.h" -#include "XMLWriter.h" -#include "XMLPakFileSink.h" -#include "ISettings.h" -#include "SingleAnimationExportSourceAdapter.h" -#include "GeometryExportSourceAdapter.h" -#include "ModelData.h" -#include "MaterialData.h" -#include "GeometryFileData.h" -#include "FileUtil.h" -#include "CBAHelpers.h" -#include "ModuleHelpers.h" -#include "PropertyHelpers.h" -#include "StringHelpers.h" -#include -#include - -namespace -{ - class ResourceCompilerLogListener - : public IResourceCompilerListener - { - public: - ResourceCompilerLogListener(IExportContext* context) - : m_context(context) - { - } - - virtual void OnRCMessage(IResourceCompilerListener::MessageSeverity severity, const char* text) - { - ILogger::ESeverity outSeverity; - switch (severity) - { - case IResourceCompilerListener::MessageSeverity_Debug: - case IResourceCompilerListener::MessageSeverity_Info: // normal RC text should just be debug - outSeverity = ILogger::eSeverity_Debug; - break; - case IResourceCompilerListener::MessageSeverity_Warning: - outSeverity = ILogger::eSeverity_Warning; - break; - case IResourceCompilerListener::MessageSeverity_Error: - outSeverity = ILogger::eSeverity_Error; - break; - default: - outSeverity = ILogger::eSeverity_Error; - break; - } - - m_context->Log(outSeverity, "%s", text); - } - - private: - IExportContext* m_context; - }; -} - -void ColladaExportWriter::Export(IExportSource* source, IExportContext* context) -{ - // Create an object to report on our progress to the export context. - ProgressRange progressRange(context, &IExportContext::SetProgress); - CResourceCompilerHelper compiler; // we need a real instance of this specific implementation. - - // Log build information. - context->Log(ILogger::eSeverity_Info, "Exporter build created on " __DATE__); - -#ifdef STLPORT - context->Log(ILogger::eSeverity_Info, "Using STLport C++ Standard Library implementation"); -#else //STLPORT - context->Log(ILogger::eSeverity_Info, "Using Microsoft (tm) C++ Standard Library implementation"); -#endif //STLPORT - -#if defined(_DEBUG) - context->Log(ILogger::eSeverity_Info, "******DEBUG BUILD******"); -#else //_DEBUG - context->Log(ILogger::eSeverity_Info, "Release build."); -#endif //_DEBUG - - context->Log(ILogger::eSeverity_Debug, "Bit count == %d.", (sizeof(void*) * 8)); - - std::string exePath = StringHelpers::ConvertString(ModuleHelpers::GetCurrentModulePath(ModuleHelpers::CurrentModuleSpecifier_Executable)); - context->Log(ILogger::eSeverity_Debug, "Application path: %s", exePath.c_str()); - - std::string exporterPath = StringHelpers::ConvertString(ModuleHelpers::GetCurrentModulePath(ModuleHelpers::CurrentModuleSpecifier_Library)); - context->Log(ILogger::eSeverity_Debug, "Exporter path: %s", exporterPath.c_str()); - - bool const bExportCompressed = (GetSetting(context->GetSettings(), "ExportCompressedCOLLADA", 1)) != 0; - context->Log(ILogger::eSeverity_Debug, "ExportCompressedCOLLADA key: %d", (bExportCompressed ? 1 : 0)); - - std::string const exportExtension = bExportCompressed ? ".dae.zip" : ".dae"; - - // Log the start time. - { - char buf[1024]; - std::time_t t = std::time(0); - std::strftime(buf, sizeof(buf) / sizeof(buf[0]), "%H:%M:%S on %a, %d/%m/%Y", std::localtime(&t)); - context->Log(ILogger::eSeverity_Info, "Export begun at %s", buf); - } - - // Select the name of the directory to export to. - std::string const originalExportDirectory = source->GetExportDirectory(); - if (originalExportDirectory.empty()) - { - throw IExportContext::NeedSaveError("Scene must be saved before exporting."); - } - - GeometryFileData geometryFileData; - std::vector colladaGeometryFileNameList; - std::vector assetGeometryFileNameList; - typedef std::vector, std::string> > AnimationFileNameList; - AnimationFileNameList animationFileNameList; - AnimationFileNameList animationCompileFileNameList; - { - CurrentTaskScope currentTask(context, "dae"); - - // Choose the files to which to export all the animations. - std::list animationExportSources; - std::list geometryExportSources; - typedef std::vector > ExportList; - ExportList exportList; - std::vector geometryFileIndices; - { - ProgressRange readProgressRange(progressRange, 0.2f); - - source->ReadGeometryFiles(context, &geometryFileData); - - for (int geometryFileIndex = 0; geometryFileIndex < geometryFileData.GetGeometryFileCount(); ++geometryFileIndex) - { - const std::string geometryFileName = geometryFileData.GetGeometryFileName(geometryFileIndex); - - IGeometryFileData::SProperties properties = geometryFileData.GetProperties(geometryFileIndex); - if (properties.filetypeInt == CRY_FILE_TYPE_CAF) - { - // LDS: This is a temporary fix for some old hacky code that would activate a deprecated compression path during export - // It needs a proper fix by tearing out the old compression code and moving the system to the new i_caf system by default. - // See for http://docs.cryengine.com/display/SDKDOC3/Transition+from+CBA+to+AnimSettings details. - properties.filetypeInt = CRY_FILE_TYPE_INTERMEDIATE_CAF; - geometryFileData.SetProperties(geometryFileIndex, properties); - } - - bool const hasGeometry = (properties.filetypeInt != CRY_FILE_TYPE_CAF && - properties.filetypeInt != CRY_FILE_TYPE_INTERMEDIATE_CAF); - - if (hasGeometry && !geometryFileName.empty()) - { - geometryFileIndices.push_back(geometryFileIndex); - } - } - - if (!geometryFileIndices.empty()) - { - std::string name = PathHelpers::RemoveExtension(PathHelpers::GetFilename(source->GetDCCFileName())); - std::replace(name.begin(), name.end(), ' ', '_'); - std::string const colladaPath = PathHelpers::Join(originalExportDirectory, name + exportExtension); - colladaGeometryFileNameList.push_back(colladaPath); - - geometryExportSources.push_back(GeometryExportSourceAdapter(source, &geometryFileData, geometryFileIndices)); - exportList.push_back(std::make_pair(colladaPath, &geometryExportSources.back())); - } - - for (int geometryFileIndex = 0; geometryFileIndex < geometryFileData.GetGeometryFileCount(); ++geometryFileIndex) - { - std::string const geometryFileName = geometryFileData.GetGeometryFileName(geometryFileIndex); - int const fileTypeInt = geometryFileData.GetProperties(geometryFileIndex).filetypeInt; - std::string customExportPath = geometryFileData.GetProperties(geometryFileIndex).customExportPath; - bool const hasGeometry = (fileTypeInt != CRY_FILE_TYPE_CAF && - fileTypeInt != CRY_FILE_TYPE_INTERMEDIATE_CAF); - - if (hasGeometry && !geometryFileName.empty()) - { - std::string extension = "missingextension"; - if (fileTypeInt == CRY_FILE_TYPE_CGF) - { - extension = "cgf"; - } - else if ((fileTypeInt == CRY_FILE_TYPE_CGA) || (fileTypeInt == (CRY_FILE_TYPE_CGA | CRY_FILE_TYPE_ANM))) - { - extension = "cga"; - } - else if (fileTypeInt == CRY_FILE_TYPE_ANM) - { - extension = "anm"; - } - else if (fileTypeInt == CRY_FILE_TYPE_CHR || - (fileTypeInt == (CRY_FILE_TYPE_CHR | CRY_FILE_TYPE_CAF)) || - (fileTypeInt == (CRY_FILE_TYPE_CHR | CRY_FILE_TYPE_INTERMEDIATE_CAF))) - { - extension = "chr"; - } - else if (fileTypeInt == CRY_FILE_TYPE_SKIN) - { - extension = "skin"; - } - - std::string safeGeometryFileName = geometryFileName; - std::replace(safeGeometryFileName.begin(), safeGeometryFileName.end(), ' ', '_'); - std::string finalFileName; - if (customExportPath.size() > 0) - { - if (PathHelpers::IsRelative(customExportPath)) - { - std::string const assetRelativePath = PathHelpers::Join(originalExportDirectory, customExportPath); - finalFileName = PathHelpers::Join(assetRelativePath, safeGeometryFileName + "." + extension); - } - else - { - context->Log(ILogger::eSeverity_Warning, "An absolute path was specified for export of node %s (%s) - This is unlikely to be correct", geometryFileName.c_str(), customExportPath.c_str()); - finalFileName = PathHelpers::Join(customExportPath, safeGeometryFileName + "." + extension); - } - } - else - { - // no relative path, just export it in the original directory. - finalFileName = PathHelpers::Join(originalExportDirectory, safeGeometryFileName + "." + extension); - } - if (finalFileName.size() > 0) - { - assetGeometryFileNameList.push_back(finalFileName); - if (!FileUtil::EnsureDirectoryExists(PathHelpers::GetDirectory(finalFileName).c_str())) - { - context->Log(ILogger::eSeverity_Error, "Unable to create directory for %s", finalFileName.c_str()); - return; - } - } - } - - if ((fileTypeInt & (CRY_FILE_TYPE_CAF | CRY_FILE_TYPE_INTERMEDIATE_CAF)) != 0) - { - for (int animationIndex = 0; animationIndex < source->GetAnimationCount(); ++animationIndex) - { - std::string const animationName = source->GetAnimationName(&geometryFileData, geometryFileIndex, animationIndex); - - // Animations beginning with an underscore should be ignored. - bool const ignoreAnimation = animationName.empty() || (animationName[0] == '_'); - - if (!ignoreAnimation) - { - std::string safeAnimationName = animationName; - std::replace(safeAnimationName.begin(), safeAnimationName.end(), ' ', '_'); - - std::string exportPath = PathHelpers::Join(originalExportDirectory, safeAnimationName + exportExtension); - animationFileNameList.push_back(std::make_pair(std::make_pair(animationIndex, geometryFileIndex), exportPath)); - if (fileTypeInt & CRY_FILE_TYPE_CAF) - { - animationCompileFileNameList.push_back(std::make_pair(std::make_pair(animationIndex, geometryFileIndex), exportPath)); - } - animationExportSources.push_back(SingleAnimationExportSourceAdapter(source, &geometryFileData, geometryFileIndex, animationIndex)); - exportList.push_back(std::make_pair(exportPath, &animationExportSources.back())); - } - } - } - } - } - - // Export the COLLADA file to the chosen file. - { - ProgressRange exportProgressRange(progressRange, 0.6f); - - size_t const daeCount = exportList.size(); - float const daeProgressRangeSlice = 1.0f / (daeCount > 0 ? daeCount : 1); - for (ExportList::iterator itFile = exportList.begin(); itFile != exportList.end(); ++itFile) - { - const std::string& colladaFileName = (*itFile).first; - IExportSource* fileExportSource = (*itFile).second; - - ProgressRange animationExportProgressRange(exportProgressRange, daeProgressRangeSlice); - - try - { - context->Log(ILogger::eSeverity_Info, "Exporting to file '%s'", colladaFileName.c_str()); - - // Try to create the directory for the file. - if (!FileUtil::EnsureDirectoryExists(PathHelpers::GetDirectory(colladaFileName).c_str())) - { - context->Log(ILogger::eSeverity_Error, "Unable to create directory for %s", colladaFileName.c_str()); - return; - } - - bool ok; - - if (bExportCompressed) - { - IPakSystem* pakSystem = (context ? context->GetPakSystem() : 0); - if (!pakSystem) - { - throw IExportContext::PakSystemError("No pak system provided."); - } - - std::string const archivePath = colladaFileName; - std::string archiveRelativePath = colladaFileName.substr(0, colladaFileName.length() - exportExtension.length()) + ".dae"; - archiveRelativePath = PathHelpers::GetFilename(archiveRelativePath); - - XMLPakFileSink sink(pakSystem, archivePath, archiveRelativePath); - ok = ColladaWriter::Write(fileExportSource, context, &sink, animationExportProgressRange); - } - else - { - XMLFileSink fileSink(colladaFileName); - ok = ColladaWriter::Write(fileExportSource, context, &fileSink, animationExportProgressRange); - } - - if (!ok) - { - // FIXME: erase the resulting file somehow - context->Log(ILogger::eSeverity_Error, "Failed to export '%s'", colladaFileName.c_str()); - return; - } - } - catch (IXMLSink::OpenFailedError e) - { - context->Log(ILogger::eSeverity_Error, "Unable to open output file: %s", e.what()); - return; - } - catch (...) - { - context->Log(ILogger::eSeverity_Error, "Unexpected crash in COLLADA exporter"); - return; - } - } - } - } - - // Get the RC path. If a custom one isn't specified then fall back to the registry method as per the default. - wchar_t resourceCompilerPath[512]; - { - const std::string resourceCompilerPathString = source->GetResourceCompilerPath(); - if (!resourceCompilerPathString.empty()) - { - SettingsManagerHelpers::ConvertUtf8ToUtf16(resourceCompilerPathString.c_str(), SettingsManagerHelpers::CWCharBuffer(resourceCompilerPath, sizeof(resourceCompilerPath))); - } - } - - // Run the resource compiler on the COLLADA file to generate uncompressed CAFs. - { - ProgressRange compilerProgressRange(progressRange, 0.075f); - - CurrentTaskScope currentTask(context, "rc"); - - size_t const daeCount = animationFileNameList.size(); - float const animationProgressRangeSlice = 1.0f / (daeCount > 0 ? daeCount : 1); - for (AnimationFileNameList::iterator itFile = animationFileNameList.begin(); itFile != animationFileNameList.end(); ++itFile) - { - std::string colladaFileName = (*itFile).second; - int geometryFileIndex = itFile->first.second; - - std::string expectedCAFPath; - { - bool isIntermediateCAF = (geometryFileData.GetProperties(geometryFileIndex).filetypeInt & CRY_FILE_TYPE_INTERMEDIATE_CAF) != 0; - string nameWithoutExtension = colladaFileName.substr(0, colladaFileName.length() - exportExtension.length()); - expectedCAFPath = nameWithoutExtension + (isIntermediateCAF ? ".i_caf" : ".caf"); - } - - if (FileUtil::FileExists(expectedCAFPath.c_str())) - { - if (!DeleteFileA(expectedCAFPath.c_str())) - { - context->Log(ILogger::eSeverity_Error, "Failed to remove existing animation file: %s", expectedCAFPath.c_str()); - continue; - } - } - - string arguments = "/refresh"; - - ProgressRange animationCompileProgressRange(compilerProgressRange, animationProgressRangeSlice); - ResourceCompilerLogListener listener(context); - - context->Log(ILogger::eSeverity_Info, "Calling RC to generate uncompressed CAF file: %s", colladaFileName.c_str()); - CResourceCompilerHelper::ERcCallResult result = compiler.CallResourceCompiler( // actual instance of compiler used - colladaFileName.c_str(), - arguments.c_str(), - &listener, - true, false, false, 0, resourceCompilerPath); - - if (result != CResourceCompilerHelper::eRcCallResult_success) - { - context->Log(ILogger::eSeverity_Error, "%s", compiler.GetCallResultDescription(result)); - continue; - } - - context->Log(ILogger::eSeverity_Debug, "RC finished: %s", colladaFileName.c_str()); - if (!FileUtil::FileExists(expectedCAFPath.c_str())) - { - context->Log(ILogger::eSeverity_Error, "Following Animation file is expected to be created by RC: %s", expectedCAFPath.c_str()); - context->Log(ILogger::eSeverity_Error, "Do you have an old RC version?"); - } - -#if !defined(_DEBUG) - // Delete the Collada file. - DeleteFileA(colladaFileName.c_str()); -#endif - } - } - - // Run the resource compiler on the COLLADA file to generate the geometry assets. - { - ProgressRange compilerProgressRange(progressRange, 0.075f); - - CurrentTaskScope currentTask(context, "rc"); - - size_t const daeCount = colladaGeometryFileNameList.size(); - float const assetProgressRangeSlice = 1.0f / (daeCount > 0 ? daeCount : 1); - for (size_t i = 0; i < daeCount; ++i) - { - const std::string& colladaFileName = colladaGeometryFileNameList[i]; - - ProgressRange assetCompileProgressRange(compilerProgressRange, assetProgressRangeSlice); - ResourceCompilerLogListener listener(context); - context->Log(ILogger::eSeverity_Info, "Calling RC to generate raw asset file: %s", colladaFileName.c_str()); - CResourceCompilerHelper::ERcCallResult result = compiler.CallResourceCompiler( - colladaFileName.c_str(), - "/refresh", - &listener, - true, false, false, 0, resourceCompilerPath); - -#if !defined(_DEBUG) - // Delete the Collada file. - DeleteFileA(colladaFileName.c_str()); -#endif - - if (result == CResourceCompilerHelper::eRcCallResult_success) - { - context->Log(ILogger::eSeverity_Debug, "RC finished: %s", colladaFileName.c_str()); - } - else - { - context->Log(ILogger::eSeverity_Error, "%s", compiler.GetCallResultDescription(result)); - return; - } - } - } - - { - // Create an RC helper - do it outside the loop, since it queries the registry on construction. - ResourceCompilerLogListener listener(context); - - // Check the registry to see whether we should compress the animations or not. - int processAnimations = GetSetting(context->GetSettings(), "CompressCAFs", 1); - - if (!processAnimations) - { - context->Log(ILogger::eSeverity_Warning, "CompressCAFs registry key set to 0 - not compressing CAFs"); - } - else - { - // Run the resource compiler again on the generated CAF files to compress/process them. - context->Log(ILogger::eSeverity_Debug, "CompressCAFs not set or set to 1 - compressing CAFs"); - - CurrentTaskScope currentTask(context, "compress"); - ProgressRange compressRange(progressRange, 0.025f); - - size_t const cafCount = animationCompileFileNameList.size(); - float const animationProgressRangeSlice = 1.0f / (cafCount > 0 ? cafCount : 1); - for (AnimationFileNameList::iterator itFile = animationCompileFileNameList.begin(); itFile != animationCompileFileNameList.end(); ++itFile) - { - std::string colladaFileName = (*itFile).second; - ProgressRange animationProgressRange(compressRange, animationProgressRangeSlice); - - // Assume the RC generated the CAF file using the take name and adding .CAF. - std::string cafPath = colladaFileName.substr(0, colladaFileName.length() - exportExtension.length()) + ".caf"; - std::string cbaPath = StringHelpers::ConvertString(CBAHelpers::FindCBAFileForFile(cafPath.c_str(), context->GetPakSystem())); - - if (cbaPath.empty()) - { - context->Log(ILogger::eSeverity_Error, "Unable to find CBA file for file \"%s\" (looked for a root game directory that contains a relative path of \"Animations/Animations.cba\"", cafPath.c_str()); - } - else - { - char buffer[2048]; - sprintf(buffer, "/file=\"%s\" /refresh /SkipDba", cafPath.c_str()); - context->Log(ILogger::eSeverity_Info, "Calling RC to compress CAF file: (CBA file = %s) %s", cbaPath.c_str(), buffer); - CResourceCompilerHelper::ERcCallResult result = compiler.CallResourceCompiler(cbaPath.c_str(), buffer, &listener, true, resourceCompilerPathType, false, false, 0, resourceCompilerPath); - if (result == CResourceCompilerHelper::eRcCallResult_success) - { - context->Log(ILogger::eSeverity_Debug, "RC finished: %s %s", cbaPath.c_str(), buffer); - } - else - { - context->Log(ILogger::eSeverity_Error, "%s", compiler.GetCallResultDescription(result)); - return; - } - } - } - } - - // Check the registry to see whether we should optimize the geometry files or not. - int optimizeGeometry = GetSetting(context->GetSettings(), "OptimizeAssets", 1); - - // Run the resource compiler again on the generated geometry files to compress/process them. - // TODO: This should not be necessary, the RC should be modified so that assets are automatically - // compressed when exported from COLLADA. - if (!optimizeGeometry) - { - context->Log(ILogger::eSeverity_Warning, "OptimizeAssets registry key set to 0 - not compressing CAFs"); - } - else - { - context->Log(ILogger::eSeverity_Debug, "OptimizeAssets not set or set to 1 - optimizing geometry"); - - CurrentTaskScope currentTask(context, "compress"); - ProgressRange compressRange(progressRange, 0.025f); - - size_t const assetCount = assetGeometryFileNameList.size(); - float const assetProgressRangeSlice = 1.0f / (assetCount > 0 ? assetCount : 1); - for (size_t i = 0; i < assetCount; ++i) - { - const std::string& assetFileName = assetGeometryFileNameList[i]; - ProgressRange animationProgressRange(compressRange, assetProgressRangeSlice); - - // note: we skip some asset types because we know that they are "optimized" already - if (StringHelpers::EndsWithIgnoreCase(assetFileName, ".anm") || StringHelpers::EndsWithIgnoreCase(assetFileName, ".chr") || StringHelpers::EndsWithIgnoreCase(assetFileName, ".skin")) - { - context->Log(ILogger::eSeverity_Info, "Calling RC to optimize asset \"%s\"", assetFileName.c_str()); - CResourceCompilerHelper::ERcCallResult result = compiler.CallResourceCompiler(assetFileName.c_str(), "/refresh", &listener, true, resourceCompilerPathType, false, false, 0, resourceCompilerPath); - if (result == CResourceCompilerHelper::eRcCallResult_success) - { - context->Log(ILogger::eSeverity_Debug, "RC finished: %s", assetFileName.c_str()); - } - else - { - context->Log(ILogger::eSeverity_Error, "%s", compiler.GetCallResultDescription(result)); - return; - } - } - } - } - } - - // Log the end time. - { - char buf[1024]; - std::time_t t = std::time(0); - std::strftime(buf, sizeof(buf) / sizeof(buf[0]), "%H:%M:%S on %a, %d/%m/%Y", std::localtime(&t)); - context->Log(ILogger::eSeverity_Info, "Export finished at %s", buf); - } -} diff --git a/Code/Tools/CryCommonTools/Export/ColladaExportWriter.h b/Code/Tools/CryCommonTools/Export/ColladaExportWriter.h deleted file mode 100644 index 8dc53ad62f..0000000000 --- a/Code/Tools/CryCommonTools/Export/ColladaExportWriter.h +++ /dev/null @@ -1,29 +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_CRYCOMMONTOOLS_EXPORT_COLLADAEXPORTWRITER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAEXPORTWRITER_H -#pragma once - - -#include "IExportWriter.h" - -class ColladaExportWriter - : public IExportWriter -{ -public: - // IExportWriter - virtual void Export(IExportSource* source, IExportContext* context); -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAEXPORTWRITER_H diff --git a/Code/Tools/CryCommonTools/Export/ColladaWriter.cpp b/Code/Tools/CryCommonTools/Export/ColladaWriter.cpp deleted file mode 100644 index 106ed02ba4..0000000000 --- a/Code/Tools/CryCommonTools/Export/ColladaWriter.cpp +++ /dev/null @@ -1,2918 +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 "StdAfx.h" -#include "ColladaWriter.h" -#include "IExportSource.h" -#include "ISettings.h" -#include "XMLWriter.h" -#include "SkeletonData.h" -#include "AnimationData.h" -#include "ProgressRange.h" -#include "ModelData.h" -#include "IExportContext.h" -#include "GeometryFileData.h" -#include "GeometryData.h" -#include "MaterialData.h" -#include "SkinningData.h" -#include "Cry_Math.h" -#include "LocaleChanger.h" -#include "MorphData.h" -#include "StringHelpers.h" -#include "GeometryMaterialData.h" -#include "ColladaShared.h" -#include -#include -#include -#include - -namespace -{ - bool FloatingPointHasPrecisionIssues() - { - Matrix44 m; - - m.m00 = 0.729367f; - m.m01 = -0.143863f; - m.m02 = -0.668825f; - m.m03 = 0.595435f; - - m.m10 = -0.573746f; - m.m11 = 0.403844f; - m.m12 = -0.712549f; - m.m13 = 1.14523f; - - m.m20 = 0.37261f; - m.m21 = 0.903445f; - m.m22 = 0.21201f; - m.m23 = 0.0669039f; - - m.m30 = 0; - m.m31 = 0; - m.m32 = 0; - m.m33 = 1; - - m.Invert(); - - return m.m33 <= 0.999f || m.m33 >= 1.001f; - - // For testing with www.wolframalpha.com: - // string a = StringHelpers::Format("inverse{{%g,%g,%g,%g},{%g,%g,%g,%g},{%g,%g,%g,%g},{%g,%g,%g,%g}}", - // m.m00, m.m01, m.m02, m.m03, - // m.m10, m.m11, m.m12, m.m13, - // m.m20, m.m21, m.m22, m.m23, - // m.m30, m.m31, m.m32, m.m33); - } -} - - -namespace -{ - void DecomposeTransform(Vec3& translation, CryQuat& rotation, Vec3& scale, const Matrix34& transform) - { - translation = transform.GetTranslation(); - Matrix33 orientation(transform); - scale.x = Vec3(orientation.m00, orientation.m10, orientation.m20).GetLength(); - scale.y = Vec3(orientation.m01, orientation.m11, orientation.m21).GetLength(); - scale.z = Vec3(orientation.m02, orientation.m12, orientation.m22).GetLength(); - orientation.OrthonormalizeFast(); - rotation = !CryQuat(orientation); - } - - struct BoneEntry - { - std::string name; - std::string physName; - std::string parentFrameName; - }; - - typedef std::map, SkeletonData> SkeletonDataMap; - typedef std::map, MorphData> MorphDataMap; - typedef std::map, std::vector > BoneDataMap; - - struct GeometryEntry - { - GeometryEntry(const std::string& name, int geometryFileIndex, int modelIndex) - : name(name) - , geometryFileIndex(geometryFileIndex) - , modelIndex(modelIndex) {} - std::string name; - int geometryFileIndex; - int modelIndex; - }; - - struct BoneGeometryEntry - { - BoneGeometryEntry(const std::string& name, int geometryFileIndex, int modelIndex, int boneIndex) - : name(name) - , geometryFileIndex(geometryFileIndex) - , modelIndex(modelIndex) - , boneIndex(boneIndex) {} - std::string name; - int geometryFileIndex; - int modelIndex; - int boneIndex; - }; - - struct MorphGeometryEntry - { - MorphGeometryEntry(const std::string& name, const std::string& morphName, int geometryFileIndex, int modelIndex, int morphIndex) - : name(name) - , morphName(morphName) - , geometryFileIndex(geometryFileIndex) - , modelIndex(modelIndex) - , morphIndex(morphIndex) {} - std::string name; - std::string morphName; - int geometryFileIndex; - int modelIndex; - int morphIndex; - }; - - struct EffectsEntry - { - EffectsEntry(const std::string& name) - : name(name) {} - - std::string name; - }; - - struct MaterialEntry - { - MaterialEntry(const std::string& name) - : name(name) {} - - std::string name; - }; - - struct SkinControllerEntry - { - std::string name; - int geometryFileIndex; - int modelIndex; - }; - - struct MorphControllerEntry - { - std::string name; - int geometryFileIndex; - int modelIndex; - }; - - typedef std::map, MorphControllerEntry> MorphControllerMap; - - void BindMaterials(XMLWriter& writer, IExportContext* context, MaterialData& materialData, const ModelData& modelData, int modelIndex, const std::map& materialMaterialMap, const std::vector& materials, IExportSource* source) - { - // Instance any materials that the node uses. - GeometryMaterialData geometryMaterialData; - source->ReadGeometryMaterialData(context, &geometryMaterialData, &modelData, &materialData, modelIndex); - - std::set usedMaterialIndices; - for (int materialIndex = 0, materialCount = geometryMaterialData.GetUsedMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - usedMaterialIndices.insert(geometryMaterialData.GetUsedMaterialIndex(materialIndex)); - } - if (!usedMaterialIndices.empty()) - { - XMLWriter::Element bindMaterialElement(writer, "bind_material"); - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - for (std::set::const_iterator usedMtlPos = usedMaterialIndices.begin(), usedMtlEnd = usedMaterialIndices.end(); usedMtlPos != usedMtlEnd; ++usedMtlPos) - { - std::map::const_iterator entryMapPos = materialMaterialMap.find(*usedMtlPos); - int entryIndex = (entryMapPos != materialMaterialMap.end() ? (*entryMapPos).second : -1); - std::string name = (entryIndex >= 0 ? materials[entryIndex].name : "UNKNOWN_INSTANCED_MATERIAL"); - - XMLWriter::Element instanceMaterialElement(writer, "instance_material"); - instanceMaterialElement.Attribute("symbol", name); - instanceMaterialElement.Attribute("target", "#" + name); - } - } - } - - void BindBoneMaterials(XMLWriter& writer, IExportContext* context, MaterialData& materialData, SkeletonData& skeletonData, int boneIndex, const std::map& materialMaterialMap, const std::vector& materials, IExportSource* source) - { - // Instance any materials that the node uses. - GeometryMaterialData geometryMaterialData; - source->ReadBoneGeometryMaterialData(context, &geometryMaterialData, &skeletonData, boneIndex, &materialData); - - std::set usedMaterialIndices; - for (int materialIndex = 0, materialCount = geometryMaterialData.GetUsedMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - usedMaterialIndices.insert(geometryMaterialData.GetUsedMaterialIndex(materialIndex)); - } - if (!usedMaterialIndices.empty()) - { - XMLWriter::Element bindMaterialElement(writer, "bind_material"); - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - for (std::set::const_iterator usedMtlPos = usedMaterialIndices.begin(), usedMtlEnd = usedMaterialIndices.end(); usedMtlPos != usedMtlEnd; ++usedMtlPos) - { - std::map::const_iterator entryMapPos = materialMaterialMap.find(*usedMtlPos); - int entryIndex = (entryMapPos != materialMaterialMap.end() ? (*entryMapPos).second : -1); - std::string name = (entryIndex >= 0 ? materials[entryIndex].name : "UNKNOWN_INSTANCED_MATERIAL"); - - XMLWriter::Element instanceMaterialElement(writer, "instance_material"); - instanceMaterialElement.Attribute("symbol", name); - instanceMaterialElement.Attribute("target", "#" + name); - } - } - - //// Instance any materials that the node uses. - //std::vector materialIDs; - //for (int materialIndex = 0, materialCount = materialData.GetMaterialCount(); materialIndex < materialCount; ++materialIndex) - //{ - // int parentIndex = materialData.GetParentIndex(materialIndex); - // if (parentIndex >= 0 && parentIndex == skeletonData.GetMaterial(boneIndex)) - // materialIDs.push_back(materialIndex); - //} - - //if (!materialIDs.empty()) - //{ - // XMLWriter::Element bindMaterialElement(writer, "bind_material"); - // XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - // for (int i = 0, count = int(materialIDs.size()); i < count; ++i) - // { - // std::map::const_iterator entryMapPos = materialMaterialMap.find(materialIDs[i]); - // int entryIndex = (entryMapPos != materialMaterialMap.end() ? (*entryMapPos).second : -1); - // std::string name = (entryIndex >= 0 ? materials[entryIndex].name : 0); - - // XMLWriter::Element instanceMaterialElement(writer, "instance_material"); - // instanceMaterialElement.Attribute("symbol", name); - // instanceMaterialElement.Attribute("target", "#" + name); - // } - //} - } - - void WriteExtraData(XMLWriter& writer, const SHelperData& helperData, const std::string& properties) - { - // Write helper data (if it's helper node) and properties - if ((!properties.empty()) || (helperData.m_eHelperType != SHelperData::eHelperType_UNKNOWN)) - { - XMLWriter::Element elem(writer, "extra"); - { - XMLWriter::Element elem(writer, "technique"); - elem.Attribute("profile", "CryEngine"); - { - if (!properties.empty()) - { - // TODO: Sokov: check for invalid characters in properties string, like '<', '>', <' ', >127 etc. - XMLWriter::Element elem(writer, "properties"); - elem.Content(properties); - } - - if (helperData.m_eHelperType != SHelperData::eHelperType_UNKNOWN) - { - XMLWriter::Element elem(writer, "helper"); - switch (helperData.m_eHelperType) - { - case SHelperData::eHelperType_Point: - elem.Attribute("type", "point"); - break; - case SHelperData::eHelperType_Dummy: - elem.Attribute("type", "dummy"); - { - XMLWriter::Element elem(writer, "bound_box_min"); - elem.ContentArrayElement(helperData.m_boundBoxMin[0]); - elem.ContentArrayElement(helperData.m_boundBoxMin[1]); - elem.ContentArrayElement(helperData.m_boundBoxMin[2]); - } - { - XMLWriter::Element elem(writer, "bound_box_max"); - elem.ContentArrayElement(helperData.m_boundBoxMax[0]); - elem.ContentArrayElement(helperData.m_boundBoxMax[1]); - elem.ContentArrayElement(helperData.m_boundBoxMax[2]); - } - break; - default: - assert(false); - elem.Attribute("type", "UNKNOWN"); - break; - } - } - } - } - } - - // ****** I dont think we need this anymore. These files are not readable by XSI as far as I know. ****** - // ****** Removed 03-Jan-2012 - // Write special properties for importing to the XSI. - /*{ - XMLWriter::Element elem(writer, "technique"); - elem.Attribute("profile","XSI"); - { - XMLWriter::Element elem(writer, "XSI_CustomPSet"); - elem.Attribute("name","ObjectProperties"); - { - XMLWriter::Element elem(writer, "propagation"); - elem.Content("NODE"); - } - { - XMLWriter::Element elem(writer, "type"); - elem.Content("CryNodeProperties"); - } - { - XMLWriter::Element elem(writer, "XSI_Parameter"); - elem.Attribute("id","Props"); - elem.Attribute("type","Text"); - elem.Attribute("value",properties.c_str()); - } - } - }*/ - } - - void WriteSkeletonRecurse(XMLWriter& writer, IExportContext* context, const std::string& modelName, SkeletonData& skeletonData, int boneIndex, const std::string& name, const std::vector& bones, std::map, int>, int>& boneGeometryMap, std::vector& boneGeometries, int geometryFileIndex, int modelIndex, MaterialData& materialData, const std::map& materialMaterialMap, const std::vector& materials, IExportSource* source, ProgressRange& progressRange) - { - XMLWriter::Element nodeElement(writer, "node"); - nodeElement.Attribute("id", name); // The ID must be unique. - nodeElement.Attribute("name", name); // The name must not include model name as prefix, so it can match the skeleton. - - // Calculate the transforms for the bone and its parent. This could be made a lot simpler by using proper - // transforms in the skeleton data. - Matrix34 transform; - { - Matrix44 transforms[2]; - int boneIndices[2] = {boneIndex, skeletonData.GetBoneParentIndex(boneIndex)}; - for (int i = 0; i < 2; ++i) - { - transforms[i] = IDENTITY; - - if (boneIndices[i] >= 0) - { - Vec3 scaleParams; - skeletonData.GetScale((float*)&scaleParams, boneIndices[i]); - Matrix44 scale = Matrix33::CreateScale(scaleParams); - - Ang3 rotationParams; - skeletonData.GetRotation((float*)&rotationParams, boneIndices[i]); - Matrix44 rotation = Matrix33::CreateRotationXYZ(rotationParams); - - Vec3 translationParams; - skeletonData.GetTranslation((float*)&translationParams, boneIndices[i]); - Matrix44 translation(IDENTITY); - translation.SetTranslation(translationParams); - - transforms[i] = translation * (rotation * scale); - } - } - transform = Matrix34(transforms[1].GetInverted() * transforms[0]); - } - - Vec3 translation, scaling; - CryQuat orientation; - DecomposeTransform(translation, orientation, scaling, transform); - Ang3 rotation = Ang3::GetAnglesXYZ(orientation); - - // Write translation element. - { - XMLWriter::Element translateElement(writer, "translate"); - translateElement.Attribute("sid", "translation"); - translateElement.ContentArrayElement(translation[0]); - translateElement.ContentArrayElement(translation[1]); - translateElement.ContentArrayElement(translation[2]); - } - - // Write rotation elements. - for (int axisIndex = 0; axisIndex < 3; ++axisIndex) - { - XMLWriter::Element rotateElement(writer, "rotate"); - char sidBuffer[1024]; - sprintf(sidBuffer, "rotation_%c", 'z' - axisIndex); - rotateElement.Attribute("sid", sidBuffer); - rotateElement.ContentArrayElement(axisIndex == 2 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 1 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 0 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(rotation[2 - axisIndex] * 180.0f / 3.14159f); - } - - // Write scale elements - { - XMLWriter::Element scaleElement(writer, "scale"); - scaleElement.Attribute("sid", "scale"); - scaleElement.ContentArrayElement(scaling[0]); - scaleElement.ContentArrayElement(scaling[1]); - scaleElement.ContentArrayElement(scaling[2]); - } - - // If the node has geometry, write out the reference to it. - std::map, int>, int>::iterator boneGeometryMapPos = boneGeometryMap.find(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), boneIndex)); - if (boneGeometryMapPos != boneGeometryMap.end()) - { - const std::string& boneGeometryName = boneGeometries[(*boneGeometryMapPos).second].name; - XMLWriter::Element instanceGeometryElement(writer, "instance_geometry"); - instanceGeometryElement.Attribute("url", std::string("#") + boneGeometryName); - - BindBoneMaterials(writer, context, materialData, skeletonData, boneIndex, materialMaterialMap, materials, source); - } - - SHelperData dummyHelperData; - WriteExtraData(writer, dummyHelperData, skeletonData.GetBoneProperties(boneIndex)); - - int childIndexCount = skeletonData.GetChildCount(boneIndex); - float progressRangeSlice = 1.0f / (childIndexCount > 0 ? float(childIndexCount) : 1.0f); - for (int childIndexIndex = 0; childIndexIndex < childIndexCount; ++childIndexIndex) - { - int childIndex = skeletonData.GetChildIndex(boneIndex, childIndexIndex); - WriteSkeletonRecurse(writer, context, modelName, skeletonData, childIndex, bones[childIndex].name, bones, boneGeometryMap, boneGeometries, geometryFileIndex, modelIndex, materialData, materialMaterialMap, materials, source, ProgressRange(progressRange, progressRangeSlice)); - } - } - - void WritePhysSkeletonRecurse(XMLWriter& writer, const std::string& modelName, const SkeletonData& skeletonData, int boneIndex, const std::vector& bones, ProgressRange& progressRange, const Matrix34& physFrameTM, const Matrix34& parentTM) - { - Matrix34 currentPhysFrameTM = physFrameTM; - - // Output a node for the parent frame. - bool shouldWriteParentFrame = skeletonData.HasParentFrame(boneIndex); - XMLWriter::Element parentFrameElement(writer, "node", shouldWriteParentFrame); - if (shouldWriteParentFrame) - { - parentFrameElement.Attribute("id", bones[boneIndex].parentFrameName); // The ID must be unique. - parentFrameElement.Attribute("name", bones[boneIndex].parentFrameName); // The name must not include model name as prefix, so it can match the skeleton. - - // Write translation element. - float translation[3]; - skeletonData.GetParentFrameTranslation(boneIndex, translation); - { - XMLWriter::Element translateElement(writer, "translate"); - translateElement.Attribute("sid", "translation"); - translateElement.ContentArrayElement(translation[0]); - translateElement.ContentArrayElement(translation[1]); - translateElement.ContentArrayElement(translation[2]); - } - - // Write rotation elements. - float rotation[3]; - skeletonData.GetParentFrameRotation(boneIndex, rotation); - for (int axisIndex = 0; axisIndex < 3; ++axisIndex) - { - XMLWriter::Element rotateElement(writer, "rotate"); - char sidBuffer[1024]; - sprintf(sidBuffer, "rotation_%c", 'z' - axisIndex); - rotateElement.Attribute("sid", sidBuffer); - rotateElement.ContentArrayElement(axisIndex == 2 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 1 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 0 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(rotation[2 - axisIndex] * 180.0f / 3.14159f); - } - - // Write scale elements - float scaling[3]; - skeletonData.GetParentFrameScale(boneIndex, scaling); - { - XMLWriter::Element scaleElement(writer, "scale"); - scaleElement.Attribute("sid", "scale"); - scaleElement.ContentArrayElement(scaling[0]); - scaleElement.ContentArrayElement(scaling[1]); - scaleElement.ContentArrayElement(scaling[2]); - } - - Matrix34 tm(IDENTITY); - Matrix34 translationTM(IDENTITY); - translationTM.SetTranslation(Vec3(translation[0], translation[1], translation[2])); - Matrix34 rotationTM = Matrix33::CreateRotationXYZ(Ang3(rotation[0], rotation[1], rotation[2])); - Matrix34 scaleTM = Matrix33::CreateScale(Vec3(scaling[0], scaling[1], scaling[2])); - Matrix34 transform = translationTM * (rotationTM * scaleTM); - - currentPhysFrameTM = transform * currentPhysFrameTM; - } - - Matrix34 worldTM; - { - float translation[3]; - skeletonData.GetTranslation(translation, boneIndex); - float rotation[3]; - skeletonData.GetRotation(rotation, boneIndex); - float scaling[3]; - skeletonData.GetScale(scaling, boneIndex); - Matrix34 tm(IDENTITY); - Matrix34 translationTM(IDENTITY); - translationTM.SetTranslation(Vec3(translation[0], translation[1], translation[2])); - Matrix34 rotationTM = Matrix33::CreateRotationXYZ(Ang3(rotation[0], rotation[1], rotation[2])); - Matrix34 scaleTM = Matrix33::CreateScale(Vec3(scaling[0], scaling[1], scaling[2])); - worldTM = translationTM * (rotationTM * scaleTM); - } - Matrix34 transform = parentTM.GetInverted() * worldTM; - - XMLWriter::Element nodeElement(writer, "node", skeletonData.GetPhysicalized(boneIndex)); - if (skeletonData.GetPhysicalized(boneIndex)) - { - Matrix34 physTM = currentPhysFrameTM.GetInverted() * worldTM; - Vec3 translation, scaling; - CryQuat orientation; - DecomposeTransform(translation, orientation, scaling, physTM); - Ang3 rotation = Ang3::GetAnglesXYZ(orientation); - - nodeElement.Attribute("id", bones[boneIndex].physName); // The ID must be unique. - nodeElement.Attribute("name", bones[boneIndex].physName); // The name must not include model name as prefix, so it can match the skeleton. - - // Write translation element. - { - XMLWriter::Element translateElement(writer, "translate"); - translateElement.Attribute("sid", "translation"); - translateElement.ContentArrayElement(translation[0]); - translateElement.ContentArrayElement(translation[1]); - translateElement.ContentArrayElement(translation[2]); - } - - // Write rotation elements. - for (int axisIndex = 0; axisIndex < 3; ++axisIndex) - { - XMLWriter::Element rotateElement(writer, "rotate"); - char sidBuffer[1024]; - sprintf(sidBuffer, "rotation_%c", 'z' - axisIndex); - rotateElement.Attribute("sid", sidBuffer); - rotateElement.ContentArrayElement(axisIndex == 2 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 1 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 0 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(rotation[2 - axisIndex] * 180.0f / 3.14159f); - } - - // Write scale elements - { - XMLWriter::Element scaleElement(writer, "scale"); - scaleElement.Attribute("sid", "scale"); - scaleElement.ContentArrayElement(scaling[0]); - scaleElement.ContentArrayElement(scaling[1]); - scaleElement.ContentArrayElement(scaling[2]); - } - - currentPhysFrameTM = worldTM; - } - - SHelperData dummyHelperData; - WriteExtraData(writer, dummyHelperData, skeletonData.GetBoneGeomProperties(boneIndex)); - - int childIndexCount = skeletonData.GetChildCount(boneIndex); - float progressRangeSlice = 1.0f / (childIndexCount > 0 ? float(childIndexCount) : 1.0f); - for (int childIndexIndex = 0; childIndexIndex < childIndexCount; ++childIndexIndex) - { - int childIndex = skeletonData.GetChildIndex(boneIndex, childIndexIndex); - WritePhysSkeletonRecurse(writer, modelName, skeletonData, childIndex, bones, ProgressRange(progressRange, progressRangeSlice), currentPhysFrameTM, worldTM); - } - } - - void WriteGeometryData(XMLWriter& writer, const std::string& id, const std::string& name, GeometryData& geometryData, MaterialData& materialData, std::map& materialMaterialMap, std::vector& materials) - { - XMLWriter::Element geometryElement(writer, "geometry"); - geometryElement.Attribute("id", id); - if (!name.empty()) - { - geometryElement.Attribute("name", name); - } - XMLWriter::Element meshElement(writer, "mesh"); - - // Write out the positions. - std::string posSourceName = id + "-pos"; - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", posSourceName); - - std::string arrayName = posSourceName + "-array"; - { - XMLWriter::Element arrayElement(writer, "float_array"); - arrayElement.Attribute("id", arrayName); - arrayElement.Attribute("count", int(geometryData.positions.size()) * 3); - for (int positionIndex = 0, positionCount = int(geometryData.positions.size()); positionIndex < positionCount; ++positionIndex) - { - arrayElement.ContentArrayElement(geometryData.positions[positionIndex].x); - arrayElement.ContentArrayElement(geometryData.positions[positionIndex].y); - arrayElement.ContentArrayElement(geometryData.positions[positionIndex].z); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", std::string("#") + arrayName); - accessorElement.Attribute("count", int(geometryData.positions.size())); - accessorElement.Attribute("stride", 3); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "X"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "Y"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "Z"); - paramElement.Attribute("type", "float"); - } - } - - // Write out the normals. - std::string normalSourceName = id + "-normal"; - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", normalSourceName); - - std::string arrayName = normalSourceName + "-array"; - { - XMLWriter::Element arrayElement(writer, "float_array"); - arrayElement.Attribute("id", arrayName); - arrayElement.Attribute("count", int(geometryData.normals.size()) * 3); - for (int normalIndex = 0, normalCount = int(geometryData.normals.size()); normalIndex < normalCount; ++normalIndex) - { - arrayElement.ContentArrayElement(geometryData.normals[normalIndex].x); - arrayElement.ContentArrayElement(geometryData.normals[normalIndex].y); - arrayElement.ContentArrayElement(geometryData.normals[normalIndex].z); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", std::string("#") + arrayName); - accessorElement.Attribute("count", int(geometryData.normals.size())); - accessorElement.Attribute("stride", 3); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "X"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "Y"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "Z"); - paramElement.Attribute("type", "float"); - } - } - - // Write out the texture coordinates. - std::string textureCoordinateSourceName = id + "-uvs"; - if (!geometryData.textureCoordinates.empty()) - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", textureCoordinateSourceName); - - std::string arrayName = textureCoordinateSourceName + "-array"; - { - XMLWriter::Element arrayElement(writer, "float_array"); - arrayElement.Attribute("id", arrayName); - arrayElement.Attribute("count", int(geometryData.textureCoordinates.size()) * 2); - for (int textureCoordinateIndex = 0, textureCoordinateCount = int(geometryData.textureCoordinates.size()); textureCoordinateIndex < textureCoordinateCount; ++textureCoordinateIndex) - { - arrayElement.ContentArrayElement(geometryData.textureCoordinates[textureCoordinateIndex].u); - arrayElement.ContentArrayElement(geometryData.textureCoordinates[textureCoordinateIndex].v); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", std::string("#") + arrayName); - accessorElement.Attribute("count", int(geometryData.textureCoordinates.size())); - accessorElement.Attribute("stride", 2); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "S"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "T"); - paramElement.Attribute("type", "float"); - } - } - - // Write out the vertex colors. - std::string vertexColorSourceName = id + "-vcol"; - if (!geometryData.vertexColors.empty()) - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", vertexColorSourceName); - - std::string arrayName = vertexColorSourceName + "-array"; - { - XMLWriter::Element arrayElement(writer, "float_array"); - arrayElement.Attribute("id", arrayName); - arrayElement.Attribute("count", int(geometryData.vertexColors.size()) * 4); - for (int vertexColorIndex = 0, vertexColorCount = int(geometryData.vertexColors.size()); vertexColorIndex < vertexColorCount; ++vertexColorIndex) - { - arrayElement.ContentArrayElement(geometryData.vertexColors[vertexColorIndex].r); - arrayElement.ContentArrayElement(geometryData.vertexColors[vertexColorIndex].g); - arrayElement.ContentArrayElement(geometryData.vertexColors[vertexColorIndex].b); - arrayElement.ContentArrayElement(geometryData.vertexColors[vertexColorIndex].a); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", std::string("#") + arrayName); - accessorElement.Attribute("count", int(geometryData.vertexColors.size())); - accessorElement.Attribute("stride", 4); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "R"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "G"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "B"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "A"); - paramElement.Attribute("type", "float"); - } - } - - // Write out the vertex elements. - std::string vertexName = id + "-vtx"; - { - XMLWriter::Element vertexElement(writer, "vertices"); - vertexElement.Attribute("id", vertexName); - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "POSITION"); - inputElement.Attribute("source", std::string("#") + posSourceName); - } - - // Sort the triangles by material. - std::vector > polygonsByMaterial(materialData.GetMaterialCount() + 1); - for (int polygonIndex = 0, polygonCount = int(geometryData.polygons.size()); polygonIndex < polygonCount; ++polygonIndex) - { - polygonsByMaterial[geometryData.polygons[polygonIndex].mtlID + 1].push_back(geometryData.polygons[polygonIndex]); - } - - // Write out the triangles. - for (int materialIndex = -1, materialCount = materialData.GetMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - if (!polygonsByMaterial[materialIndex + 1].empty()) - { - std::map::iterator materialMapPos = materialMaterialMap.find(materialIndex); - int materialEntryIndex = (materialMapPos != materialMaterialMap.end() ? (*materialMapPos).second : -1); - - std::vector& polygons = polygonsByMaterial[materialIndex + 1]; - - XMLWriter::Element trianglesElement(writer, "triangles"); - trianglesElement.Attribute("count", int(polygons.size())); - if (materialEntryIndex >= 0) - { - trianglesElement.Attribute("material", materials[materialEntryIndex].name); - } - int offset = 0; - bool hasPositions = false; - if (!geometryData.positions.empty()) - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "VERTEX"); - inputElement.Attribute("source", std::string("#") + vertexName); - inputElement.Attribute("offset", offset++); - hasPositions = true; - } - bool hasNormals = false; - if (!geometryData.normals.empty()) - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "NORMAL"); - inputElement.Attribute("source", std::string("#") + normalSourceName); - inputElement.Attribute("offset", offset++); - hasNormals = true; - } - bool hasUVs = false; - if (!geometryData.textureCoordinates.empty()) - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "TEXCOORD"); - inputElement.Attribute("source", std::string("#") + textureCoordinateSourceName); - inputElement.Attribute("offset", offset++); - hasUVs = true; - } - bool hasColors = false; - if (!geometryData.vertexColors.empty()) - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "COLOR"); - inputElement.Attribute("source", std::string("#") + vertexColorSourceName); - inputElement.Attribute("offset", offset++); - hasColors = true; - } - - XMLWriter::Element pElement(writer, "p"); - for (int polygonIndex = 0, polygonCount = int(polygons.size()); polygonIndex < polygonCount; ++polygonIndex) - { - for (int vertexIndex = 0; vertexIndex < 3; ++vertexIndex) - { - if (hasPositions && polygons[polygonIndex].v[vertexIndex].positionIndex >= 0) - { - pElement.ContentArrayElement(polygons[polygonIndex].v[vertexIndex].positionIndex); - } - if (hasNormals && polygons[polygonIndex].v[vertexIndex].normalIndex >= 0) - { - pElement.ContentArrayElement(polygons[polygonIndex].v[vertexIndex].normalIndex); - } - if (hasUVs && polygons[polygonIndex].v[vertexIndex].textureCoordinateIndex >= 0) - { - pElement.ContentArrayElement(polygons[polygonIndex].v[vertexIndex].textureCoordinateIndex); - } - if (hasColors && polygons[polygonIndex].v[vertexIndex].vertexColorIndex >= 0) - { - pElement.ContentArrayElement(polygons[polygonIndex].v[vertexIndex].vertexColorIndex); - } - } - } - } - } - } - - bool WriteGeometries(IExportContext* context, XMLWriter& writer, std::vector& geometries, GeometryFileData& geometryFileData, const std::vector& modelData, MorphDataMap& morphData, MaterialData& materialData, std::vector& materials, std::map& materialMaterialMap, SkeletonDataMap& skeletonData, std::vector& boneGeometries, std::map, int>, int>& boneGeometryMap, std::map, int>, int>& morphGeometryMap, std::vector& morphGeometries, IExportSource* source, ProgressRange& progressRange) - { - XMLWriter::Element libraryGeometriesElement(writer, "library_geometries"); - - // Loop through all the geometries. - for (int geometryIndex = 0, geometryCount = int(geometries.size()); geometryIndex < geometryCount; ++geometryIndex) - { - GeometryEntry& geometryEntry = geometries[geometryIndex]; - - // Read in the geometry data. - GeometryData geometryData; - bool ok = source->ReadGeometry(context, &geometryData, &modelData[geometryEntry.geometryFileIndex], &materialData, geometryEntry.modelIndex); - if (!ok) - { - return false; - } - - WriteGeometryData(writer, geometryEntry.name, "", geometryData, materialData, materialMaterialMap, materials); - } - - // Loop through all the bone geometries. - for (int boneGeometryIndex = 0, boneGeometryCount = int(boneGeometries.size()); boneGeometryIndex < boneGeometryCount; ++boneGeometryIndex) - { - BoneGeometryEntry& boneGeometryEntry = boneGeometries[boneGeometryIndex]; - - GeometryData geometryData; - SkeletonDataMap::iterator skeletonDataPos = skeletonData.find(std::make_pair(boneGeometryEntry.geometryFileIndex, boneGeometryEntry.modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - source->ReadBoneGeometry(context, &geometryData, &(*skeletonDataPos).second, boneGeometryEntry.boneIndex, &materialData); - } - - WriteGeometryData(writer, boneGeometryEntry.name, "", geometryData, materialData, materialMaterialMap, materials); - } - - // Loop through all the morph geometries. - for (int morphGeometryIndex = 0, morphGeometryCount = int(morphGeometries.size()); morphGeometryIndex < morphGeometryCount; ++morphGeometryIndex) - { - MorphGeometryEntry& morphGeometryEntry = morphGeometries[morphGeometryIndex]; - - GeometryData geometryData; - MorphDataMap::iterator morphDataPos = morphData.find(std::make_pair(morphGeometryEntry.geometryFileIndex, morphGeometryEntry.modelIndex)); - if (morphDataPos != morphData.end()) - { - source->ReadMorphGeometry(context, &geometryData, &modelData[morphGeometryEntry.geometryFileIndex], morphGeometryEntry.modelIndex, &(*morphDataPos).second, morphGeometryEntry.morphIndex, &materialData); - } - - WriteGeometryData(writer, morphGeometryEntry.name, morphGeometryEntry.morphName, geometryData, materialData, materialMaterialMap, materials); - } - - return true; - } - - void WriteExportNodeProperties(const IExportSource& source, XMLWriter& writer, const char* geomFilename, const IGeometryFileData::SProperties& properties) - { - XMLWriter::Element elem(writer, "extra"); - { - XMLWriter::Element elem(writer, "technique"); - elem.Attribute("profile", "CryEngine"); - { - std::string const filetypeStr = ExportFileTypeHelpers::CryFileTypeToString(properties.filetypeInt); - std::string props = std::string("fileType=") + filetypeStr; - if (properties.bDoNotMerge) - { - props += std::string("\r\n") + "DoNotMerge"; - } - if (properties.bUseCustomNormals) - { - props += std::string("\r\n") + "UseCustomNormals"; - } - if (properties.filetypeInt == CRY_FILE_TYPE_SKIN && properties.b8WeightsPerVertex) - { - props += std::string("\r\n") + "EightWeightsPerVertex"; - } - if (properties.bUseF32VertexFormat) - { - props += std::string("\r\n") + "UseF32VertexFormat"; - } - - props += std::string("\r\n") + std::string("CustomExportPath=") + properties.customExportPath; - XMLWriter::Element elem(writer, "properties"); - elem.Content(props); - } - } - - // Write special properties for importing to the XSI. - { - XMLWriter::Element elem(writer, "technique"); - elem.Attribute("profile", "XSI"); - { - XMLWriter::Element elem(writer, "XSI_CustomPSet"); - elem.Attribute("name", "ExportProperties"); - { - XMLWriter::Element elem(writer, "propagation"); - elem.Content("NODE"); - } - { - XMLWriter::Element elem(writer, "type"); - elem.Content("CryExportNodeProperties"); - } - { - XMLWriter::Element elem(writer, "XSI_Parameter"); - elem.Attribute("id", "Filetype"); - elem.Attribute("type", "Integer"); - elem.Attribute("value", properties.filetypeInt); - } - { - XMLWriter::Element elem(writer, "XSI_Parameter"); - elem.Attribute("id", "Filename"); - elem.Attribute("type", "Text"); - elem.Attribute("value", geomFilename); - } - { - XMLWriter::Element elem(writer, "XSI_Parameter"); - elem.Attribute("id", "Exportable"); - elem.Attribute("type", "Boolean"); - elem.Attribute("value", "1"); - } - { - XMLWriter::Element elem(writer, "XSI_Parameter"); - elem.Attribute("id", "MergeObjects"); - elem.Attribute("type", "Boolean"); - elem.Attribute("value", (!properties.bDoNotMerge)); - } - } - } - } - - - void WriteHierarchyRecurse( - XMLWriter& writer, - IExportContext* context, - int geometryFileIndex, - MaterialData& materialData, - const std::map& materialMaterialMap, - const std::vector& materials, - const ModelData& modelData, - int const modelIndex, - std::map, int>& modelGeometryMap, - std::vector& geometries, - std::map, int>& modelControllerMap, - std::vector& controllers, - std::map, int>& modelMorphControllerMap, - std::vector& morphControllers, - IExportSource* source, - ProgressRange& progressRange) - { - XMLWriter::Element nodeElement(writer, "node"); - nodeElement.Attribute("id", modelData.GetModelName(modelIndex)); // The ID must be unique. - - { - float translation[3]; - float rotation[3]; - float scaling[3]; - modelData.GetTranslationRotationScale(modelIndex, translation, rotation, scaling); - - // Write translation element. - { - XMLWriter::Element translateElement(writer, "translate"); - translateElement.Attribute("sid", "translation"); - translateElement.ContentArrayElement(translation[0]); - translateElement.ContentArrayElement(translation[1]); - translateElement.ContentArrayElement(translation[2]); - } - - // Write rotation elements. - for (int axisIndex = 0; axisIndex < 3; ++axisIndex) - { - XMLWriter::Element rotateElement(writer, "rotate"); - char sidBuffer[1024]; - sprintf(sidBuffer, "rotation_%c", 'z' - axisIndex); - rotateElement.Attribute("sid", sidBuffer); - rotateElement.ContentArrayElement(axisIndex == 2 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 1 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 0 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(rotation[2 - axisIndex] * 180.0f / 3.14159f); - } - - // Write scale elements - { - XMLWriter::Element scaleElement(writer, "scale"); - scaleElement.Attribute("sid", "scale"); - scaleElement.ContentArrayElement(scaling[0]); - scaleElement.ContentArrayElement(scaling[1]); - scaleElement.ContentArrayElement(scaling[2]); - } - } - - // If the node has a controller, write out the reference to it. - std::map, int>::iterator modelControllerMapPos = modelControllerMap.find(std::make_pair(geometryFileIndex, modelIndex)); - std::map, int>::iterator modelMorphControllerMapPos = modelMorphControllerMap.find(std::make_pair(geometryFileIndex, modelIndex)); - if (modelControllerMapPos != modelControllerMap.end()) - { - const std::string& controllerName = controllers[(*modelControllerMapPos).second].name; - XMLWriter::Element instanceControllerElement(writer, "instance_controller"); - instanceControllerElement.Attribute("url", "#" + controllerName); - - BindMaterials(writer, context, materialData, modelData, modelIndex, materialMaterialMap, materials, source); - } - else if (modelMorphControllerMapPos != modelMorphControllerMap.end()) - { - const std::string& controllerName = morphControllers[(*modelMorphControllerMapPos).second].name; - XMLWriter::Element instanceControllerElement(writer, "instance_controller"); - instanceControllerElement.Attribute("url", "#" + controllerName); - - BindMaterials(writer, context, materialData, modelData, modelIndex, materialMaterialMap, materials, source); - } - else - { - // If the node has geometry, write out the reference to it. - std::map, int>::iterator modelGeometryMapPos = modelGeometryMap.find(std::make_pair(geometryFileIndex, modelIndex)); - if (modelGeometryMapPos != modelGeometryMap.end()) - { - const std::string& geometryName = geometries[(*modelGeometryMapPos).second].name; - XMLWriter::Element instanceGeometryElement(writer, "instance_geometry"); - instanceGeometryElement.Attribute("url", std::string("#") + geometryName); - - BindMaterials(writer, context, materialData, modelData, modelIndex, materialMaterialMap, materials, source); - } - } - - // Recurse to the child nodes. - int childIndexCount = modelData.GetChildCount(modelIndex); - float progressRangeSlice = 1.0f / (childIndexCount > 0 ? float(childIndexCount) : 1.0f); - for (int childIndexIndex = 0; childIndexIndex < childIndexCount; ++childIndexIndex) - { - int childIndex = modelData.GetChildIndex(modelIndex, childIndexIndex); - WriteHierarchyRecurse(writer, context, geometryFileIndex, materialData, materialMaterialMap, materials, modelData, childIndex, modelGeometryMap, geometries, modelControllerMap, controllers, modelMorphControllerMap, morphControllers, source, ProgressRange(progressRange, progressRangeSlice)); - } - - // Write properties, HelperData - WriteExtraData(writer, modelData.GetHelperData(modelIndex), modelData.GetProperties(modelIndex)); - } - - void WriteHierarchy( - XMLWriter& writer, - IExportContext* context, - const GeometryFileData& geometryFileData, - MaterialData& materialData, - const std::map& materialMaterialMap, - const std::vector& materials, - const std::vector& modelData, - SkeletonDataMap& skeletonData, - std::map, int>& modelGeometryMap, - std::vector& geometries, - std::map, int>& modelControllerMap, - std::vector& controllers, - BoneDataMap& boneDataMap, - std::map, int>, int>& boneGeometryMap, - std::vector& boneGeometries, - std::map, int>& modelMorphControllerMap, - std::vector& morphControllers, - IExportSource* source, - ProgressRange& progressRange) - { - XMLWriter::Element libraryVisualScenesElement(writer, "library_visual_scenes"); - XMLWriter::Element visualSceneElement(writer, "visual_scene"); - visualSceneElement.Attribute("id", "visual_scene_0"); - visualSceneElement.Attribute("name", "untitled"); - - int geometryFileCount = geometryFileData.GetGeometryFileCount(); - float geometryFileRangeSlice = 1.0f / (geometryFileCount > 0 ? float(geometryFileCount) : 1.0f); - for (int geometryFileIndex = 0; geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - ProgressRange geometryFileRange(progressRange, geometryFileRangeSlice); - - // Make sure to write out a LumberyardExportNode - this is expected by the RC. - std::string nodeName; - - nodeName = geometryFileData.GetGeometryFileName(geometryFileIndex); - XMLWriter::Element nodeElement(writer, "node"); - nodeElement.Attribute("id", nodeName); - nodeElement.Attribute(g_LumberyardExportNodeTag, true); - - // Write translation element. - { - XMLWriter::Element translateElement(writer, "translate"); - translateElement.Attribute("sid", "translation"); - translateElement.Content("0 0 0"); - } - - // Write rotation elements. - { - XMLWriter::Element rotateElement(writer, "rotate"); - rotateElement.Attribute("sid", "rotation_z"); - rotateElement.Content("0 0 1 0"); - } - - { - XMLWriter::Element rotateElement(writer, "rotate"); - rotateElement.Attribute("sid", "rotation_y"); - rotateElement.Content("0 1 0 0"); - } - - { - XMLWriter::Element rotateElement(writer, "rotate"); - rotateElement.Attribute("sid", "rotation_x"); - rotateElement.Content("1 0 0 0"); - } - - // Write scale elements - { - XMLWriter::Element scaleElement(writer, "scale"); - scaleElement.Attribute("sid", "scale"); - scaleElement.Content("1 1 1"); - } - - { - ProgressRange modelProgressRange(geometryFileRange, 0.5f); - int rootIndexCount = modelData[geometryFileIndex].GetRootCount(); - float progressRangeSlice = 1.0f / (rootIndexCount > 0 ? float(rootIndexCount) : 1.0f); - for (int rootIndexIndex = 0; rootIndexIndex < rootIndexCount; ++rootIndexIndex) - { - int rootModelIndex = modelData[geometryFileIndex].GetRootIndex(rootIndexIndex); - WriteHierarchyRecurse(writer, context, geometryFileIndex, materialData, materialMaterialMap, materials, modelData[geometryFileIndex], rootModelIndex, modelGeometryMap, geometries, modelControllerMap, controllers, modelMorphControllerMap, morphControllers, source, ProgressRange(modelProgressRange, progressRangeSlice)); - } - } - - { - ProgressRange skeletonProgressRange(geometryFileRange, 0.5f); - //write the skeleton for the first model in the geometry file only - //for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - if (modelData[geometryFileIndex].GetModelCount() > 0) - { - int modelIndex = 0; - int modelCount = 1; - SkeletonDataMap::iterator skeletonDataPos = skeletonData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - SkeletonData& skeletonDataInstance = (*skeletonDataPos).second; - const std::vector& bones = (*boneDataMap.find(std::make_pair(geometryFileIndex, modelIndex))).second; - int rootIndexCount = skeletonDataInstance.GetRootCount(); - float progressRangeSlice = 1.0f / ((rootIndexCount > 0 ? float(rootIndexCount) : 1.0f) * modelCount); - for (int rootIndexIndex = 0; rootIndexIndex < rootIndexCount; ++rootIndexIndex) - { - int rootBoneIndex = skeletonDataInstance.GetRootIndex(rootIndexIndex); - WriteSkeletonRecurse(writer, context, geometryFileData.GetGeometryFileName(geometryFileIndex), skeletonDataInstance, rootBoneIndex, bones[rootBoneIndex].name, bones, boneGeometryMap, boneGeometries, geometryFileIndex, modelIndex, materialData, materialMaterialMap, materials, source, ProgressRange(skeletonProgressRange, progressRangeSlice * 0.5f)); - WritePhysSkeletonRecurse(writer, geometryFileData.GetGeometryFileName(geometryFileIndex), skeletonDataInstance, rootBoneIndex, bones, ProgressRange(skeletonProgressRange, progressRangeSlice * 0.5f), Matrix34(IDENTITY), Matrix34(IDENTITY)); - } - } - } - } - - // Write properties if they exist - WriteExportNodeProperties(*source, writer, geometryFileData.GetGeometryFileName(geometryFileIndex), geometryFileData.GetProperties(geometryFileIndex)); - } - } - - void WriteMetaData(IExportSource* pExportSource, XMLWriter& writer, ProgressRange& progressRange) - { - SExportMetaData metaData; - pExportSource->GetMetaData(metaData); - - XMLWriter::Element assetElement(writer, "asset"); - { - XMLWriter::Element contributorElement(writer, "contributor"); - contributorElement.Child("author", metaData.author); - contributorElement.Child("authoring_tool", metaData.authoring_tool); - contributorElement.Child("source_data", metaData.source_data); - } - - std::time_t time = std::time(0); - std::tm dateTime = *std::localtime(&time); - char scratchBuffer[1024]; - std::strftime(scratchBuffer, sizeof(scratchBuffer) / sizeof(scratchBuffer[0]), "%Y-%m-%dT%H:%M:%SZ", &dateTime); - assetElement.Child("created", scratchBuffer); - assetElement.Child("modified", scratchBuffer); - assetElement.Child("revision", metaData.revision); - { - XMLWriter::Element unitElement(writer, "unit"); - unitElement.Attribute("meter", metaData.fMeterUnit); - unitElement.Attribute("name", "meter"); - } - - switch (metaData.up_axis) - { - case SExportMetaData::X_UP: - assetElement.Child("up_axis", "X_UP"); - break; - case SExportMetaData::Y_UP: - assetElement.Child("up_axis", "Y_UP"); - break; - case SExportMetaData::Z_UP: - default: - assetElement.Child("up_axis", "Z_UP"); - break; - } - - int framesPerSecond = metaData.fFramesPerSecond <= 0.f ? 30 : static_cast(metaData.fFramesPerSecond); - sprintf_s(scratchBuffer, sizeof(scratchBuffer) / sizeof(scratchBuffer[0]), "%i", framesPerSecond); - XMLWriter::Element frameRateElement(writer, "framerate"); - frameRateElement.Attribute("fps", scratchBuffer); - } - - enum AnimationBoneParameter - { - AnimationBoneParameter_TransX, - AnimationBoneParameter_TransY, - AnimationBoneParameter_TransZ, - AnimationBoneParameter_RotX, - AnimationBoneParameter_RotY, - AnimationBoneParameter_RotZ, - AnimationBoneParameter_SclX, - AnimationBoneParameter_SclY, - AnimationBoneParameter_SclZ, - }; - const char* parameterStrings[] = { - "posx", - "posy", - "posz", - "rotx", - "roty", - "rotz", - "sclx", - "scly", - "sclz" - }; - const char* parameterTargetStrings[] = { - "translation.X", - "translation.Y", - "translation.Z", - "rotation_x.ANGLE", - "rotation_y.ANGLE", - "rotation_z.ANGLE", - "scale.X", - "scale.Y", - "scale.Z" - }; - struct AnimationBoneParameterEntry - { - std::string name; - int boneIndex; - AnimationBoneParameter parameter; - }; - struct AnimationEntry - { - std::string name; - int geometryFileIndex; - int modelIndex; - int animationIndex; - float start; - float stop; - std::vector parameters; - }; - void AddParametersRecursive(AnimationEntry& animation, AnimationData& animationData, const SkeletonData& skeletonData, int boneIndex, ProgressRange& progressRange) - { - for (AnimationBoneParameter parameter = AnimationBoneParameter_TransX; parameter <= AnimationBoneParameter_SclZ; parameter = AnimationBoneParameter(parameter + 1)) - { - animation.parameters.push_back(AnimationBoneParameterEntry()); - AnimationBoneParameterEntry& parameterEntry = animation.parameters.back(); - parameterEntry.boneIndex = boneIndex; - parameterEntry.parameter = parameter; - parameterEntry.name = animation.name + "-" + skeletonData.GetSafeName(boneIndex) + "_" + parameterStrings[parameter] + "-anim"; - - // Encode the flags as naming conventions. - unsigned modelFlags = animationData.GetModelFlags(boneIndex); - if (modelFlags & IAnimationData::ModelFlags_NoExport) - { - parameterEntry.name += "-NoExport"; - } - } - - int childIndexCount = skeletonData.GetChildCount(boneIndex); - float progressRangeSlice = 1.0f / (childIndexCount > 0 ? float(childIndexCount) : 1.0f); - for (int childIndexIndex = 0; childIndexIndex < childIndexCount; ++childIndexIndex) - { - AddParametersRecursive(animation, animationData, skeletonData, skeletonData.GetChildIndex(boneIndex, childIndexIndex), ProgressRange(progressRange, progressRangeSlice)); - } - } - - void AddParametersForNoSkeleton(AnimationEntry& animation, int modelIndex, const std::string& modelName, AnimationBoneParameter whichParameter) - { - for (AnimationBoneParameter parameter = whichParameter; parameter < whichParameter + 3; parameter = AnimationBoneParameter(parameter + 1)) - { - animation.parameters.push_back(AnimationBoneParameterEntry()); - AnimationBoneParameterEntry& parameterEntry = animation.parameters.back(); - parameterEntry.boneIndex = modelIndex; - parameterEntry.parameter = parameter; - parameterEntry.name = animation.name + "-" + modelName + "_" + parameterStrings[parameter] + "-anim"; - } - } - - void AddAnimationEntry(std::vector& animations, int animationIndex, int geometryFileIndex, int modelIndex, IExportSource* source, GeometryFileData& geometryFileData) - { - animations.push_back(AnimationEntry()); - AnimationEntry& animation = animations.back(); - animation.animationIndex = animationIndex; - animation.geometryFileIndex = geometryFileIndex; - animation.modelIndex = modelIndex; - - std::string safeAnimationName = source->GetAnimationName(&geometryFileData, geometryFileIndex, animationIndex); - std::replace(safeAnimationName.begin(), safeAnimationName.end(), ' ', '_'); - animation.name = safeAnimationName + std::string("-") + geometryFileData.GetGeometryFileName(geometryFileIndex); - source->GetAnimationTimeSpan(animation.start, animation.stop, animationIndex); - } - - void GenerateAnimationList(IExportContext* context, std::vector& animations, GeometryFileData& geometryFileData, const std::vector& modelData, SkeletonDataMap& skeletonData, IExportSource* source, ProgressRange& progressRange) - { - int geometryFileCount = geometryFileData.GetGeometryFileCount(); - float geometryFileProgressRangeSlice = 1.0f / (geometryFileCount > 0 ? float(geometryFileCount) : 1.0f); - for (int geometryFileIndex = 0; geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - ProgressRange geometryFileProgressRange(progressRange, geometryFileProgressRangeSlice); - - int modelCount = modelData[geometryFileIndex].GetModelCount(); - float modelProgressRangeSlice = 1.0f / (modelCount > 0 ? float(modelCount) : 1.0f); - - int animationCount = source->GetAnimationCount(); - float animProgressRangeSlice = 1.0f / (animationCount > 0 ? float(animationCount) : 1.0f); - for (int animationIndex = 0; animationIndex < animationCount; ++animationIndex) - { - ProgressRange animationProgressRange(geometryFileProgressRange, animProgressRangeSlice); - - if (skeletonData.empty()) // Non-skeletal mesh - { - AddAnimationEntry(animations, animationIndex, geometryFileIndex, -1, source, geometryFileData); - } - else // Skeletal mesh - { - AddAnimationEntry(animations, animationIndex, geometryFileIndex, 0, source, geometryFileData); - } - AnimationEntry& animation = animations.back(); - for (int modelIndex = 0; modelIndex < modelCount; ++modelIndex) - { - ProgressRange modelProgressRange(animationProgressRange, modelProgressRangeSlice); - - if (skeletonData.empty()) // Non-skeletal mesh - { - bool hasPos = source->HasValidPosController(&modelData[geometryFileIndex], modelIndex); - bool hasRot = source->HasValidRotController(&modelData[geometryFileIndex], modelIndex); - bool hasScl = source->HasValidSclController(&modelData[geometryFileIndex], modelIndex); - if (hasPos || hasRot || hasScl) - { - std::string modelName = modelData[geometryFileIndex].GetModelName(modelIndex); - std::replace_if(modelName.begin(), modelName.end(), std::isspace, '_'); - if (hasPos) - { - AddParametersForNoSkeleton(animation, modelIndex, modelName, - AnimationBoneParameter_TransX); - } - if (hasRot) - { - AddParametersForNoSkeleton(animation, modelIndex, modelName, - AnimationBoneParameter_RotX); - } - if (hasScl) - { - AddParametersForNoSkeleton(animation, modelIndex, modelName, - AnimationBoneParameter_SclX); - } - } - } - else // Skeletal mesh - { - ProgressRange animationProgressRange(modelProgressRange, animProgressRangeSlice); - - // Read the animation flags. - SkeletonDataMap::const_iterator skeletonDataPos = skeletonData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - const SkeletonData& skeletonDataInstance = (*skeletonDataPos).second; - float FPS = ExportGlobal::g_defaultFrameRate; // This is only used for reading flags, using the default since it will have no impact - AnimationData animationData(skeletonDataInstance.GetBoneCount(), FPS, 0); - source->ReadAnimationFlags(context, &animationData, &geometryFileData, &modelData[geometryFileIndex], modelIndex, &skeletonDataInstance, animationIndex); - - int rootIndexCount = skeletonDataInstance.GetRootCount(); - float rootProgressRangeSlice = 1.0f / (rootIndexCount > 0 ? float(rootIndexCount) : 1.0f); - for (int rootIndexIndex = 0; rootIndexIndex < rootIndexCount; ++rootIndexIndex) - { - ProgressRange rootProgressRange(animationProgressRange, rootProgressRangeSlice); - - int rootBoneIndex = skeletonDataInstance.GetRootIndex(rootIndexIndex); - - // Generate the list of animated parameters for this animation - by generating the names in one place, we can - // use them in both passes to refer to each other. - AddParametersRecursive(animation, animationData, skeletonDataInstance, rootBoneIndex, rootProgressRange); - } - } - } - } - } - } - } - - void GenerateSkinControllerList(IExportContext* context, std::vector& controllers, std::map, int>& modelControllerMap, SkeletonDataMap& skeletonData, GeometryFileData& geometryFileData, const std::vector& modelData, std::map, int>& modelGeometryMap, std::vector& geometries, ProgressRange& progressRange) - { - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - std::map, int>::iterator modelGeometryPos = modelGeometryMap.find(std::make_pair(geometryFileIndex, modelIndex)); - SkeletonDataMap::const_iterator skeletonDataPos = skeletonData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (skeletonDataPos != skeletonData.end() && modelGeometryPos != modelGeometryMap.end()) - { - const SkeletonData& skeleton = (*skeletonDataPos).second; - - int controllerIndex = int(controllers.size()); - controllers.resize(controllers.size() + 1); - - SkinControllerEntry& entry = controllers.back(); - char nameBuf[1024]; - sprintf(nameBuf, "controller_%d", controllerIndex); - entry.name = nameBuf; - entry.geometryFileIndex = geometryFileIndex; - entry.modelIndex = modelIndex; - - modelControllerMap.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), controllerIndex)); - } - } - } - } - - void GenerateMorphControllerList(IExportContext* context, std::vector& morphControllers, std::map, int>& modelMorphControllerMap, MorphDataMap& morphData, GeometryFileData& geometryFileData, const std::vector& modelData, std::map, int>& modelGeometryMap, std::vector& geometries, ProgressRange& progressRange) - { - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - std::map, int>::iterator modelGeometryPos = modelGeometryMap.find(std::make_pair(geometryFileIndex, modelIndex)); - MorphDataMap::const_iterator morphDataPos = morphData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (morphDataPos != morphData.end() && modelGeometryPos != modelGeometryMap.end()) - { - int controllerIndex = int(morphControllers.size()); - morphControllers.resize(morphControllers.size() + 1); - - MorphControllerEntry& entry = morphControllers.back(); - char nameBuf[1024]; - sprintf(nameBuf, "morphController_%d", controllerIndex); - entry.name = nameBuf; - entry.geometryFileIndex = geometryFileIndex; - entry.modelIndex = modelIndex; - - modelMorphControllerMap.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), controllerIndex)); - } - } - } - } - - void GenerateEffectsList(IExportContext* context, std::map& materialFXMap, std::vector& effects, MaterialData& materialData) - { - for (int materialIndex = 0, materialCount = materialData.GetMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - std::string name; - - std::string mtlName = materialData.GetName(materialIndex); - assert(!mtlName.empty()); - - name = mtlName; - - char buffer[100]; - const int id = materialData.GetID(materialIndex); - assert(id >= 0); - sprintf(buffer, "-%d", id + 1); - - name += buffer; - - name += "-submat"; - - name += "-effect"; - - const int effectIndex = int(effects.size()); - effects.push_back(EffectsEntry(name)); - - materialFXMap.insert(std::make_pair(materialIndex, effectIndex)); - } - } - - void GenerateMaterialList(IExportContext* context, std::map& materialMaterialMap, std::map& materialFXMap, std::vector& effects, std::vector& materials, MaterialData& materialData) - { - for (int materialIndex = 0, materialCount = materialData.GetMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - // Material needs to be named according to a specific format - this communicates information to - // the resource compiler about the settings to be used for the material. - // Format is: ____[__...] - - std::string name; - - std::string mtlName = materialData.GetName(materialIndex); - assert(!mtlName.empty()); - - std::string mtlProperties = materialData.GetProperties(materialIndex); - assert(!mtlProperties.empty()); - - name = mtlName; - - char buffer[100]; - const int id = materialData.GetID(materialIndex); - assert(id >= 0); - sprintf(buffer, "__%d", id + 1); - - name += buffer; - - name += "__"; - name += materialData.GetSubMatName(materialIndex); - - name += mtlProperties; - - const int index = int(materials.size()); - materials.push_back(MaterialEntry(name)); - - materialMaterialMap.insert(std::make_pair(materialIndex, index)); - } - } - - void GenerateGeometryList(IExportContext* context, std::map, int>& modelGeometryMap, std::vector& geometries, GeometryFileData& geometryFileData, const std::vector& modelData) - { - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - if (modelData[geometryFileIndex].HasGeometry(modelIndex)) - { - std::string geometryName = std::string(geometryFileData.GetGeometryFileName(geometryFileIndex)) + "_" + modelData[geometryFileIndex].GetModelName(modelIndex) + "_geometry"; - int geometryIndex = int(geometries.size()); - geometries.push_back(GeometryEntry(geometryName, geometryFileIndex, modelIndex)); - modelGeometryMap.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), geometryIndex)); - } - } - } - } - - void GenerateBoneGeometryList(IExportContext* context, std::map, int>, int>& boneGeometryMap, std::vector& boneGeometries, GeometryFileData& geometryFileData, const std::vector& modelData, SkeletonDataMap& skeletonData) - { - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - SkeletonDataMap::iterator skeletonDataPos = skeletonData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - SkeletonData& modelSkeletonData = (*skeletonDataPos).second; - for (int boneIndex = 0, boneCount = modelSkeletonData.GetBoneCount(); boneIndex < boneCount; ++boneIndex) - { - if (modelSkeletonData.HasGeometry(boneIndex)) - { - std::string geometryName = std::string(geometryFileData.GetGeometryFileName(geometryFileIndex)) + "_" + modelData[geometryFileIndex].GetModelName(modelIndex) + "_" + modelSkeletonData.GetSafeName(boneIndex) + "_boneGeometry"; - int geometryIndex = int(boneGeometries.size()); - boneGeometries.push_back(BoneGeometryEntry(geometryName, geometryFileIndex, modelIndex, boneIndex)); - boneGeometryMap.insert(std::make_pair(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), boneIndex), geometryIndex)); - } - } - } - } - } - } - - void GenerateMorphGeometryList(IExportContext* context, std::map, int>, int>& morphGeometryMap, std::vector& morphGeometries, GeometryFileData& geometryFileData, const std::vector& modelData, MorphDataMap& morphData) - { - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - MorphDataMap::iterator morphDataPos = morphData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (morphDataPos != morphData.end()) - { - MorphData& modelMorphData = (*morphDataPos).second; - for (int morphIndex = 0, morphCount = modelMorphData.GetMorphCount(); morphIndex < morphCount; ++morphIndex) - { - std::string geometryName = std::string(geometryFileData.GetGeometryFileName(geometryFileIndex)) + "_" + modelData[geometryFileIndex].GetModelName(modelIndex) + "_" + modelMorphData.GetMorphFullName(morphIndex) + "_morphGeometry"; - int geometryIndex = int(morphGeometries.size()); - morphGeometries.push_back(MorphGeometryEntry(geometryName, modelMorphData.GetMorphName(morphIndex), geometryFileIndex, modelIndex, morphIndex)); - morphGeometryMap.insert(std::make_pair(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), morphIndex), geometryIndex)); - } - } - } - } - } - - void GenerateIKPropertyList(const SkeletonData& skeletonData, int boneIndex, std::vector >& propertyList) - { - // Loop through each axis, adding the properties for this axis to the list. - for (int axis = 0; axis < 3; ++axis) - { - // Add the limit properties for this axis. - const char* extremeNames[] = {"min", "max"}; - for (int extreme = 0; extreme < 2; ++extreme) - { - std::string key; - key += ('x' + axis); - key += extremeNames[extreme]; - if (skeletonData.HasLimit(boneIndex, ISkeletonData::Axis(axis), ISkeletonData::Limit(extreme))) - { - float limit = skeletonData.GetLimit(boneIndex, ISkeletonData::Axis(axis), ISkeletonData::Limit(extreme)); - char buffer[1024]; - sprintf(buffer, "%f", limit * 180.0f / 3.14159f); // Convert to degrees. - propertyList.push_back(std::make_pair(key, buffer)); - } - } - - // Add the remaining properties. - const char* propNames[] = {"damping", "springangle", "springtension"}; - typedef bool (SkeletonData::* HasMember)(int boneIndex, ISkeletonData::Axis axis) const; - typedef float (SkeletonData::* GetMember)(int boneIndex, ISkeletonData::Axis axis) const; - HasMember hasMembers[] = {&SkeletonData::HasAxisDamping, &SkeletonData::HasSpringAngle, &SkeletonData::HasSpringTension}; - GetMember getMembers[] = {&SkeletonData::GetAxisDamping, &SkeletonData::GetSpringAngle, &SkeletonData::GetSpringTension}; - for (int propIndex = 0; propIndex < 3; ++propIndex) - { - std::string key; - key += ('x' + axis); - key += propNames[propIndex]; - if ((skeletonData.*(hasMembers[propIndex]))(boneIndex, ISkeletonData::Axis(axis))) - { - float value = (skeletonData.*(getMembers[propIndex]))(boneIndex, ISkeletonData::Axis(axis)); - char buffer[1024]; - sprintf(buffer, "%f", value); - propertyList.push_back(std::make_pair(key, buffer)); - } - } - } - } - - void GenerateBoneList(IExportContext* context, BoneDataMap& boneDataMap, const SkeletonDataMap& skeletonData, const std::vector& modelData) - { - for (SkeletonDataMap::const_iterator skeletonDataPos = skeletonData.begin(), skeletonDataEnd = skeletonData.end(); skeletonDataPos != skeletonDataEnd; ++skeletonDataPos) - { - int geometryFileIndex = (*skeletonDataPos).first.first; - int modelIndex = (*skeletonDataPos).first.second; - const SkeletonData& skeleton = (*skeletonDataPos).second; - - BoneDataMap::iterator boneDataPos = boneDataMap.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), std::vector())).first; - std::vector& bones = (*boneDataPos).second; - bones.resize(skeleton.GetBoneCount()); - - std::string modelName = modelData[geometryFileIndex].GetModelName(modelIndex); - - for (int boneIndex = 0, boneCount = skeleton.GetBoneCount(); boneIndex < boneCount; ++boneIndex) - { - typedef std::string BoneEntry::* BoneNamePtr; - BoneNamePtr boneNames[3] = {&BoneEntry::name, &BoneEntry::physName, &BoneEntry::parentFrameName}; - const char* suffixes[3] = {"", " Phys", " Phys ParentFrame"}; - std::vector > properties[3]; - - // Add the IK properties to the phys bone. - GenerateIKPropertyList(skeleton, boneIndex, properties[1]); - - for (int nameIndex = 0; nameIndex < 3; ++nameIndex) - { - std::string unsafeName = skeleton.GetName(boneIndex); - unsafeName += suffixes[nameIndex]; - bool containsSpaces = (unsafeName.find_first_of(" \t") != std::string::npos); - std::string name = unsafeName; - if (containsSpaces) - { - std::string overrideName = unsafeName; - std::replace_if(overrideName.begin(), overrideName.end(), std::isspace, '*'); - - std::string safeName = unsafeName; - std::replace_if(safeName.begin(), safeName.end(), std::isspace, '_'); - - name = safeName + "%" + modelName + "%" + "--PRprops_name=" + overrideName; - - // Add all the properties. - for (size_t propIndex = 0, propCount = properties[nameIndex].size(); propIndex < propCount; ++propIndex) - { - name += "_" + properties[nameIndex][propIndex].first + "=" + properties[nameIndex][propIndex].second; - } - - name += "__"; - } - else - { - name = unsafeName + "%" + modelName + "%"; - } - (bones[boneIndex].*(boneNames[nameIndex])) = name; - } - } - } - } - - void WriteAnimationList(XMLWriter& writer, std::vector& animations, ProgressRange& progressRange) - { - // Write out all the animations in the library_animation_clips element. Each animation lists the name and timespan - // of the clip, and the controllers for each model parameter. The actual animation data is written out in a separate pass. - XMLWriter::Element libraryAnimationClipsElement(writer, "library_animation_clips"); - - for (int animationEntryIndex = 0, animationEntryCount = int(animations.size()); animationEntryIndex < animationEntryCount; ++animationEntryIndex) - { - AnimationEntry& entry = animations[animationEntryIndex]; - - XMLWriter::Element animationClipElement(writer, "animation_clip"); - animationClipElement.Attribute("start", entry.start); - animationClipElement.Attribute("end", entry.stop); - animationClipElement.Attribute("id", entry.name); - - // For each parameter write out a reference to the controller for that parameter. - for (int parameterEntryIndex = 0, parameterEntryCount = int(entry.parameters.size()); parameterEntryIndex < parameterEntryCount; ++parameterEntryIndex) - { - AnimationBoneParameterEntry& parameter = entry.parameters[parameterEntryIndex]; - - XMLWriter::Element instanceAnimationElement(writer, "instance_animation"); - instanceAnimationElement.Attribute("url", std::string("#") + parameter.name); - } - } - } - - void WriteAnimationTags( - ProgressRange& animationEntryProgressRange, - const AnimationEntry& entry, - const IAnimationData* animationData, - XMLWriter& writer, - const std::vector* pBones, - const IModelData* pModelData) - { - // Loop through all the parameters of all the models. - ProgressRange writeAnimProgressRange(animationEntryProgressRange, 0.5f); - for (int parameterEntryIndex = 0, parameterEntryCount = int(entry.parameters.size()); parameterEntryIndex < parameterEntryCount; ++parameterEntryIndex) - { - const AnimationBoneParameterEntry& parameter = entry.parameters[parameterEntryIndex]; - - int frameCount = 0; - switch (parameter.parameter) - { - case AnimationBoneParameter_TransX: - case AnimationBoneParameter_TransY: - case AnimationBoneParameter_TransZ: - frameCount = animationData->GetFrameCountPos(parameter.boneIndex); - break; - case AnimationBoneParameter_RotX: - case AnimationBoneParameter_RotY: - case AnimationBoneParameter_RotZ: - frameCount = animationData->GetFrameCountRot(parameter.boneIndex); - break; - case AnimationBoneParameter_SclX: - case AnimationBoneParameter_SclY: - case AnimationBoneParameter_SclZ: - frameCount = animationData->GetFrameCountScl(parameter.boneIndex); - break; - } - - XMLWriter::Element animationElement(writer, "animation"); - animationElement.Attribute("id", parameter.name); - - std::string inputID = parameter.name + "-input"; - std::string outputID = parameter.name + "-output"; - std::string interpID = parameter.name + "-interp"; - std::string tcbID = parameter.name + "-tcb"; - std::string easeinoutID = parameter.name + "-easeinout"; - - // Write out the times. - { - XMLWriter::Element inputElement(writer, "source"); - inputElement.Attribute("id", inputID); - std::string arrayID = inputID + "-array"; - { - XMLWriter::Element array(writer, "float_array"); - array.Attribute("count", frameCount); - array.Attribute("id", arrayID); - - float floatBuffer[24]; - int bufferCount = 0; - for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) - { - switch (parameter.parameter) - { - case AnimationBoneParameter_TransX: - case AnimationBoneParameter_TransY: - case AnimationBoneParameter_TransZ: - floatBuffer[bufferCount++] = animationData->GetFrameTimePos(parameter.boneIndex, frameIndex); - break; - case AnimationBoneParameter_RotX: - case AnimationBoneParameter_RotY: - case AnimationBoneParameter_RotZ: - floatBuffer[bufferCount++] = animationData->GetFrameTimeRot(parameter.boneIndex, frameIndex); - break; - case AnimationBoneParameter_SclX: - case AnimationBoneParameter_SclY: - case AnimationBoneParameter_SclZ: - floatBuffer[bufferCount++] = animationData->GetFrameTimeScl(parameter.boneIndex, frameIndex); - break; - } - if (bufferCount == 24) - { - array.ContentArrayFloat24(floatBuffer, bufferCount); - bufferCount = 0; - } - } - if (bufferCount > 0) - { - array.ContentArrayFloat24(floatBuffer, bufferCount); - bufferCount = 0; - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", arrayID); - accessorElement.Attribute("count", frameCount); - accessorElement.Attribute("stride", 1); - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "TIME"); - paramElement.Attribute("type", "float"); - } - - // Write out the values. - { - XMLWriter::Element inputElement(writer, "source"); - inputElement.Attribute("id", outputID); - std::string arrayID = outputID + "-array"; - { - XMLWriter::Element array(writer, "float_array"); - array.Attribute("count", frameCount); - array.Attribute("id", arrayID); - - float floatBuffer[24]; - int bufferCount = 0; - for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) - { - const float* translation, * rotation, * scale; - switch (parameter.parameter) - { - case AnimationBoneParameter_TransX: - case AnimationBoneParameter_TransY: - case AnimationBoneParameter_TransZ: - animationData->GetFrameDataPos(parameter.boneIndex, frameIndex, translation); - floatBuffer[bufferCount++] = translation[parameter.parameter - AnimationBoneParameter_TransX]; - break; - case AnimationBoneParameter_RotX: - case AnimationBoneParameter_RotY: - case AnimationBoneParameter_RotZ: - animationData->GetFrameDataRot(parameter.boneIndex, frameIndex, rotation); - floatBuffer[bufferCount++] = rotation[parameter.parameter - AnimationBoneParameter_RotX]; - break; - case AnimationBoneParameter_SclX: - case AnimationBoneParameter_SclY: - case AnimationBoneParameter_SclZ: - animationData->GetFrameDataScl(parameter.boneIndex, frameIndex, scale); - floatBuffer[bufferCount++] = scale[parameter.parameter - AnimationBoneParameter_SclX]; - break; - } - if (bufferCount == 24) - { - array.ContentArrayFloat24(floatBuffer, bufferCount); - bufferCount = 0; - } - } - if (bufferCount > 0) - { - array.ContentArrayFloat24(floatBuffer, bufferCount); - bufferCount = 0; - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", arrayID); - accessorElement.Attribute("count", frameCount); - accessorElement.Attribute("stride", 1); - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "VALUE"); - paramElement.Attribute("type", "float"); - } - - // Write out the interpolation method. - { - XMLWriter::Element inputElement(writer, "source"); - inputElement.Attribute("id", interpID); - std::string arrayID = interpID + "-array"; - { - XMLWriter::Element array(writer, "Name_array"); - array.Attribute("count", frameCount); - array.Attribute("id", arrayID); - for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) - { - array.WriteDirectText(" CONSTANT"); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", arrayID); - accessorElement.Attribute("count", frameCount); - accessorElement.Attribute("stride", 1); - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "INTERPOLATION"); - paramElement.Attribute("type", "Name"); - } - - if (pModelData) // only for the non-skeletal animation - { - // Write out the TCB values. - { - const int stride = 3; - XMLWriter::Element inputElement(writer, "source"); - inputElement.Attribute("id", tcbID); - std::string arrayID = tcbID + "-array"; - { - XMLWriter::Element array(writer, "float_array"); - array.Attribute("count", frameCount * stride); - array.Attribute("id", arrayID); - for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) - { - IAnimationData::TCB tcb; - switch (parameter.parameter) - { - case AnimationBoneParameter_TransX: - case AnimationBoneParameter_TransY: - case AnimationBoneParameter_TransZ: - animationData->GetFrameTCBPos(parameter.boneIndex, frameIndex, tcb); - break; - case AnimationBoneParameter_RotX: - case AnimationBoneParameter_RotY: - case AnimationBoneParameter_RotZ: - animationData->GetFrameTCBRot(parameter.boneIndex, frameIndex, tcb); - break; - case AnimationBoneParameter_SclX: - case AnimationBoneParameter_SclY: - case AnimationBoneParameter_SclZ: - animationData->GetFrameTCBScl(parameter.boneIndex, frameIndex, tcb); - break; - } - array.ContentArrayElement(tcb.tension); - array.ContentArrayElement(tcb.continuity); - array.ContentArrayElement(tcb.bias); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", arrayID); - accessorElement.Attribute("count", frameCount); - accessorElement.Attribute("stride", stride); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "TENSION"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "CONTINUITY"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "BIAS"); - paramElement.Attribute("type", "float"); - } - } - - // Write out the ease-in/-out values. - { - const int stride = 2; - XMLWriter::Element inputElement(writer, "source"); - inputElement.Attribute("id", easeinoutID); - std::string arrayID = easeinoutID + "-array"; - { - XMLWriter::Element array(writer, "float_array"); - array.Attribute("count", frameCount * stride); - array.Attribute("id", arrayID); - for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) - { - IAnimationData::Ease ease; - switch (parameter.parameter) - { - case AnimationBoneParameter_TransX: - case AnimationBoneParameter_TransY: - case AnimationBoneParameter_TransZ: - animationData->GetFrameEaseInOutPos(parameter.boneIndex, frameIndex, ease); - break; - case AnimationBoneParameter_RotX: - case AnimationBoneParameter_RotY: - case AnimationBoneParameter_RotZ: - animationData->GetFrameEaseInOutRot(parameter.boneIndex, frameIndex, ease); - break; - case AnimationBoneParameter_SclX: - case AnimationBoneParameter_SclY: - case AnimationBoneParameter_SclZ: - animationData->GetFrameEaseInOutScl(parameter.boneIndex, frameIndex, ease); - break; - } - array.ContentArrayElement(ease.in); - array.ContentArrayElement(ease.out); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", arrayID); - accessorElement.Attribute("count", frameCount); - accessorElement.Attribute("stride", stride); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "EASE_IN"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "EASE_OUT"); - paramElement.Attribute("type", "float"); - } - } - } - - // Write out the sampler element. - std::string samplerID = parameter.name + "-sampler"; - { - XMLWriter::Element samplerElement(writer, "sampler"); - samplerElement.Attribute("id", samplerID); - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "INPUT"); - inputElement.Attribute("source", std::string("#") + inputID); - } - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "OUTPUT"); - inputElement.Attribute("source", std::string("#") + outputID); - } - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "INTERPOLATION"); - inputElement.Attribute("source", std::string("#") + interpID); - } - if (pModelData) // only for the non-skeletal animation - { - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "TCB"); - inputElement.Attribute("source", std::string("#") + tcbID); - } - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "EASE_IN_OUT"); - inputElement.Attribute("source", std::string("#") + easeinoutID); - } - } - } - - // Write out the channel element. - XMLWriter::Element channelElement(writer, "channel"); - channelElement.Attribute("source", std::string("#") + samplerID); - std::string targetName; - if (pBones) - { - targetName = (*pBones)[parameter.boneIndex].name; - } - else - { - assert(pModelData); - targetName = pModelData->GetModelName(parameter.boneIndex); - } - targetName = targetName + "/" + parameterTargetStrings[parameter.parameter]; - channelElement.Attribute("target", targetName); - } - } - - void WriteAnimationData( - IExportContext* context, - XMLWriter& writer, - std::vector& animations, - GeometryFileData& geometryFileData, - const std::vector& modelData, - SkeletonDataMap& skeletonData, - const BoneDataMap& boneDataMap, - IExportSource* source, - ProgressRange& progressRange) - { - XMLWriter::Element libraryAnimationsElement(writer, "library_animations"); - - int animationEntryCount = int(animations.size()); - float animationEntryProgressSlice = (1.0f / (animationEntryCount ? float(animationEntryCount) : 1.0f)); - for (int animationEntryIndex = 0; animationEntryIndex < animationEntryCount; ++animationEntryIndex) - { - float FPS = source->GetDCCFrameRate(); - ProgressRange animationEntryProgressRange(progressRange, animationEntryProgressSlice); - - AnimationEntry& entry = animations[animationEntryIndex]; - - if (skeletonData.empty()) // Non-skeletal mesh - { - IAnimationData* animationData = NULL; - { - ProgressRange readAnimProgressRange(animationEntryProgressRange, 0.5f); - animationData = source->ReadAnimation(context, &geometryFileData, &modelData[0], -1, NULL, animationEntryIndex, FPS); - } - - if (animationData) - { - WriteAnimationTags(animationEntryProgressRange, entry, animationData, writer, NULL, &modelData[0]); - delete animationData; - } - } - else // Skeletal mesh - { - // Read the animation data. - SkeletonDataMap::const_iterator skeletonDataPos = skeletonData.find(std::make_pair(entry.geometryFileIndex, entry.modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - IAnimationData* animationData = NULL; - const SkeletonData& skeletonDataInstance = (*skeletonDataPos).second; - { - ProgressRange readAnimProgressRange(animationEntryProgressRange, 0.5f); - - animationData = source->ReadAnimation(context, &geometryFileData, &modelData[entry.modelIndex], entry.modelIndex, &skeletonDataInstance, entry.animationIndex, FPS); - } - - // Look up the bone entries for this model. - BoneDataMap::const_iterator boneDataPos = boneDataMap.find(std::make_pair(entry.geometryFileIndex, entry.modelIndex)); - const std::vector& bones = (*boneDataPos).second; - - if (animationData) - { - WriteAnimationTags(animationEntryProgressRange, entry, animationData, writer, &bones, NULL); - delete animationData; - } - } - } - } - } - - void WriteEffects(XMLWriter& writer, std::vector& effects, ProgressRange& progressRange) - { - XMLWriter::Element libraryEffectsElement(writer, "library_effects"); - for (int effectIndex = 0, effectCount = int(effects.size()); effectIndex < effectCount; ++effectIndex) - { - XMLWriter::Element effectElement(writer, "effect"); - effectElement.Attribute("id", effects[effectIndex].name); - - // Write out dummy effects values. - XMLWriter::Element profileElement(writer, "profile_COMMON"); - XMLWriter::Element techniqueElement(writer, "technique"); - techniqueElement.Attribute("sid", "default"); - XMLWriter::Element phongElement(writer, "phong"); - { - XMLWriter::Element emissionElement(writer, "emission"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "emission"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(1.0f); - } - { - XMLWriter::Element ambientElement(writer, "ambient"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "ambient"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(1.0f); - } - { - XMLWriter::Element diffuseElement(writer, "diffuse"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "diffuse"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(1.0f); - } - { - XMLWriter::Element specularElement(writer, "specular"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "specular"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(1.0f); - } - { - XMLWriter::Element shininessElement(writer, "shininess"); - XMLWriter::Element floatElement(writer, "float"); - floatElement.Attribute("sid", "shininess"); - floatElement.ContentArrayElement(0.0f); - } - { - XMLWriter::Element reflectiveElement(writer, "reflective"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "reflective"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(1.0f); - } - { - XMLWriter::Element reflectivityElement(writer, "reflectivity"); - XMLWriter::Element floatElement(writer, "float"); - floatElement.Attribute("sid", "reflectivity"); - floatElement.ContentArrayElement(0.0f); - } - { - XMLWriter::Element transparentElement(writer, "transparent"); - transparentElement.Attribute("opaque", "RGB_ZERO"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "transparent"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - } - { - XMLWriter::Element transparencyElement(writer, "transparency"); - XMLWriter::Element floatElement(writer, "float"); - floatElement.Attribute("sid", "transparency"); - floatElement.ContentArrayElement(0.0f); - } - { - XMLWriter::Element refractionElement(writer, "index_of_refraction"); - XMLWriter::Element floatElement(writer, "float"); - floatElement.Attribute("sid", "index_of_refraction"); - floatElement.ContentArrayElement(0.0f); - } - } - } - - void WriteControllers( - XMLWriter& writer, - IExportContext* context, - IExportSource* exportSource, - std::vector& skinControllers, - std::vector& morphControllers, - std::map, int> modelMorphControllerMap, - GeometryFileData& geometryFileData, - const std::vector& modelData, - SkeletonDataMap& skeletonData, - MorphDataMap& morphData, - std::vector& morphGeometries, - std::map, int>, int>& morphGeometryMap, - std::vector& geometries, - std::map, int>& modelGeometryMap, - const BoneDataMap& boneDataMap, - ProgressRange& progressRange) - { - // - XMLWriter::Element libraryControllersElement(writer, "library_controllers"); - for (int controllerIndex = 0, controllerCount = int(skinControllers.size()); controllerIndex < controllerCount; ++controllerIndex) - { - SkinControllerEntry& controller = skinControllers[controllerIndex]; - SkeletonDataMap::iterator skeletonDataPos = skeletonData.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex)); - if (skeletonDataPos == skeletonData.end()) - { - continue; - } - - SkeletonData skeleton = (*skeletonDataPos).second; - - // - XMLWriter::Element controllerElement(writer, "controller"); - controllerElement.Attribute("id", controller.name); - - // - std::string geometryName; - bool sourceFound = false; - { - std::map, int>::const_iterator modelMorphControllerMapPos = modelMorphControllerMap.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex)); - int morphControllerIndex = (modelMorphControllerMapPos != modelMorphControllerMap.end() ? (*modelMorphControllerMapPos).second : -1); - geometryName = (morphControllerIndex >= 0 ? morphControllers[morphControllerIndex].name : "MISSING MORPH CONTROLLER NAME"); - sourceFound = (morphControllerIndex >= 0); - } - if (!sourceFound) - { - std::map, int>::const_iterator geometryMapPos = modelGeometryMap.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex)); - int geometryIndex = (geometryMapPos != modelGeometryMap.end() ? (*geometryMapPos).second : -1); - geometryName = (geometryIndex >= 0 ? geometries[geometryIndex].name : "MISSING GEOMETRY NAME"); - sourceFound = (geometryIndex >= 0); - } - XMLWriter::Element skinElement(writer, "skin"); - skinElement.Attribute("source", "#" + geometryName); - - // - // 1.000000 0.000000 0.000000 0.000000 - // 0.000000 1.000000 0.000000 0.000000 - // 0.000000 0.000000 1.000000 0.000000 - // 0.000000 0.000000 0.000000 1.000000 - // - { - XMLWriter::Element bindMatrixElement(writer, "bind_shape_matrix"); - bindMatrixElement.ContentArrayElement(1.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(1.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(1.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(1.0f); - } - - // - std::string jointsSourceName = controller.name + "_joints"; - { - XMLWriter::Element jointsSourceElement(writer, "source"); - jointsSourceElement.Attribute("id", jointsSourceName); - - // - const std::vector& bones = (*boneDataMap.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex))).second; - std::string arrayName = jointsSourceName + "_array"; - { - XMLWriter::Element idArrayElement(writer, "IDREF_array"); - idArrayElement.Attribute("id", arrayName); - idArrayElement.Attribute("count", skeleton.GetBoneCount()); - for (int boneIndex = 0, boneCount = skeleton.GetBoneCount(); boneIndex < boneCount; ++boneIndex) - { - idArrayElement.ContentArrayElement(bones[boneIndex].name); - } - } - - // - { - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - // - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("count", skeleton.GetBoneCount()); - accessorElement.Attribute("stride", 1); - accessorElement.Attribute("source", "#" + arrayName); - - // - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("type", std::string("IDREF")); - // - // - // - } - } - - // - std::string matricesSourceName = controller.name + "_matrices"; - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", matricesSourceName); - - // - std::string arrayName = matricesSourceName + "_array"; - { - XMLWriter::Element arrayElement(writer, "float_array"); - arrayElement.Attribute("id", arrayName); - arrayElement.Attribute("count", skeleton.GetBoneCount() * 16); - arrayElement.ContentLine(""); - for (int boneIndex = 0, boneCount = skeleton.GetBoneCount(); boneIndex < boneCount; ++boneIndex) - { - Vec3 scaleParams; - skeleton.GetScale((float*)&scaleParams, boneIndex); - Matrix44 scale = Matrix33::CreateScale(scaleParams); - - Ang3 rotationParams; - skeleton.GetRotation((float*)&rotationParams, boneIndex); - Matrix44 rotation = Matrix33::CreateRotationXYZ(rotationParams); - - Vec3 translationParams; - skeleton.GetTranslation((float*)&translationParams, boneIndex); - Matrix44 translation(IDENTITY); - translation.SetTranslation(translationParams); - - Matrix44 transform = translation * (rotation * scale); - transform.Invert(); - for (int i = 0; i < 4; ++i) - { - for (int j = 0; j < 4; ++j) - { - arrayElement.ContentArrayElement(transform(i, j)); - } - arrayElement.ContentLine(""); - } - } - } - - // - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - - // - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("count", skeleton.GetBoneCount()); - accessorElement.Attribute("stride", 16); - accessorElement.Attribute("source", "#" + arrayName); - - // - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("type", std::string("float4x4")); - - // - // - // - } - - // Read in the skinning info. - SkinningData skinningData; - exportSource->ReadSkinning(context, &skinningData, &modelData[controller.geometryFileIndex], controller.modelIndex, &skeleton); - - // Build a single array of weights. - std::vector weightsArray; - std::vector > weightIndexArray; - int vertexCount = skinningData.GetVertexCount(); - weightIndexArray.resize(vertexCount); - for (int vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) - { - int linkCount = skinningData.GetBoneLinkCount(vertexIndex); - weightIndexArray[vertexIndex].resize(linkCount); - for (int linkIndex = 0; linkIndex < linkCount; ++linkIndex) - { - int weightIndex = int(weightsArray.size()); - weightsArray.push_back(skinningData.GetWeight(vertexIndex, linkIndex)); - weightIndexArray[vertexIndex][linkIndex] = weightIndex; - } - } - - // - std::string weightsSourceName = controller.name + "_weights"; - { - XMLWriter::Element weightsSourceElement(writer, "source"); - weightsSourceElement.Attribute("id", weightsSourceName); - - // - int weightCount = int(weightsArray.size()); - std::string arrayName = weightsSourceName + "_array"; - { - XMLWriter::Element floatArrayElement(writer, "float_array"); - floatArrayElement.Attribute("count", weightCount); - floatArrayElement.Attribute("id", arrayName); - - for (int weightIndex = 0; weightIndex < weightCount; ++weightIndex) - { - floatArrayElement.ContentArrayElement(weightsArray[weightIndex]); - } - } - - // - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - - // - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("count", weightCount); - accessorElement.Attribute("stride", 1); - accessorElement.Attribute("source", "#" + arrayName); - - // - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("type", "float"); - - // - // - // - } - - { - // - XMLWriter::Element jointsElement(writer, "joints"); - - // - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "JOINT"); - inputElement.Attribute("source", "#" + jointsSourceName); - } - - // - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "INV_BIND_MATRIX"); - inputElement.Attribute("source", "#" + matricesSourceName); - } - - // - } - - { - // - XMLWriter::Element vertexWeightsElement(writer, "vertex_weights"); - int vertexCount = skinningData.GetVertexCount(); - vertexWeightsElement.Attribute("count", vertexCount); - - // - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "JOINT"); - inputElement.Attribute("offset", 0); - inputElement.Attribute("source", "#" + jointsSourceName); - } - - // - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "WEIGHT"); - inputElement.Attribute("offset", 1); - inputElement.Attribute("source", "#" + weightsSourceName); - } - - // - { - XMLWriter::Element vcountElement(writer, "vcount"); - - for (int vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) - { - vcountElement.ContentArrayElement(int(weightIndexArray[vertexIndex].size())); - } - } - - // - { - XMLWriter::Element vElement(writer, "v"); - vElement.ContentLine(""); - - for (int vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) - { - for (int linkIndex = 0, linkCount = int(weightIndexArray[vertexIndex].size()); linkIndex < linkCount; ++linkIndex) - { - vElement.ContentArrayElement(skinningData.GetBoneIndex(vertexIndex, linkIndex)); - vElement.ContentArrayElement(weightIndexArray[vertexIndex][linkIndex]); - } - vElement.ContentLine(""); - } - - // - } - // - } - - // - // - // - } - - // Write out the morph controllers. - for (int controllerIndex = 0, controllerCount = int(morphControllers.size()); controllerIndex < controllerCount; ++controllerIndex) - { - MorphControllerEntry& controller = morphControllers[controllerIndex]; - - // Find the geometry and morphs for the model. - std::map, int>::const_iterator modelGeometryMapPos = modelGeometryMap.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex)); - MorphDataMap::const_iterator modelMorphDataPos = morphData.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex)); - - if (modelGeometryMapPos != modelGeometryMap.end() && modelMorphDataPos != morphData.end()) - { - GeometryEntry& geometry = geometries[(*modelGeometryMapPos).second]; - const MorphData& modelMorphData = (*modelMorphDataPos).second; - - XMLWriter::Element controllerElement(writer, "controller"); - controllerElement.Attribute("id", controller.name); - XMLWriter::Element morphElement(writer, "morph"); - morphElement.Attribute("source", "#" + geometry.name); - - std::string targetsSourceID = controller.name + "-source_targets"; - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", targetsSourceID); - std::string arrayID = targetsSourceID + "-array"; - { - XMLWriter::Element idrefArrayElement(writer, "IDREF_array"); - idrefArrayElement.Attribute("id", arrayID); - idrefArrayElement.Attribute("count", modelMorphData.GetMorphCount()); - for (int morphIndex = 0, morphCount = modelMorphData.GetMorphCount(); morphIndex < morphCount; ++morphIndex) - { - // Look up the geometry for this morph. - //std::vector& morphGeometries - std::map, int>, int>::const_iterator morphGeometryMapPos = morphGeometryMap.find(std::make_pair(std::make_pair(controller.geometryFileIndex, controller.modelIndex), morphIndex)); - int morphGeometryIndex = (morphGeometryMapPos != morphGeometryMap.end() ? (*morphGeometryMapPos).second : -1); - if (morphGeometryIndex >= -1) - { - const MorphGeometryEntry& morphGeometry = morphGeometries[morphGeometryIndex]; - idrefArrayElement.ContentArrayElement(morphGeometry.name); - } - } - } - { - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", "#" + arrayID); - accessorElement.Attribute("count", modelMorphData.GetMorphCount()); - accessorElement.Attribute("offset", 0); - accessorElement.Attribute("stride", 1); - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "MORPH_TARGET"); - paramElement.Attribute("type", "IDREF"); - } - } - std::string weightsSourceID = controller.name + "-source_weights"; - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", weightsSourceID); - std::string arrayID = weightsSourceID + "-array"; - { - XMLWriter::Element floatArrayElement(writer, "float_array"); - floatArrayElement.Attribute("id", arrayID); - floatArrayElement.Attribute("count", modelMorphData.GetMorphCount()); - for (int morphIndex = 0, morphCount = modelMorphData.GetMorphCount(); morphIndex < morphCount; ++morphIndex) - { - // Look up the geometry for this morph. - //std::vector& morphGeometries - std::map, int>, int>::const_iterator morphGeometryMapPos = morphGeometryMap.find(std::make_pair(std::make_pair(controller.geometryFileIndex, controller.modelIndex), morphIndex)); - int morphGeometryIndex = (morphGeometryMapPos != morphGeometryMap.end() ? (*morphGeometryMapPos).second : -1); - if (morphGeometryIndex >= -1) - { - const MorphGeometryEntry& morphGeometry = morphGeometries[morphGeometryIndex]; - floatArrayElement.ContentArrayElement(0); - } - } - } - { - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", "#" + arrayID); - accessorElement.Attribute("count", modelMorphData.GetMorphCount()); - accessorElement.Attribute("offset", 0); - accessorElement.Attribute("stride", 1); - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "MORPH_WEIGHT"); - paramElement.Attribute("type", "float"); - } - } - XMLWriter::Element targestElement(writer, "targets"); - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "MORPH_TARGET"); - inputElement.Attribute("source", "#" + targetsSourceID); - } - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "MORPH_WEIGHT"); - inputElement.Attribute("source", "#" + weightsSourceID); - } - } - } - } - - void WriteImages(XMLWriter& writer, ProgressRange& progressRange) - { - XMLWriter::Element libraryImagesElement(writer, "library_images"); - } - - void WriteMaterials(XMLWriter& writer, MaterialData& materialData, std::map& materialFXMap, std::vector& effects, std::map& materialMaterialMap, std::vector& materials, ProgressRange& progressRange) - { - XMLWriter::Element libraryMaterialsElement(writer, "library_materials"); - - for (int materialIndex = 0, materialCount = materialData.GetMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - std::map::iterator materialMapPos = materialMaterialMap.find(materialIndex); - int entryIndex = (materialMapPos != materialMaterialMap.end() ? (*materialMapPos).second : -1); - std::map::iterator effectMapPos = materialFXMap.find(materialIndex); - int effectIndex = (effectMapPos != materialFXMap.end() ? (*effectMapPos).second : -1); - - if (entryIndex >= 0) - { - std::string name = materials[entryIndex].name; - XMLWriter::Element materialElement(writer, "material"); - materialElement.Attribute("id", name); - if (effectIndex >= 0) - { - XMLWriter::Element effectElement(writer, "instance_effect"); - effectElement.Attribute("url", "#" + effects[effectIndex].name); - } - } - } - } - - void WriteScene(XMLWriter& writer, ProgressRange& progressRange) - { - XMLWriter::Element sceneElement(writer, "scene"); - XMLWriter::Element instanceElement(writer, "instance_visual_scene"); - instanceElement.Attribute("url", "#visual_scene_0"); - } -} - -bool ColladaWriter::Write(IExportSource* source, IExportContext* context, IXMLSink* sink, ProgressRange& progressRange) -{ - if (FloatingPointHasPrecisionIssues()) - { - // If you hit this point, please change floating point settings in your VS project (and recompile it): - // ConfigurationProperties -> C/C++ -> CodeGeneration -> FloatingPointModel: "/fp:strict". - // Note: using "/fp:precise" doesn't help. - assert(0); - context->Log(ILogger::eSeverity_Error, "Cannot write Collada file, because the writer has precision issues. Contact Crytek tools programmers."); - return false; - } - - // Temporarily change the current locale so that floats get written out using periods rather than commas. - LocaleChanger localeChangeToStandard(LC_NUMERIC, "C"); - - // Create an object to format the xml. - XMLWriter writer(sink); - - // Export the animations to the file. - { - XMLWriter::Element colladaElement(writer, "COLLADA"); - colladaElement.Attribute("xmlns", "http://www.collada.org/2005/11/COLLADASchema"); - colladaElement.Attribute("version", "1.4.1"); - - // Write out the document metadata. - WriteMetaData(source, writer, ProgressRange(progressRange, 0.01f)); - - // Read the skeleton. - GeometryFileData geometryFileData; - MaterialData materialData; - std::vector modelData; - SkeletonDataMap skeletonData; - MorphDataMap morphData; - { - ProgressRange subProgressRange(progressRange, 0.1f); - - source->ReadGeometryFiles(context, &geometryFileData); - - bool ok = source->ReadMaterials(context, &geometryFileData, &materialData); - if (!ok) - { - return false; - } - - modelData.resize(geometryFileData.GetGeometryFileCount()); - - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - source->ReadModels(&geometryFileData, geometryFileIndex, &modelData[geometryFileIndex]); - - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - MorphDataMap::iterator morphDataPos = morphData.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), MorphData())).first; - source->ReadMorphs(context, &(*morphDataPos).second, &modelData[geometryFileIndex], modelIndex); - if ((*morphDataPos).second.GetMorphCount() == 0) - { - morphData.erase(morphDataPos); - } - - SkeletonDataMap::iterator skeletonDataPos = skeletonData.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), SkeletonData())).first; - if (!source->ReadSkeleton(&geometryFileData, geometryFileIndex, &modelData[geometryFileIndex], modelIndex, &materialData, &(*skeletonDataPos).second)) - { - skeletonData.erase(skeletonDataPos); - } - -#if !defined(HACK_HACK_FORCE_PELVIS_TO_BE_BONE_1_BECAUSE_LOADING_CODE_EXPECTS_IT) -# define HACK_HACK_FORCE_PELVIS_TO_BE_BONE_1_BECAUSE_LOADING_CODE_EXPECTS_IT 0 -#endif //!defined(HACK_HACK_FORCE_PELVIS_TO_BE_BONE_1_BECAUSE_LOADING_CODE_EXPECTS_IT) - - skeletonDataPos = skeletonData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - SkeletonData newData, & oldData = (*skeletonDataPos).second; - int pelvisIndex = -1; - for (int i = 0, count = oldData.GetBoneCount(); i < count; ++i) - { - pelvisIndex = ((_stricmp(oldData.GetName(i).c_str(), "Bip01 Pelvis") == 0) ? i : pelvisIndex); - } - if (pelvisIndex >= 0) - { - if (pelvisIndex != 1) - { - context->Log(ILogger::eSeverity_Warning, "`Bip01 Pelvis` should be the second bone."); - } -#if HACK_HACK_FORCE_PELVIS_TO_BE_BONE_1_BECAUSE_LOADING_CODE_EXPECTS_IT == 1 - std::vector oldToNewMap(oldData.GetBoneCount()); - std::vector newToOldMap(oldData.GetBoneCount()); - for (int i = 0, count = oldData.GetBoneCount(); i < count; ++i) - { - oldToNewMap[i] = i, newToOldMap[i] = i; - } - std::swap(oldToNewMap[pelvisIndex], oldToNewMap[1]); - std::swap(newToOldMap[pelvisIndex], newToOldMap[1]); - for (int i = 0, count = oldData.GetBoneCount(); i < count; ++i) - { - int oldIndex = newToOldMap[i]; - void* handle = oldData.GetBoneHandle(oldIndex); - std::string name = oldData.GetName(oldIndex); - int oldParentIndex = oldData.GetParentIndex(oldIndex); - int parentIndex = (oldParentIndex >= 0 ? oldToNewMap[oldParentIndex] : -1); - float translation[3], rotation[3], scale[3]; - oldData.GetTranslation(translation, oldIndex); - oldData.GetRotation(rotation, oldIndex); - oldData.GetScale(scale, oldIndex); - - int boneIndex = newData.AddBone(handle, name.c_str(), parentIndex); - newData.SetTranslation(boneIndex, translation); - newData.SetRotation(boneIndex, rotation); - newData.SetScale(boneIndex, scale); - - newData.SetHasGeometry(boneIndex, oldData.HasGeometry(oldIndex)); - - if (oldData.HasParentFrame(oldIndex)) - { - float parentFrameTranslation[3], parentFrameRotation[3], parentFrameScale[3]; - oldData.GetParentFrameTranslation(oldIndex, parentFrameTranslation); - oldData.GetParentFrameRotation(oldIndex, parentFrameRotation); - oldData.GetParentFrameScale(oldIndex, parentFrameScale); - newData.SetParentFrameTranslation(boneIndex, parentFrameTranslation); - newData.SetParentFrameRotation(boneIndex, parentFrameRotation); - newData.SetParentFrameScale(boneIndex, parentFrameScale); - } - for (int axisIndex = 0; axisIndex < 3; ++axisIndex) - { - ISkeletonData::Axis axis = ISkeletonData::Axis(axisIndex); - if (oldData.HasLimit(oldIndex, axis, ISkeletonData::LimitMin)) - { - newData.SetLimit(boneIndex, axis, ISkeletonData::LimitMin, oldData.GetLimit(oldIndex, axis, ISkeletonData::LimitMin)); - } - if (oldData.HasLimit(oldIndex, axis, ISkeletonData::LimitMax)) - { - newData.SetLimit(boneIndex, axis, ISkeletonData::LimitMax, oldData.GetLimit(oldIndex, axis, ISkeletonData::LimitMax)); - } - if (oldData.HasSpringTension(oldIndex, axis)) - { - newData.SetSpringTension(boneIndex, axis, oldData.GetSpringTension(oldIndex, axis)); - } - if (oldData.HasSpringAngle(oldIndex, axis)) - { - newData.SetSpringAngle(boneIndex, axis, oldData.GetSpringAngle(oldIndex, axis)); - } - if (oldData.HasAxisDamping(oldIndex, axis)) - { - newData.SetAxisDamping(boneIndex, axis, oldData.GetAxisDamping(oldIndex, axis)); - } - newData.SetPhysicalized(boneIndex, oldData.GetPhysicalized(oldIndex)); - } - } - (*skeletonDataPos).second = newData; -#endif //HACK_HACK_FORCE_PELVIS_TO_BE_BONE_1_BECAUSE_LOADING_CODE_EXPECTS_IT == 1 - } - } - } - } - } - - // Generate a list of fx to export. - std::map materialFXMap; - std::vector effects; - GenerateEffectsList(context, materialFXMap, effects, materialData); - - // Generate a list of geometry to export. - std::map, int> modelGeometryMap; - std::vector geometries; - GenerateGeometryList(context, modelGeometryMap, geometries, geometryFileData, modelData); - - // Generate a list of bone geometries to export. - std::map, int>, int> boneGeometryMap; - std::vector boneGeometries; - GenerateBoneGeometryList(context, boneGeometryMap, boneGeometries, geometryFileData, modelData, skeletonData); - - // Generate a list of morph geometries to export. - std::map, int>, int> morphGeometryMap; - std::vector morphGeometries; - GenerateMorphGeometryList(context, morphGeometryMap, morphGeometries, geometryFileData, modelData, morphData); - - BoneDataMap boneDataMap; - GenerateBoneList(context, boneDataMap, skeletonData, modelData); - - // Generate a list of animations to export. - std::vector animations; - GenerateAnimationList(context, animations, geometryFileData, modelData, skeletonData, source, ProgressRange(progressRange, 0.025f)); - - // Generate a list of morph controllers to export. - std::vector morphControllers; - std::map, int> modelMorphControllerMap; - GenerateMorphControllerList(context, morphControllers, modelMorphControllerMap, morphData, geometryFileData, modelData, modelGeometryMap, geometries, ProgressRange(progressRange, 0.0125f)); - - // Generate a list of skin controllers to export. - std::vector controllers; - std::map, int> modelControllerMap; - GenerateSkinControllerList(context, controllers, modelControllerMap, skeletonData, geometryFileData, modelData, modelGeometryMap, geometries, ProgressRange(progressRange, 0.0125f)); - - // Write out all the animations. - WriteAnimationList(writer, animations, ProgressRange(progressRange, 0.025f)); - WriteAnimationData(context, writer, animations, geometryFileData, modelData, skeletonData, boneDataMap, source, ProgressRange(progressRange, 0.475f)); - - // Write out all the effects. - WriteEffects(writer, effects, ProgressRange(progressRange, 0.01f)); - - // Write out the materials. - std::map materialMaterialMap; - std::vector materials; - GenerateMaterialList(context, materialMaterialMap, materialFXMap, effects, materials, materialData); - WriteMaterials(writer, materialData, materialFXMap, effects, materialMaterialMap, materials, ProgressRange(progressRange, 0.005f)); - - // Write out all the geometries. - bool ok = WriteGeometries(context, writer, geometries, geometryFileData, modelData, morphData, materialData, materials, materialMaterialMap, skeletonData, boneGeometries, boneGeometryMap, morphGeometryMap, morphGeometries, source, ProgressRange(progressRange, 0.2f)); - if (!ok) - { - return false; - } - - // Write out all the controllers. - WriteControllers(writer, context, source, controllers, morphControllers, modelMorphControllerMap, geometryFileData, modelData, skeletonData, morphData, morphGeometries, morphGeometryMap, geometries, modelGeometryMap, boneDataMap, ProgressRange(progressRange, 0.005f)); - - // Write out the list of models. - WriteHierarchy(writer, context, geometryFileData, materialData, materialMaterialMap, materials, modelData, skeletonData, modelGeometryMap, geometries, modelControllerMap, controllers, boneDataMap, boneGeometryMap, boneGeometries, modelMorphControllerMap, morphControllers, source, ProgressRange(progressRange, 0.1f)); - - // Write out all the other libraries. - WriteImages(writer, ProgressRange(progressRange, 0.01f)); - WriteScene(writer, ProgressRange(progressRange, 0.01f)); - } - - return true; -} diff --git a/Code/Tools/CryCommonTools/Export/ColladaWriter.h b/Code/Tools/CryCommonTools/Export/ColladaWriter.h deleted file mode 100644 index f880e8ce1b..0000000000 --- a/Code/Tools/CryCommonTools/Export/ColladaWriter.h +++ /dev/null @@ -1,32 +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_CRYCOMMONTOOLS_EXPORT_COLLADAWRITER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAWRITER_H -#pragma once - - -#include - -class IExportSource; -class IExportContext; -class ProgressRange; -class IXMLSink; - -class ColladaWriter -{ -public: - static bool Write(IExportSource* source, IExportContext* context, IXMLSink* sink, ProgressRange& progressRange); -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAWRITER_H diff --git a/Code/Tools/CryCommonTools/Export/ExportFileType.cpp b/Code/Tools/CryCommonTools/Export/ExportFileType.cpp deleted file mode 100644 index 8e552f361b..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportFileType.cpp +++ /dev/null @@ -1,66 +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 "StdAfx.h" -#include "ExportFileType.h" -#include "StringHelpers.h" - - -struct SFileTypeInfo -{ - int type; - const char* name; -}; - -SFileTypeInfo s_fileTypes[] = -{ - { CRY_FILE_TYPE_CGF, "cgf" }, - { CRY_FILE_TYPE_CGA, "cga" }, - { CRY_FILE_TYPE_CHR, "chr" }, - { CRY_FILE_TYPE_CAF, "caf" }, - { CRY_FILE_TYPE_ANM, "anm" }, - { CRY_FILE_TYPE_CHR | CRY_FILE_TYPE_CAF, "chrcaf" }, - { CRY_FILE_TYPE_CGA | CRY_FILE_TYPE_ANM, "cgaanm" }, - { CRY_FILE_TYPE_SKIN, "skin" }, - { CRY_FILE_TYPE_INTERMEDIATE_CAF, "i_caf" }, -}; - -static const int s_fileTypeCount = (sizeof(s_fileTypes) / sizeof(s_fileTypes[0])); - - -const char* ExportFileTypeHelpers::CryFileTypeToString(int const cryFileType) -{ - for (int i = 0; i < s_fileTypeCount; ++i) - { - if (s_fileTypes[i].type == cryFileType) - { - return s_fileTypes[i].name; - } - } - return "unknown"; -} - -int ExportFileTypeHelpers::StringToCryFileType(const char* str) -{ - if (str) - { - for (int i = 0; i < s_fileTypeCount; ++i) - { - if (_stricmp(str, s_fileTypes[i].name) == 0) - { - return s_fileTypes[i].type; - } - } - } - return CRY_FILE_TYPE_NONE; -} diff --git a/Code/Tools/CryCommonTools/Export/ExportFileType.h b/Code/Tools/CryCommonTools/Export/ExportFileType.h deleted file mode 100644 index 11d68f699b..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportFileType.h +++ /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. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTFILETYPE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTFILETYPE_H -#pragma once - - -enum CryFileType -{ - CRY_FILE_TYPE_NONE = 0x0000, - CRY_FILE_TYPE_CGF = 0x0001, - CRY_FILE_TYPE_CGA = 0x0002, - CRY_FILE_TYPE_CHR = 0x0004, - CRY_FILE_TYPE_CAF = 0x0008, - CRY_FILE_TYPE_ANM = 0x0010, - CRY_FILE_TYPE_SKIN = 0x0020, - CRY_FILE_TYPE_INTERMEDIATE_CAF = 0x0040, - //START: Add Skinned Geometry (.CGF) export type (for touch bending vegetation) - CRY_FILE_TYPE_SKIN_CGF = 0x0080, - //END: Add Skinned Geometry (.CGF) export type (for touch bending vegetation) -}; - -namespace ExportFileTypeHelpers -{ - const char* CryFileTypeToString(int cryFileType); - int StringToCryFileType(const char* str); -}; - - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTFILETYPE_H - diff --git a/Code/Tools/CryCommonTools/Export/ExportHelpers.h b/Code/Tools/CryCommonTools/Export/ExportHelpers.h deleted file mode 100644 index 00780696fe..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportHelpers.h +++ /dev/null @@ -1,83 +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_CRYCOMMONTOOLS_EXPORT_EXPORTHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTHELPERS_H -#pragma once - - -#include - -namespace ExportHelpers -{ - inline void GenerateTextureCoordinates(float* const res_s, float* const res_t, const float x, const float y, const float z) - { - const float ax = ::fabs(x); - const float ay = ::fabs(y); - const float az = ::fabs(z); - - float s = 0.0f; - float t = 0.0f; - - if (ax > 1e-3f || ay > 1e-3f || az > 1e-3f) - { - if (ax > ay) - { - if (ax > az) - { - // X rules - s = y / ax; - t = z / ax; - } - else - { - // Z rules - s = x / az; - t = y / az; - } - } - else - { - // ax <= ay - if (ay > az) - { - // Y rules - s = x / ay; - t = z / ay; - } - else - { - // Z rules - s = x / az; - t = y / az; - } - } - } - - // Now the texture coordinates are in the range [-1,1]. - // We want normalized [0,1] texture coordinates. - s = (s + 1) * 0.5f; - t = (t + 1) * 0.5f; - - if (res_s) - { - *res_s = s; - } - if (res_t) - { - *res_t = t; - } - } -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTHELPERS_H diff --git a/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.cpp b/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.cpp deleted file mode 100644 index 5fd0cb855f..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.cpp +++ /dev/null @@ -1,130 +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 "StdAfx.h" -#include "ExportSourceDecoratorBase.h" - -ExportSourceDecoratorBase::ExportSourceDecoratorBase(IExportSource* source) - : source(source) -{ -} - -void ExportSourceDecoratorBase::GetMetaData(SExportMetaData& metaData) const -{ - this->source->GetMetaData(metaData); -} - -std::string ExportSourceDecoratorBase::GetDCCFileName() const -{ - return this->source->GetDCCFileName(); -} - -std::string ExportSourceDecoratorBase::GetExportDirectory() const -{ - return this->source->GetExportDirectory(); -} - -void ExportSourceDecoratorBase::ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData) -{ - this->source->ReadGeometryFiles(context, geometryFileData); -} - -bool ExportSourceDecoratorBase::ReadMaterials(IExportContext* context, const IGeometryFileData* const geometryFileData, IMaterialData* materialData) -{ - return this->source->ReadMaterials(context, geometryFileData, materialData); -} - -void ExportSourceDecoratorBase::ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData) -{ - this->source->ReadModels(geometryFileData, geometryFileIndex, modelData); -} - -void ExportSourceDecoratorBase::ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* const modelData, int modelIndex, ISkeletonData* skeletonData) -{ - this->source->ReadSkinning(context, skinningData, modelData, modelIndex, skeletonData); -} - -bool ExportSourceDecoratorBase::ReadSkeleton(const IGeometryFileData* const geometryFileData, int geometryFileIndex, const IModelData* const modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData) -{ - return this->source->ReadSkeleton(geometryFileData, geometryFileIndex, modelData, modelIndex, materialData, skeletonData); -} - -int ExportSourceDecoratorBase::GetAnimationCount() const -{ - return this->source->GetAnimationCount(); -} - -std::string ExportSourceDecoratorBase::GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const -{ - return this->source->GetAnimationName(geometryFileData, geometryFileIndex, animationIndex); -} - -void ExportSourceDecoratorBase::GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const -{ - this->source->GetAnimationTimeSpan(start, stop, animationIndex); -} - -void ExportSourceDecoratorBase::ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* const geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const -{ - this->source->ReadAnimationFlags(context, animationData, geometryFileData, modelData, modelIndex, skeletonData, animationIndex); -} - -IAnimationData* ExportSourceDecoratorBase::ReadAnimation(IExportContext* context, const IGeometryFileData* const geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const -{ - return this->source->ReadAnimation(context, geometryFileData, modelData, modelIndex, skeletonData, animationIndex, fps); -} - -bool ExportSourceDecoratorBase::ReadGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* const modelData, const IMaterialData* const materialData, int modelIndex) -{ - return this->source->ReadGeometry(context, geometry, modelData, materialData, modelIndex); -} - -bool ExportSourceDecoratorBase::ReadGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, const IModelData* const modelData, const IMaterialData* const materialData, int modelIndex) const -{ - return this->source->ReadGeometryMaterialData(context, geometryMaterialData, modelData, materialData, modelIndex); -} - -bool ExportSourceDecoratorBase::ReadBoneGeometry(IExportContext* context, IGeometryData* geometry, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* const materialData) -{ - return this->source->ReadBoneGeometry(context, geometry, skeletonData, boneIndex, materialData); -} - -bool ExportSourceDecoratorBase::ReadBoneGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* const materialData) const -{ - return this->source->ReadBoneGeometryMaterialData(context, geometryMaterialData, skeletonData, boneIndex, materialData); -} - -void ExportSourceDecoratorBase::ReadMorphs(IExportContext* context, IMorphData* morphData, const IModelData* const modelData, int modelIndex) -{ - this->source->ReadMorphs(context, morphData, modelData, modelIndex); -} - -bool ExportSourceDecoratorBase::ReadMorphGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* const modelData, int modelIndex, const IMorphData* const morphData, int morphIndex, const IMaterialData* materialData) -{ - return this->source->ReadMorphGeometry(context, geometry, modelData, modelIndex, morphData, morphIndex, materialData); -} - -bool ExportSourceDecoratorBase::HasValidPosController(const IModelData* modelData, int modelIndex) const -{ - return this->source->HasValidPosController(modelData, modelIndex); -} - -bool ExportSourceDecoratorBase::HasValidRotController(const IModelData* modelData, int modelIndex) const -{ - return this->source->HasValidRotController(modelData, modelIndex); -} - -bool ExportSourceDecoratorBase::HasValidSclController(const IModelData* modelData, int modelIndex) const -{ - return this->source->HasValidSclController(modelData, modelIndex); -} diff --git a/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.h b/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.h deleted file mode 100644 index df5bea80ee..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.h +++ /dev/null @@ -1,54 +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_CRYCOMMONTOOLS_EXPORT_EXPORTSOURCEDECORATORBASE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSOURCEDECORATORBASE_H -#pragma once - - -#include "IExportSource.h" - -class ExportSourceDecoratorBase - : public IExportSource -{ -public: - ExportSourceDecoratorBase(IExportSource* source); - - virtual std::string GetResourceCompilerPath() const { return std::string(""); }; - virtual void GetMetaData(SExportMetaData& metaData) const; - virtual std::string GetDCCFileName() const; - virtual std::string GetExportDirectory() const; - virtual void ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData); - virtual bool ReadMaterials(IExportContext* context, const IGeometryFileData* geometryFileData, IMaterialData* materialData); - virtual void ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData); - virtual void ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* modelData, int modelIndex, ISkeletonData* skeletonData); - virtual bool ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData); - virtual int GetAnimationCount() const; - virtual std::string GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const; - virtual void GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const; - virtual void ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const; - virtual IAnimationData* ReadAnimation(IExportContext* context, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const; - virtual bool ReadGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* modelData, const IMaterialData* materialData, int modelIndex); - virtual bool ReadGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, const IModelData* modelData, const IMaterialData* materialData, int modelIndex) const; - virtual bool ReadBoneGeometry(IExportContext* context, IGeometryData* geometry, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* materialData); - virtual bool ReadBoneGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* materialData) const; - virtual void ReadMorphs(IExportContext* context, IMorphData* morphData, const IModelData* modelData, int modelIndex); - virtual bool ReadMorphGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* modelData, int modelIndex, const IMorphData* morphData, int morphIndex, const IMaterialData* materialData); - virtual bool HasValidPosController(const IModelData* modelData, int modelIndex) const; - virtual bool HasValidRotController(const IModelData* modelData, int modelIndex) const; - virtual bool HasValidSclController(const IModelData* modelData, int modelIndex) const; -protected: - IExportSource* source; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSOURCEDECORATORBASE_H diff --git a/Code/Tools/CryCommonTools/Export/ExportStatusWindow.cpp b/Code/Tools/CryCommonTools/Export/ExportStatusWindow.cpp deleted file mode 100644 index bc10a107e7..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportStatusWindow.cpp +++ /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. - -#include "StdAfx.h" -#include "ExportStatusWindow.h" -#include "UI/Win32GUI.h" -#include "StringHelpers.h" -#include -#include - -enum -{ - WM_USER_TASK_FINISHED = WM_USER + 53, - WM_USER_ACCEPTED -}; - -struct ThreadData -{ - ExportStatusWindow* statusWindow; - void (ExportStatusWindow::* initialize)(int width, int height, const std::vector >& tasks); - void (ExportStatusWindow::* run)(); - int width; - int height; - const std::vector >* tasks; - HANDLE initializedSemaphore; -}; -unsigned int __stdcall ThreadFunc(void* threadDataMemory) -{ - ThreadData* data = static_cast(threadDataMemory); - ExportStatusWindow* statusWindow = data->statusWindow; - void (ExportStatusWindow::* initialize)(int width, int height, const std::vector >& tasks) = data->initialize; - void (ExportStatusWindow::* run)() = data->run; - int width = data->width; - int height = data->height; - const std::vector >& tasks = *data->tasks; - HANDLE initializedSemaphore = data->initializedSemaphore; - - // Initialize the data. - (statusWindow->*initialize)(width, height, tasks); - - // Let the creating thread know that we have read the data - it is - // now safe for it to clear it. - ReleaseSemaphore(initializedSemaphore, 1, 0); - - // Perform the main thread processing. - (statusWindow->*run)(); - return 0; -} - -#pragma warning(push) -#pragma warning(disable: 4355) // 'this' : used in base member initializer list -ExportStatusWindow::ExportStatusWindow(int width, int height, const std::vector >& tasks) - : m_threadHandle(0) - , m_warningsEncountered(false) - , m_errorsEncountered(false) - , m_waitState(WaitState_WarningsAndErrors) - , m_okButtonSpacer(0, 0, 2000, 0) - , m_okButton(_T("OK"), this, &ExportStatusWindow::OkPressed) - , m_okButtonLayout(Layout::DirectionHorizontal) -{ - OutputDebugString(_T("Showing status window.\n")); - - Win32GUI::Initialize(); - - HANDLE initializedSemaphore = CreateSemaphore(0, 0, 1, 0); - - // Create a thread to handle the message pump for the window. - ThreadData threadData; - threadData.statusWindow = this; - threadData.initialize = &ExportStatusWindow::Initialize; - threadData.run = &ExportStatusWindow::Run; - threadData.width = width; - threadData.height = height; - threadData.tasks = &tasks; - threadData.initializedSemaphore = initializedSemaphore; - m_threadHandle = (HANDLE)_beginthreadex( - 0, //void *security, - 0, //unsigned stack_size, - ThreadFunc, //unsigned ( *start_address )( void * ), - &threadData, //void *arglist, - 0, //unsigned initflag, - 0); //unsigned *thrdaddr - - // Wait until the thread has read the data, since once we return the data will be lost. - WaitForSingleObject(initializedSemaphore, INFINITE); - CloseHandle(initializedSemaphore); -} -#pragma warning(pop) - -ExportStatusWindow::~ExportStatusWindow() -{ - OutputDebugString(_T("Hiding status window.\n")); - - // Tell the thread to exit and then wait for it to do so. - if (HWND hwnd = (HWND)m_frameWindow.GetHWND()) - { - PostMessage(hwnd, WM_USER_TASK_FINISHED, 0, 0); - m_okButton.Enable(true); - WaitForSingleObject((HANDLE)m_threadHandle, INFINITE); - } -} - -void ExportStatusWindow::Initialize(int width, int height, const std::vector >& tasks) -{ - OutputDebugString(_T("Beginning status window thread.\n")); - - for (int taskIndex = 0, taskCount = int(tasks.size()); taskIndex < taskCount; ++taskIndex) - { - m_taskList.AddTask(tasks[taskIndex].first, tasks[taskIndex].second); - } - - m_okButtonLayout.AddComponent(&m_okButtonSpacer); - m_okButtonLayout.AddComponent(&m_okButton); - m_okButton.Enable(false); - - m_frameWindow.AddComponent(&m_taskList); - m_frameWindow.AddComponent(&m_progressBar); - m_frameWindow.AddComponent(&m_logWindow); - m_frameWindow.AddComponent(&m_okButtonLayout); - m_frameWindow.Show(true, width, height); -} - -void ExportStatusWindow::Run() -{ - MSG msg; - BOOL status; - bool waitingAcceptance = false; - while ((status = GetMessage(&msg, HWND(0), UINT(0), UINT(0))) != 0) - { - if (status == -1) - { - break; - } - else if (msg.message == WM_USER_TASK_FINISHED) - { - if (m_waitState == WaitState_Always || - (m_waitState == WaitState_WarningsAndErrors && m_warningsEncountered || m_errorsEncountered) || - (m_waitState == WaitState_ErrorsOnly && m_errorsEncountered)) - { - waitingAcceptance = true; - } - else - { - break; - } - } - else if (waitingAcceptance && msg.message == WM_USER_ACCEPTED) - { - break; - } - else - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - - m_frameWindow.Show(false, 0, 0); - OutputDebugString(_T("Ending status window thread.\n")); -} - -void ExportStatusWindow::OkPressed() -{ - if (HWND hwnd = (HWND)m_frameWindow.GetHWND()) - { - PostMessage(hwnd, WM_USER_ACCEPTED, 0, 0); - } -} - -void ExportStatusWindow::SetWaitState(WaitState state) -{ - m_waitState = state; -} - -void ExportStatusWindow::AddTask(const std::string& id, const std::string& description) -{ - m_taskList.AddTask(id, description); -} - -void ExportStatusWindow::SetCurrentTask(const std::string& id) -{ - m_taskList.SetCurrentTask(id); -} - -void ExportStatusWindow::SetProgress(float progress) -{ - TCHAR buffer[2048]; - _sntprintf_s(buffer, sizeof(buffer), _TRUNCATE, _T("%.1f%% complete - exporting scene."), progress * 100); - m_frameWindow.SetCaption(buffer); - m_progressBar.SetProgress(progress); -} - -void ExportStatusWindow::Log(ILogger::ESeverity eSeverity, const char* message) -{ - if (eSeverity == ILogger::eSeverity_Error) - { - m_errorsEncountered = true; - } - else if (eSeverity == ILogger::eSeverity_Warning) - { - m_warningsEncountered = true; - } - - m_logWindow.Log(eSeverity, StringHelpers::ConvertString(message).c_str()); -} diff --git a/Code/Tools/CryCommonTools/Export/ExportStatusWindow.h b/Code/Tools/CryCommonTools/Export/ExportStatusWindow.h deleted file mode 100644 index d82869ae96..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportStatusWindow.h +++ /dev/null @@ -1,67 +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_CRYCOMMONTOOLS_EXPORT_EXPORTSTATUSWINDOW_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSTATUSWINDOW_H -#pragma once - - -#include "UI/FrameWindow.h" -#include "UI/ProgressBar.h" -#include "UI/TaskList.h" -#include "UI/LogWindow.h" -#include "UI/Spacer.h" -#include "UI/Layout.h" -#include "UI/PushButton.h" -#include "ILogger.h" - -class ExportStatusWindow -{ -public: - enum WaitState - { - WaitState_WarningsAndErrors, - WaitState_ErrorsOnly, - WaitState_Always, - WaitState_Never, - }; - - ExportStatusWindow(int width, int height, const std::vector >& tasks); - ~ExportStatusWindow(); - - void SetWaitState(WaitState state); - - void AddTask(const std::string& id, const std::string& description); - void SetCurrentTask(const std::string& id); - void SetProgress(float progress); - void Log(ILogger::ESeverity eSeverity, const char* message); - -private: - void Initialize(int width, int height, const std::vector >& tasks); - void Run(); - void OkPressed(); - - FrameWindow m_frameWindow; - TaskList m_taskList; - ProgressBar m_progressBar; - Spacer m_okButtonSpacer; - PushButton m_okButton; - Layout m_okButtonLayout; - LogWindow m_logWindow; - void* m_threadHandle; - bool m_warningsEncountered; - bool m_errorsEncountered; - WaitState m_waitState; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSTATUSWINDOW_H diff --git a/Code/Tools/CryCommonTools/Export/GeometryData.cpp b/Code/Tools/CryCommonTools/Export/GeometryData.cpp deleted file mode 100644 index dd82d90181..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryData.cpp +++ /dev/null @@ -1,82 +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 "StdAfx.h" -#include "GeometryData.h" - -GeometryData::GeometryData() -{ -} - -int GeometryData::AddPosition(float x, float y, float z) -{ - int positionIndex = int(this->positions.size()); - this->positions.push_back(Vector(x, y, z)); - return positionIndex; -} - -int GeometryData::AddNormal(float x, float y, float z) -{ - int normalIndex = int(this->normals.size()); - this->normals.push_back(Vector(x, y, z)); - return normalIndex; -} - -int GeometryData::AddTextureCoordinate(float u, float v) -{ - int textureCoordinateIndex = int(this->textureCoordinates.size()); - this->textureCoordinates.push_back(TextureCoordinate(u, v)); - return textureCoordinateIndex; -} - -int GeometryData::AddVertexColor(float r, float g, float b, float a) -{ - int vertexColorIndex = int(this->vertexColors.size()); - this->vertexColors.push_back(VertexColor(r, g, b, a)); - return vertexColorIndex; -} - -int GeometryData::AddPolygon(const int* indices, int mtlID) -{ - int polygonIndex = int(this->polygons.size()); - this->polygons.push_back(Polygon(mtlID, - Polygon::Vertex(indices[0], indices[1], indices[2], indices[3]), - Polygon::Vertex(indices[4], indices[5], indices[6], indices[7]), - Polygon::Vertex(indices[8], indices[9], indices[10], indices[11]))); - return polygonIndex; -} - -int GeometryData::GetNumberOfPositions() const -{ - return (int)this->positions.size(); -} - -int GeometryData::GetNumberOfNormals() const -{ - return (int)this->normals.size(); -} - -int GeometryData::GetNumberOfTextureCoordinates() const -{ - return (int)this->textureCoordinates.size(); -} - -int GeometryData::GetNumberOfVertexColors() const -{ - return (int)this->vertexColors.size(); -} - -int GeometryData::GetNumberOfPolygons() const -{ - return (int)this->polygons.size(); -} diff --git a/Code/Tools/CryCommonTools/Export/GeometryData.h b/Code/Tools/CryCommonTools/Export/GeometryData.h deleted file mode 100644 index aa42925128..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryData.h +++ /dev/null @@ -1,102 +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_CRYCOMMONTOOLS_EXPORT_GEOMETRYDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYDATA_H -#pragma once - - -#include "IGeometryData.h" -#include - -class GeometryData - : public IGeometryData -{ -public: - GeometryData(); - - // IGeometryData - virtual int AddPosition(float x, float y, float z); - virtual int AddNormal(float x, float y, float z); - virtual int AddTextureCoordinate(float u, float v); - virtual int AddVertexColor(float r, float g, float b, float a); - - virtual int AddPolygon(const int* indices, int mtlID); - - virtual int GetNumberOfPositions() const; - virtual int GetNumberOfNormals() const; - virtual int GetNumberOfTextureCoordinates() const; - virtual int GetNumberOfVertexColors() const; - - virtual int GetNumberOfPolygons() const; - - struct Vector - { - Vector(float x, float y, float z) - : x(x) - , y(y) - , z(z) {} - float x, y, z; - }; - - struct TextureCoordinate - { - TextureCoordinate(float u, float v) - : u(u) - , v(v) {} - float u, v; - }; - - struct VertexColor - { - VertexColor(float r, float g, float b, float a) - : r(r) - , g(g) - , b(b) - , a(a) {} - float r, g, b, a; - }; - - struct Polygon - { - struct Vertex - { - Vertex() {} - Vertex(int positionIndex, int normalIndex, int textureCoordinateIndex, int vertexColorIndex) - : positionIndex(positionIndex) - , normalIndex(normalIndex) - , textureCoordinateIndex(textureCoordinateIndex) - , vertexColorIndex(vertexColorIndex) {} - int positionIndex, normalIndex, textureCoordinateIndex, vertexColorIndex; - }; - - Polygon(int mtlID, const Vertex& v0, const Vertex& v1, const Vertex& v2) - : mtlID(mtlID) - { - v[0] = v0; - v[1] = v1; - v[2] = v2; - } - - int mtlID; - Vertex v[3]; - }; - - std::vector positions; - std::vector normals; - std::vector textureCoordinates; - std::vector vertexColors; - std::vector polygons; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYDATA_H diff --git a/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.cpp b/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.cpp deleted file mode 100644 index 3333e12ca6..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.cpp +++ /dev/null @@ -1,54 +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 "StdAfx.h" -#include "GeometryExportSourceAdapter.h" -#include "IGeometryFileData.h" -#include - -GeometryExportSourceAdapter::GeometryExportSourceAdapter(IExportSource* source, IGeometryFileData* geometryFileData, const std::vector& geometryFileIndices) - : ExportSourceDecoratorBase(source) - , m_geometryFileData(geometryFileData) - , m_geometryFileIndices(geometryFileIndices) -{ - assert(m_geometryFileIndices.size() <= m_geometryFileData->GetGeometryFileCount()); - for (size_t i = 0; i < m_geometryFileIndices.size(); ++i) - { - int const geometryFileIndex = m_geometryFileIndices[i]; - assert(geometryFileIndex >= 0 && geometryFileIndex < m_geometryFileData->GetGeometryFileCount()); - } -} - -void GeometryExportSourceAdapter::ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData) -{ - for (size_t i = 0; i < m_geometryFileIndices.size(); ++i) - { - int const geometryFileIndex = m_geometryFileIndices[i]; - int const newGeometryFileIndex = geometryFileData->AddGeometryFile( - m_geometryFileData->GetGeometryFileHandle(geometryFileIndex), - m_geometryFileData->GetGeometryFileName(geometryFileIndex), - m_geometryFileData->GetProperties(geometryFileIndex)); - } -} - -void GeometryExportSourceAdapter::ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData) -{ - assert(geometryFileIndex >= 0 && geometryFileIndex < m_geometryFileIndices.size()); - this->source->ReadModels(m_geometryFileData, m_geometryFileIndices[geometryFileIndex], modelData); -} - -bool GeometryExportSourceAdapter::ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData) -{ - assert(geometryFileIndex >= 0 && geometryFileIndex < m_geometryFileIndices.size()); - return this->source->ReadSkeleton(m_geometryFileData, m_geometryFileIndices[geometryFileIndex], modelData, modelIndex, materialData, skeletonData); -} diff --git a/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.h b/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.h deleted file mode 100644 index 7fb6ee081d..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYEXPORTSOURCEADAPTER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYEXPORTSOURCEADAPTER_H -#pragma once - - -#include "ExportSourceDecoratorBase.h" - -class GeometryExportSourceAdapter - : public ExportSourceDecoratorBase -{ -public: - GeometryExportSourceAdapter(IExportSource* source, IGeometryFileData* geometryFileData, const std::vector& geometryFileIndices); - - virtual void ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData); - virtual void ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData); - virtual bool ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData); - -private: - IGeometryFileData* m_geometryFileData; - std::vector m_geometryFileIndices; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYEXPORTSOURCEADAPTER_H diff --git a/Code/Tools/CryCommonTools/Export/GeometryFileData.cpp b/Code/Tools/CryCommonTools/Export/GeometryFileData.cpp deleted file mode 100644 index f67c0905dd..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryFileData.cpp +++ /dev/null @@ -1,59 +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 "StdAfx.h" -#include "GeometryFileData.h" - -int GeometryFileData::AddGeometryFile(const void* handle, const char* name, const SProperties& properties) -{ - const int geometryFileIndex = int(m_geometryFiles.size()); - m_geometryFiles.push_back(GeometryFileEntry(handle, name, properties)); - return geometryFileIndex; -} - -int GeometryFileData::GetGeometryFileCount() const -{ - return int(m_geometryFiles.size()); -} - -const void* GeometryFileData::GetGeometryFileHandle(int geometryFileIndex) const -{ - return m_geometryFiles[geometryFileIndex].handle; -} - -const char* GeometryFileData::GetGeometryFileName(int geometryFileIndex) const -{ - return m_geometryFiles[geometryFileIndex].name.c_str(); -} - -////////////////////////////////////////////////////////////////////////// -const IGeometryFileData::SProperties& GeometryFileData::GetProperties(int geometryFileIndex) const -{ - if (size_t(geometryFileIndex) >= m_geometryFiles.size()) - { - assert(0); - static SProperties badValue; - return badValue; - } - return m_geometryFiles[geometryFileIndex].properties; -} - -void GeometryFileData::SetProperties(int geometryFileIndex, const IGeometryFileData::SProperties& properties) -{ - if (size_t(geometryFileIndex) >= m_geometryFiles.size()) - { - assert(0); - return; - } - m_geometryFiles[geometryFileIndex].properties = properties; -} diff --git a/Code/Tools/CryCommonTools/Export/GeometryFileData.h b/Code/Tools/CryCommonTools/Export/GeometryFileData.h deleted file mode 100644 index 975a9cc5f7..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryFileData.h +++ /dev/null @@ -1,52 +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_CRYCOMMONTOOLS_EXPORT_GEOMETRYFILEDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYFILEDATA_H -#pragma once - - -#include "IGeometryFileData.h" -#include "STLHelpers.h" - -class GeometryFileData - : public IGeometryFileData -{ -public: - // IGeometryFileData - virtual int AddGeometryFile(const void* handle, const char* name, const SProperties& properties); - virtual const SProperties& GetProperties(int geometryFileIndex) const; - virtual void SetProperties(int geometryFileIndex, const SProperties& properties); - virtual int GetGeometryFileCount() const; - virtual const void* GetGeometryFileHandle(int geometryFileIndex) const; - virtual const char* GetGeometryFileName(int geometryFileIndex) const; - -private: - struct GeometryFileEntry - { - GeometryFileEntry(const void* a_handle, const char* a_name, const SProperties& a_properties) - : handle(a_handle) - , name(a_name) - , properties(a_properties) - { - } - - const void* handle; - std::string name; - SProperties properties; - }; - - std::vector m_geometryFiles; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYFILEDATA_H diff --git a/Code/Tools/CryCommonTools/Export/GeometryMaterialData.cpp b/Code/Tools/CryCommonTools/Export/GeometryMaterialData.cpp deleted file mode 100644 index ddc27daf52..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryMaterialData.cpp +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "GeometryMaterialData.h" - -void GeometryMaterialData::AddUsedMaterialIndex(int materialIndex) -{ - std::map::iterator usedMaterialPos = m_usedMaterialIndexIndexMap.find(materialIndex); - if (usedMaterialPos == m_usedMaterialIndexIndexMap.end()) - { - int materialIndexIndex = int(m_usedMaterialIndices.size()); - m_usedMaterialIndices.push_back(materialIndex); - m_usedMaterialIndexIndexMap.insert(std::make_pair(materialIndex, materialIndexIndex)); - } -} - -int GeometryMaterialData::GetUsedMaterialCount() const -{ - return int(m_usedMaterialIndices.size()); -} - -int GeometryMaterialData::GetUsedMaterialIndex(int usedMaterialIndex) const -{ - return m_usedMaterialIndices[usedMaterialIndex]; -} diff --git a/Code/Tools/CryCommonTools/Export/GeometryMaterialData.h b/Code/Tools/CryCommonTools/Export/GeometryMaterialData.h deleted file mode 100644 index b2fb5deb30..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryMaterialData.h +++ /dev/null @@ -1,35 +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_CRYCOMMONTOOLS_EXPORT_GEOMETRYMATERIALDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYMATERIALDATA_H -#pragma once - - -#include "IGeometryMaterialData.h" - -class GeometryMaterialData - : public IGeometryMaterialData -{ -public: - // IGeometryMaterialData - virtual void AddUsedMaterialIndex(int materialIndex); - virtual int GetUsedMaterialCount() const; - virtual int GetUsedMaterialIndex(int usedMaterialIndex) const; - -private: - std::vector m_usedMaterialIndices; - std::map m_usedMaterialIndexIndexMap; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYMATERIALDATA_H diff --git a/Code/Tools/CryCommonTools/Export/HelperData.h b/Code/Tools/CryCommonTools/Export/HelperData.h deleted file mode 100644 index adede42194..0000000000 --- a/Code/Tools/CryCommonTools/Export/HelperData.h +++ /dev/null @@ -1,41 +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_CRYCOMMONTOOLS_EXPORT_HELPERDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_HELPERDATA_H -#pragma once - - -struct SHelperData -{ -public: - enum EHelperType - { - eHelperType_UNKNOWN, - eHelperType_Point, - eHelperType_Dummy - }; - -public: - SHelperData() - : m_eHelperType(eHelperType_UNKNOWN) - { - } - -public: - EHelperType m_eHelperType; - float m_boundBoxMin[3]; // used for eHelperType_Dummy only - float m_boundBoxMax[3]; // used for eHelperType_Dummy only -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_HELPERDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IAnimationData.h b/Code/Tools/CryCommonTools/Export/IAnimationData.h deleted file mode 100644 index 4ac11abbb5..0000000000 --- a/Code/Tools/CryCommonTools/Export/IAnimationData.h +++ /dev/null @@ -1,96 +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_CRYCOMMONTOOLS_EXPORT_IANIMATIONDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IANIMATIONDATA_H -#pragma once - - -class IAnimationData -{ -public: - virtual ~IAnimationData() {} - - virtual void SetFrameData(int modelIndex, int frameIndex, float translation[3], float rotation[3], float scale[3]) = 0; - virtual void SetFrameCount(int frameCount) = 0; - - virtual void SetFrameTimePos(int modelIndex, int frameIndex, float time) = 0; - virtual void SetFrameDataPos(int modelIndex, int frameIndex, float translation[3]) = 0; - virtual void SetFrameCountPos(int modelIndex, int frameCount) = 0; - virtual void SetFrameTimeRot(int modelIndex, int frameIndex, float time) = 0; - virtual void SetFrameDataRot(int modelIndex, int frameIndex, float rotation[3]) = 0; - virtual void SetFrameCountRot(int modelIndex, int frameCount) = 0; - virtual void SetFrameTimeScl(int modelIndex, int frameIndex, float time) = 0; - virtual void SetFrameDataScl(int modelIndex, int frameIndex, float scale[3]) = 0; - virtual void SetFrameCountScl(int modelIndex, int frameCount) = 0; - - // For TCB & Ease-In/-Out support - struct TCB - { - float tension; - float continuity; - float bias; - - TCB() - : tension(0) - , continuity(0) - , bias(0) {} - }; - struct Ease - { - float in; - float out; - - Ease() - : in(0) - , out(0) {} - }; - virtual void SetFrameTCBPos(int modelIndex, int frameIndex, TCB tcb) = 0; - virtual void SetFrameTCBRot(int modelIndex, int frameIndex, TCB tcb) = 0; - virtual void SetFrameTCBScl(int modelIndex, int frameIndex, TCB tcb) = 0; - virtual void SetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease ease) = 0; - virtual void SetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease ease) = 0; - virtual void SetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease ease) = 0; - - enum ModelFlags - { - ModelFlags_NoExport = 1 << 0 - }; - - virtual void SetModelFlags(int modelIndex, unsigned modelFlags) = 0; - - virtual void GetFrameData(int modelIndex, int frameIndex, const float*& translation, const float*& rotation, const float*& scale) const = 0; - virtual int GetFrameCount() const = 0; - - virtual float GetFrameTimePos(int modelIndex, int frameIndex) const = 0; - virtual void GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const = 0; - virtual int GetFrameCountPos(int modelIndex) const = 0; - virtual float GetFrameTimeRot(int modelIndex, int frameIndex) const = 0; - virtual void GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const = 0; - virtual int GetFrameCountRot(int modelIndex) const = 0; - virtual float GetFrameTimeScl(int modelIndex, int frameIndex) const = 0; - virtual void GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const = 0; - virtual int GetFrameCountScl(int modelIndex) const = 0; - - // For TCB & Ease-In/-Out support - virtual void GetFrameTCBPos(int modelIndex, int frameIndex, TCB& tcb) const = 0; - virtual void GetFrameTCBRot(int modelIndex, int frameIndex, TCB& tcb) const = 0; - virtual void GetFrameTCBScl(int modelIndex, int frameIndex, TCB& tcb) const = 0; - virtual void GetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease& ease) const = 0; - virtual void GetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease& ease) const = 0; - virtual void GetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease& ease) const = 0; - - virtual unsigned GetModelFlags(int modelIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IANIMATIONDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IExportContext.h b/Code/Tools/CryCommonTools/Export/IExportContext.h deleted file mode 100644 index b2da053e6f..0000000000 --- a/Code/Tools/CryCommonTools/Export/IExportContext.h +++ /dev/null @@ -1,55 +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_CRYCOMMONTOOLS_EXPORT_IEXPORTCONTEXT_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTCONTEXT_H -#pragma once - - -#include -#include "Exceptions.h" -#include "ILogger.h" - -struct IPakSystem; -class ISettings; - -class IExportContext - : public ILogger -{ -public: - // Declare an exception type to report the case where the scene must be saved before exporting. - struct NeedSaveErrorTag {}; - typedef Exception NeedSaveError; - struct PakSystemErrorTag {}; - typedef Exception PakSystemError; - - virtual void SetProgress(float progress) = 0; - virtual void SetCurrentTask(const std::string& id) = 0; - virtual IPakSystem* GetPakSystem() = 0; - virtual ISettings* GetSettings() = 0; - virtual void GetRootPath(char* buffer, int bufferSizeInBytes) = 0; - -protected: - // ILogger - virtual void LogImpl(ILogger::ESeverity eSeverity, const char* message) = 0; -}; - -struct CurrentTaskScope -{ - CurrentTaskScope(IExportContext* context, const std::string& id) - : context(context) {context->SetCurrentTask(id); } - ~CurrentTaskScope() {context->SetCurrentTask(""); } - IExportContext* context; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTCONTEXT_H diff --git a/Code/Tools/CryCommonTools/Export/IExportSource.h b/Code/Tools/CryCommonTools/Export/IExportSource.h deleted file mode 100644 index 61051d6a2a..0000000000 --- a/Code/Tools/CryCommonTools/Export/IExportSource.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTSOURCE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTSOURCE_H -#pragma once - - -#include "Exceptions.h" - -class ISkeletonData; -class IAnimationData; -class IExportContext; -class IModelData; -class IGeometryFileData; -class IGeometryData; -class IMaterialData; -class ISkinningData; -class IMorphData; -class IGeometryMaterialData; - -namespace ExportGlobal -{ - const float g_defaultFrameRate = 30.f; -}; - -struct SExportMetaData -{ - enum EAxisUp - { - X_UP, - Y_UP, - Z_UP - }; - - char authoring_tool[128]; - char source_data[1024]; // Filename of the source. - char author[128]; // Name of the author. - char revision[64]; - EAxisUp up_axis; - float fMeterUnit; - float fFramesPerSecond; - - SExportMetaData() - { - fMeterUnit = 1.0f; - up_axis = Z_UP; - fFramesPerSecond = ExportGlobal::g_defaultFrameRate; - strcpy(authoring_tool, "CryENGINE Collada Exporter"); - strcpy(source_data, ""); - strcpy(author, ""); - strcpy(revision, "1.4.1"); - } -}; - -class IExportSource -{ -public: - virtual ~IExportSource() - { - } - virtual std::string GetResourceCompilerPath() const = 0; - virtual void GetMetaData(SExportMetaData& metaData) const = 0; - virtual std::string GetDCCFileName() const = 0; - virtual float GetDCCFrameRate() const{ return ExportGlobal::g_defaultFrameRate; } - virtual std::string GetExportDirectory() const = 0; - virtual void ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData) = 0; - virtual bool ReadMaterials(IExportContext* context, const IGeometryFileData* geometryFileData, IMaterialData* materialData) = 0; - virtual void ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData) = 0; - virtual void ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* modelData, int modelIndex, ISkeletonData* skeletonData) = 0; - virtual bool ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData) = 0; - virtual int GetAnimationCount() const = 0; - virtual std::string GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const = 0; - virtual void GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const = 0; - virtual void ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const = 0; - virtual IAnimationData* ReadAnimation(IExportContext* context, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const = 0; - virtual bool ReadGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* modelData, const IMaterialData* materialData, int modelIndex) = 0; - virtual bool ReadGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, const IModelData* modelData, const IMaterialData* materialData, int modelIndex) const = 0; - virtual bool ReadBoneGeometry(IExportContext* context, IGeometryData* geometry, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* materialData) = 0; - virtual bool ReadBoneGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* materialData) const = 0; - virtual void ReadMorphs(IExportContext* context, IMorphData* morphData, const IModelData* modelData, int modelIndex) = 0; - virtual bool ReadMorphGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* modelData, int modelIndex, const IMorphData* morphData, int morphIndex, const IMaterialData* materialData) = 0; - virtual bool HasValidPosController(const IModelData* modelData, int modelIndex) const = 0; - virtual bool HasValidRotController(const IModelData* modelData, int modelIndex) const = 0; - virtual bool HasValidSclController(const IModelData* modelData, int modelIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTSOURCE_H diff --git a/Code/Tools/CryCommonTools/Export/IExportWriter.h b/Code/Tools/CryCommonTools/Export/IExportWriter.h deleted file mode 100644 index 5f53f01049..0000000000 --- a/Code/Tools/CryCommonTools/Export/IExportWriter.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTWRITER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTWRITER_H -#pragma once - - -class IExportSource; -class IExportContext; - -class IExportWriter -{ -public: - virtual void Export(IExportSource* source, IExportContext* context) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTWRITER_H diff --git a/Code/Tools/CryCommonTools/Export/IGeometryData.h b/Code/Tools/CryCommonTools/Export/IGeometryData.h deleted file mode 100644 index 0869c97421..0000000000 --- a/Code/Tools/CryCommonTools/Export/IGeometryData.h +++ /dev/null @@ -1,35 +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_CRYCOMMONTOOLS_EXPORT_IGEOMETRYDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYDATA_H -#pragma once - - -class IGeometryData -{ -public: - virtual int AddPosition(float x, float y, float z) = 0; - virtual int AddNormal(float x, float y, float z) = 0; - virtual int AddTextureCoordinate(float u, float v) = 0; - virtual int AddVertexColor(float r, float g, float b, float a) = 0; - virtual int AddPolygon(const int* indices, int mtlID) = 0; - - virtual int GetNumberOfPositions() const = 0; - virtual int GetNumberOfNormals() const = 0; - virtual int GetNumberOfTextureCoordinates() const = 0; - virtual int GetNumberOfVertexColors() const = 0; - virtual int GetNumberOfPolygons() const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IGeometryFileData.h b/Code/Tools/CryCommonTools/Export/IGeometryFileData.h deleted file mode 100644 index bc81366ab2..0000000000 --- a/Code/Tools/CryCommonTools/Export/IGeometryFileData.h +++ /dev/null @@ -1,54 +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_CRYCOMMONTOOLS_EXPORT_IGEOMETRYFILEDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYFILEDATA_H -#pragma once - - -#include "ExportFileType.h" -#include - -class IGeometryFileData -{ -public: - struct SProperties - { - int filetypeInt; // combination of flags from CryFileType - bool bDoNotMerge; - bool bUseCustomNormals; - bool bUseF32VertexFormat; - bool b8WeightsPerVertex; - std::string customExportPath; - - SProperties() - : filetypeInt(CRY_FILE_TYPE_NONE) - , bDoNotMerge(false) - , bUseCustomNormals(false) - , bUseF32VertexFormat(false) - , b8WeightsPerVertex(false) - { - } - }; -public: - virtual int AddGeometryFile(const void* handle, const char* name, const SProperties& properties) = 0; - virtual const SProperties& GetProperties(int geometryFileIndex) const = 0; - virtual int GetGeometryFileCount() const = 0; - - // return an implementation-specific handle (for example a maya Dag Path string, or a MAX node name or whatever) - // its opaque to the exporter, but you can cast it yourself. - virtual const void* GetGeometryFileHandle(int geometryFileIndex) const = 0; - virtual const char* GetGeometryFileName(int geometryFileIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYFILEDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IGeometryMaterialData.h b/Code/Tools/CryCommonTools/Export/IGeometryMaterialData.h deleted file mode 100644 index 1c4eca55bf..0000000000 --- a/Code/Tools/CryCommonTools/Export/IGeometryMaterialData.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYMATERIALDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYMATERIALDATA_H -#pragma once - - -class IGeometryMaterialData -{ -public: - virtual void AddUsedMaterialIndex(int materialIndex) = 0; - virtual int GetUsedMaterialCount() const = 0; - virtual int GetUsedMaterialIndex(int usedMaterialIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYMATERIALDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IMaterialData.h b/Code/Tools/CryCommonTools/Export/IMaterialData.h deleted file mode 100644 index 82102eb3ce..0000000000 --- a/Code/Tools/CryCommonTools/Export/IMaterialData.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. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMATERIALDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMATERIALDATA_H -#pragma once - - -class IMaterialData -{ -public: - // the handle represents an implementation specific underlying handle (like a maya pointer to a string dag name). - virtual int AddMaterial(const char* name, int id, const void* handle, const char* properties) = 0; - virtual int AddMaterial(const char* name, int id, const char* subMatName, const void* handle, const char* properties) = 0; - virtual int GetMaterialCount() const = 0; - virtual const char* GetName(int materialIndex) const = 0; - virtual int GetID(int materialIndex) const = 0; - virtual const char* GetSubMatName(int materialIndex) const = 0; - virtual const void* GetHandle(int materialIndex) const = 0; - virtual const char* GetProperties(int materialIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMATERIALDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IModelData.h b/Code/Tools/CryCommonTools/Export/IModelData.h deleted file mode 100644 index 26ea7ed385..0000000000 --- a/Code/Tools/CryCommonTools/Export/IModelData.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMODELDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMODELDATA_H -#pragma once - - -#include "HelperData.h" -#include - -class IModelData -{ -public: - virtual int AddModel(const void* handle, const char* modelName, int parentModelIndex, bool geometry, const SHelperData& helperData, const std::string& propertiesString) = 0; - virtual int GetModelCount() const = 0; - virtual const void* GetModelHandle(int modelIndex) const = 0; - virtual const char* GetModelName(int modelIndex) const = 0; - virtual void SetTranslationRotationScale(int modelIndex, const float* translation, const float* rotation, const float* scale) = 0; - virtual void GetTranslationRotationScale(int modelIndex, float* translation, float* rotation, float* scale) const = 0; - virtual const SHelperData& GetHelperData(int modelIndex) const = 0; - virtual const std::string& GetProperties(int modelIndex) const = 0; - virtual bool IsRoot(int modelIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMODELDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IMorphData.h b/Code/Tools/CryCommonTools/Export/IMorphData.h deleted file mode 100644 index 26c4f05e71..0000000000 --- a/Code/Tools/CryCommonTools/Export/IMorphData.h +++ /dev/null @@ -1,29 +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_CRYCOMMONTOOLS_EXPORT_IMORPHDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMORPHDATA_H -#pragma once - - -class IMorphData -{ -public: - virtual void SetHandle(const void* handle) = 0; - virtual void AddMorph(const void* handle, const char* name, const char* fullName = NULL) = 0; - virtual const void* GetHandle() const = 0; - virtual int GetMorphCount() const = 0; - virtual const void* GetMorphHandle(int morphIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMORPHDATA_H diff --git a/Code/Tools/CryCommonTools/Export/ISkeletonData.h b/Code/Tools/CryCommonTools/Export/ISkeletonData.h deleted file mode 100644 index 75f3317343..0000000000 --- a/Code/Tools/CryCommonTools/Export/ISkeletonData.h +++ /dev/null @@ -1,56 +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_CRYCOMMONTOOLS_EXPORT_ISKELETONDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKELETONDATA_H -#pragma once - - -class ISkeletonData -{ -public: - enum Axis - { - AxisX, - AxisY, - AxisZ - }; - enum Limit - { - LimitMin, - LimitMax - }; - - virtual int AddBone(const void* handle, const char* name, int parentIndex) = 0; - virtual int FindBone(const char* name) const = 0; - virtual const void* GetBoneHandle(int boneIndex) const = 0; - virtual int GetBoneParentIndex(int boneIndex) const = 0; - virtual int GetBoneCount() const = 0; - virtual void SetTranslation(int boneIndex, const float* vec) = 0; - virtual void SetRotation(int boneIndex, const float* vec) = 0; - virtual void SetScale(int boneIndex, const float* vec) = 0; - virtual void SetParentFrameTranslation(int boneIndex, const float* vec) = 0; - virtual void SetParentFrameRotation(int boneIndex, const float* vec) = 0; - virtual void SetParentFrameScale(int boneIndex, const float* vec) = 0; - virtual void SetPhysicalized(int boneIndex, bool physicalized) = 0; - virtual void SetHasGeometry(int boneIndex, bool hasGeometry) = 0; - virtual void SetBoneProperties(int boneIndex, const char* propertiesString) = 0; - virtual void SetBoneGeomProperties(int boneIndex, const char* propertiesString) = 0; - - virtual void SetLimit(int boneIndex, Axis axis, Limit extreme, float limit) = 0; - virtual void SetSpringTension(int boneIndex, Axis axis, float springTension) = 0; - virtual void SetSpringAngle(int boneIndex, Axis axis, float springAngle) = 0; - virtual void SetAxisDamping(int boneIndex, Axis axis, float damping) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKELETONDATA_H diff --git a/Code/Tools/CryCommonTools/Export/ISkinningData.h b/Code/Tools/CryCommonTools/Export/ISkinningData.h deleted file mode 100644 index d20a3ad301..0000000000 --- a/Code/Tools/CryCommonTools/Export/ISkinningData.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKINNINGDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKINNINGDATA_H -#pragma once - - -class ISkinningData -{ -public: - virtual void SetVertexCount(int vertexCount) = 0; - virtual void AddWeight(int vertexIndex, int boneIndex, float weight) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKINNINGDATA_H diff --git a/Code/Tools/CryCommonTools/Export/MaterialData.cpp b/Code/Tools/CryCommonTools/Export/MaterialData.cpp deleted file mode 100644 index 243a0dcd93..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaterialData.cpp +++ /dev/null @@ -1,69 +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 "StdAfx.h" -#include "MaterialData.h" - -int MaterialData::AddMaterial(const char* name, int id, const void* handle, const char* properties) -{ - const int materialIndex = int(m_materials.size()); - m_materials.push_back(MaterialEntry(name, id, "submat", handle, properties)); - return materialIndex; -} - -int MaterialData::AddMaterial(const char* name, int id, const char* subMatName, const void* handle, const char* properties) -{ - const int materialIndex = int(m_materials.size()); - m_materials.push_back(MaterialEntry(name, id, subMatName, handle, properties)); - return materialIndex; -} - -int MaterialData::GetMaterialCount() const -{ - return int(m_materials.size()); -} - -const char* MaterialData::GetName(int materialIndex) const -{ - assert(materialIndex >= 0); - assert(materialIndex < int(m_materials.size())); - return m_materials[materialIndex].name.c_str(); -} - -int MaterialData::GetID(int materialIndex) const -{ - assert(materialIndex >= 0); - assert(materialIndex < int(m_materials.size())); - return m_materials[materialIndex].id; -} - -const char* MaterialData::GetSubMatName(int materialIndex) const -{ - assert(materialIndex >= 0); - assert(materialIndex < int(m_materials.size())); - return m_materials[materialIndex].subMatName.c_str(); -} - -const void* MaterialData::GetHandle(int materialIndex) const -{ - assert(materialIndex >= 0); - assert(materialIndex < int(m_materials.size())); - return m_materials[materialIndex].handle; -} - -const char* MaterialData::GetProperties(int materialIndex) const -{ - assert(materialIndex >= 0); - assert(materialIndex < int(m_materials.size())); - return m_materials[materialIndex].properties.c_str(); -} diff --git a/Code/Tools/CryCommonTools/Export/MaterialData.h b/Code/Tools/CryCommonTools/Export/MaterialData.h deleted file mode 100644 index 5916f56f9b..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaterialData.h +++ /dev/null @@ -1,56 +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_CRYCOMMONTOOLS_EXPORT_MATERIALDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALDATA_H -#pragma once - - -#include "IMaterialData.h" - -class MaterialData - : public IMaterialData -{ -public: - virtual int AddMaterial(const char* name, int id, const void* handle, const char* properties); - virtual int AddMaterial(const char* name, int id, const char* subMatName, const void* handle, const char* properties); - virtual int GetMaterialCount() const; - virtual const char* GetName(int materialIndex) const; - virtual int GetID(int materialIndex) const; - virtual const char* GetSubMatName(int materialIndex) const; - virtual const void* GetHandle(int materialIndex) const; - virtual const char* GetProperties(int materialIndex) const; - -private: - struct MaterialEntry - { - MaterialEntry(const char* a_name, int a_id, const char* a_subMatName, const void* a_handle, const char* a_properties) - : name(a_name) - , id(a_id) - , subMatName(a_subMatName) - , handle(a_handle) - , properties(a_properties ? a_properties : "") - { - } - - string name; - int id; - string subMatName; - const void* handle; - string properties; - }; - - std::vector m_materials; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALDATA_H diff --git a/Code/Tools/CryCommonTools/Export/MaterialHelpers.cpp b/Code/Tools/CryCommonTools/Export/MaterialHelpers.cpp deleted file mode 100644 index 82b9d1b88d..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaterialHelpers.cpp +++ /dev/null @@ -1,107 +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 "StdAfx.h" -#include "MaterialHelpers.h" -#include "StringHelpers.h" -#include "PathHelpers.h" -#include "properties.h" - -MaterialHelpers::MaterialInfo::MaterialInfo() -{ - this->id = -1; - this->name = ""; - this->physicalize = "None"; - this->diffuseTexture = ""; - this->diffuseColor[0] = this->diffuseColor[1] = this->diffuseColor[2] = 1.0f; - this->specularColor[0] = this->specularColor[1] = this->specularColor[2] = 1.0f; - this->emissiveColor[0] = this->emissiveColor[1] = this->emissiveColor[2] = 0.0f; -} - -std::string MaterialHelpers::PhysicsIDToString(const int physicsID) -{ - switch (physicsID) - { - case 1: - return "Default"; - break; - case 2: - return "ProxyNoDraw"; - break; - case 3: - return "NoCollide"; - break; - case 4: - return "Obstruct"; - break; - default: - return "None"; - break; - } -} - -bool MaterialHelpers::WriteMaterials(const std::string& filename, const std::vector& materialList) -{ - FILE* materialFile = fopen(filename.c_str(), "w"); - if (materialFile) - { - fprintf(materialFile, "\n"); - fprintf(materialFile, " \n"); - for (int i = 0; i < materialList.size(); i++) - { - const MaterialInfo& material = materialList[i]; - - fprintf(materialFile, " \n"); - - fprintf(materialFile, " \n"); - - // Write out diffuse texture. - if (material.diffuseTexture.length() > 0) - { - //fprintf( materialFile, " \n", ProcessTexturePath( material.diffuseTexture ).c_str() ); - fprintf(materialFile, " \n", material.diffuseTexture.c_str()); - fprintf(materialFile, " \n"); - fprintf(materialFile, " \n"); - } - - fprintf(materialFile, " \n"); - fprintf(materialFile, " \n"); - } - fprintf(materialFile, " \n"); - fprintf(materialFile, "\n"); - fclose(materialFile); - - return true; - } - else - { - return false; - } -} diff --git a/Code/Tools/CryCommonTools/Export/MaterialHelpers.h b/Code/Tools/CryCommonTools/Export/MaterialHelpers.h deleted file mode 100644 index 0afe9de48c..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaterialHelpers.h +++ /dev/null @@ -1,39 +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_CRYCOMMONTOOLS_EXPORT_MATERIALHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALHELPERS_H -#pragma once - - -namespace MaterialHelpers -{ - struct MaterialInfo - { - MaterialInfo();// : id(-1) { } - - std::string name; - std::string physicalize; - int id; - - float diffuseColor[3]; - float specularColor[3]; - float emissiveColor[3]; - std::string diffuseTexture; - }; - - std::string PhysicsIDToString(const int physicsID); - bool WriteMaterials(const std::string& filename, const std::vector& materialList); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALHELPERS_H diff --git a/Code/Tools/CryCommonTools/Export/MaxHelpers.h b/Code/Tools/CryCommonTools/Export/MaxHelpers.h deleted file mode 100644 index bbb1cf17b7..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaxHelpers.h +++ /dev/null @@ -1,138 +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_CRYCOMMONTOOLS_EXPORT_MAXHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXHELPERS_H -#pragma once - - -#include "CompileTimeAssert.h" -#include "PathHelpers.h" -#include "StringHelpers.h" - - -namespace MaxHelpers -{ - enum - { - kBadChar = '_' - }; - -#if !defined(MAX_PRODUCT_VERSION_MAJOR) - #error MAX_PRODUCT_VERSION_MAJOR is undefined -#elif (MAX_PRODUCT_VERSION_MAJOR >= 15) - COMPILE_TIME_ASSERT(sizeof(MCHAR) == 2); - #define MAX_MCHAR_SIZE 2 - typedef wstring MaxCompatibleString; -#elif (MAX_PRODUCT_VERSION_MAJOR >= 12) - COMPILE_TIME_ASSERT(sizeof(MCHAR) == 1); - #define MAX_MCHAR_SIZE 1 - typedef string MaxCompatibleString; -#else - #error 3dsMax 2009 and older are not supported anymore -#endif - - inline string CreateAsciiString(const char* s_ansi) - { - return StringHelpers::ConvertAnsiToAscii(s_ansi, kBadChar); - } - - - inline string CreateAsciiString(const wchar_t* s_utf16) - { - const string s_ansi = StringHelpers::ConvertUtf16ToAnsi(s_utf16, kBadChar); - return CreateAsciiString(s_ansi.c_str()); - } - - - inline string CreateUtf8String(const char* s_ansi) - { - return StringHelpers::ConvertAnsiToUtf8(s_ansi); - } - - - inline string CreateUtf8String(const wchar_t* s_utf16) - { - return StringHelpers::ConvertUtf16ToUtf8(s_utf16); - } - - - inline string CreateTidyAsciiNodeName(const char* s_ansi) - { - const size_t len = strlen(s_ansi); - - string res; - res.reserve(len); - - for (size_t i = 0; i < len; ++i) - { - char c = s_ansi[i]; - if (c < ' ' || c >= 127) - { - c = kBadChar; - } - res.append(1, c); - } - return res; - } - - - inline string CreateTidyAsciiNodeName(const wchar_t* s_utf16) - { - const string s_ansi = StringHelpers::ConvertUtf16ToAnsi(s_utf16, kBadChar); - return CreateTidyAsciiNodeName(s_ansi.c_str()); - ; - } - - - inline MSTR CreateMaxStringFromAscii(const char* s_ascii) - { -#if (MAX_MCHAR_SIZE == 2) - return MSTR(StringHelpers::ConvertAsciiToUtf16(s_ascii).c_str()); -#else - return MSTR(s_ascii); -#endif - } - - - inline MaxCompatibleString CreateMaxCompatibleStringFromAscii(const char* s_ascii) - { -#if (MAX_MCHAR_SIZE == 2) - return StringHelpers::ConvertAsciiToUtf16(s_ascii); -#else - return MaxCompatibleString(s_ascii); -#endif - } - - - inline string GetAbsoluteAsciiPath(const char* s_ansi) - { - if (!s_ansi || !s_ansi[0]) - { - return string(); - } - return PathHelpers::GetAbsoluteAsciiPath(StringHelpers::ConvertAnsiToUtf16(s_ansi).c_str()); - } - - - inline string GetAbsoluteAsciiPath(const wchar_t* s_utf16) - { - if (!s_utf16 || !s_utf16[0]) - { - return string(); - } - return PathHelpers::GetAbsoluteAsciiPath(s_utf16); - } -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXHELPERS_H diff --git a/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.cpp b/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.cpp deleted file mode 100644 index 2afe2ca0b0..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.cpp +++ /dev/null @@ -1,99 +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 "StdAfx.h" -#include "MaxUserPropertyHelpers.h" -#include "StringHelpers.h" -#include "MaxHelpers.h" - - -std::string MaxUserPropertyHelpers::GetNodeProperties(INode* node) -{ - if (node == 0) - { - return std::string(); - } - - MSTR buf; - node->GetUserPropBuffer(buf); - - return MaxHelpers::CreateAsciiString(buf); -} - - -std::string MaxUserPropertyHelpers::GetStringNodeProperty(INode* node, const char* name, const char* defaultValue) -{ - if (node == 0) - { - return defaultValue; - } - - MSTR val; - if (!node->GetUserPropString(MaxHelpers::CreateMaxStringFromAscii(name), val)) - { - return defaultValue; - } - - return MaxHelpers::CreateAsciiString(val); -} - - -float MaxUserPropertyHelpers::GetFloatNodeProperty(INode* node, const char* name, float defaultValue) -{ - if (node == 0) - { - return defaultValue; - } - - float val; - if (!node->GetUserPropFloat(MaxHelpers::CreateMaxStringFromAscii(name), val)) - { - return defaultValue; - } - - return val; -} - - -int MaxUserPropertyHelpers::GetIntNodeProperty(INode* node, const char* name, int defaultValue) -{ - if (node == 0) - { - return defaultValue; - } - - int val; - if (!node->GetUserPropInt(MaxHelpers::CreateMaxStringFromAscii(name), val)) - { - return defaultValue; - } - - return val; -} - - -bool MaxUserPropertyHelpers::GetBoolNodeProperty(INode* node, const char* name, bool defaultValue) -{ - if (node == 0) - { - return defaultValue; - } - - BOOL val; - if (!node->GetUserPropBool(MaxHelpers::CreateMaxStringFromAscii(name), val)) - { - return defaultValue; - } - - return (val != 0); -} diff --git a/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.h b/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.h deleted file mode 100644 index efef23e167..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.h +++ /dev/null @@ -1,32 +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_CRYCOMMONTOOLS_EXPORT_MAXUSERPROPERTYHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXUSERPROPERTYHELPERS_H -#pragma once - - -#include - -class INode; - -namespace MaxUserPropertyHelpers -{ - std::string GetNodeProperties(INode* node); - std::string GetStringNodeProperty(INode* node, const char* name, const char* defaultValue); - float GetFloatNodeProperty(INode* node, const char* name, float defaultValue); - int GetIntNodeProperty(INode* node, const char* name, int defaultValue); - bool GetBoolNodeProperty(INode* node, const char* name, bool defaultValue); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXUSERPROPERTYHELPERS_H diff --git a/Code/Tools/CryCommonTools/Export/MeshUtils.h b/Code/Tools/CryCommonTools/Export/MeshUtils.h deleted file mode 100644 index 81b456bffb..0000000000 --- a/Code/Tools/CryCommonTools/Export/MeshUtils.h +++ /dev/null @@ -1,914 +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_CRYCOMMONTOOLS_EXPORT_MESHUTILS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MESHUTILS_H -#pragma once - - -#include "BaseTypes.h" // uint8 -#include "Cry_Vector3.h" // Vec3 -#include "IIndexedMesh.h" // CMesh -namespace MeshUtils -{ - struct Face - { - int vertexIndex[3]; - }; - - struct Color - { - uint8 r; - uint8 g; - uint8 b; - }; - - // Stores linking of a vertex to bone(s) - class VertexLinks - { - public: - struct Link - { - int boneId; - float weight; - Vec3 offset; - - Link() - : boneId(-1) - , weight(-1.0f) - , offset(0.0f, 0.0f, 0.0f) - { - } - }; - - enum ESort - { - eSort_ByWeight, - eSort_ByBoneId, - }; - - public: - std::vector links; - - public: - // minWeightToDelete: links with weights <= minWeightToDelete will be deleted - const char* Normalize(ESort eSort, const float minWeightToDelete, const int maxLinkCount) - { - if (minWeightToDelete < 0 || minWeightToDelete >= 1) - { - return "Bad minWeightToDelete passed"; - } - if (maxLinkCount <= 0) - { - return "Bad maxLinkCount passed"; - } - - // Merging links with matching bone ids - { - DeleteByWeight(0.0f); - - if (links.empty()) - { - return "All bone links of a vertex have zero weight"; - } - - std::sort(links.begin(), links.end(), CompareLinksByBoneId); - - size_t dst = 0; - for (size_t i = 1; i < links.size(); ++i) - { - if (links[i].boneId == links[dst].boneId) - { - const float w0 = links[dst].weight; - const float w1 = links[i].weight; - const float a = w0 / (w0 + w1); - links[dst].offset = links[dst].offset * a + links[i].offset * (1 - a); - links[dst].weight = w0 + w1; - } - else - { - links[++dst] = links[i]; - } - } - - links.resize(dst + 1); - } - - // Deleting links, normalizing link weights. - // - // Note: we produce meaningful results even in cases like this: - // input weights are { 0.03, 0.01 }, minWeightTodelete is 0.2. - // Output weights produced are { 0.75, 0.25 }. - { - std::sort(links.begin(), links.end(), CompareLinksByWeight); - - if (links.size() > maxLinkCount) - { - links.resize(maxLinkCount); - } - - NormalizeWeights(); - - const size_t oldSize = links.size(); - - DeleteByWeight(minWeightToDelete); - - if (links.empty()) - { - return "All bone links of a vertex are deleted (minWeightToDelete is too big)"; - } - - if (links.size() != oldSize) - { - NormalizeWeights(); - } - } - - switch (eSort) - { - case eSort_ByWeight: - // Do nothing because we already sorted links by weight (see above) - break; - case eSort_ByBoneId: - std::sort(links.begin(), links.end(), CompareLinksByBoneId); - break; - default: - assert(0); - break; - } - - return 0; - } - - private: - void DeleteByWeight(float minWeightToDelete) - { - for (size_t i = 0; i < links.size(); ++i) - { - if (links[i].weight <= minWeightToDelete) - { - if (i < links.size() - 1) - { - links[i] = links[links.size() - 1]; - } - links.resize(links.size() - 1); - --i; - } - } - } - - void NormalizeWeights() - { - assert(!links.empty() && links[0].weight > 0); - - float w = 0; - - for (size_t i = 0; i < links.size(); ++i) - { - w += links[i].weight; - } - - w = 1 / w; - - for (size_t i = 0; i < links.size(); ++i) - { - links[i].weight *= w; - } - } - - static bool CompareLinksByBoneId(const Link& left, const Link& right) - { - if (left.boneId != right.boneId) - { - return left.boneId < right.boneId; - } - if (left.weight != right.weight) - { - return left.weight < right.weight; - } - return memcmp(&left.offset, &right.offset, sizeof(left.offset)) < 0; - } - - static bool CompareLinksByWeight(const Link& left, const Link& right) - { - if (left.weight != right.weight) - { - return left.weight > right.weight; - } - if (left.boneId != right.boneId) - { - return left.boneId < right.boneId; - } - return memcmp(&left.offset, &right.offset, sizeof(left.offset)) < 0; - } - }; - - - class Mesh - { - public: - // Vertex data - std::vector m_positions; - std::vector m_topologyIds; - std::vector m_normals; - std::vector> m_texCoords; - std::vector m_colors; - std::vector m_alphas; - std::vector m_links; - std::vector m_vertexMatIds; - size_t m_auxSizeof; - std::vector m_aux; - - // Face data - std::vector m_faces; - std::vector m_faceMatIds; - - // Mappings computed and filled by ComputeVertexRemapping() - std::vector m_vertexOldToNew; - std::vector m_vertexNewToOld; - - public: - Mesh() - : m_auxSizeof(0) - { - } - - int GetVertexCount() const - { - return m_positions.size(); - } - - int GetFaceCount() const - { - return m_faces.size(); - } - - ////////////////////////////////////////////////////////////////////////// - // Setters - - void Clear() - { - m_positions.clear(); - m_topologyIds.clear(); - m_normals.clear(); - m_texCoords.clear(); - m_colors.clear(); - m_alphas.clear(); - m_links.clear(); - m_vertexMatIds.clear(); - m_aux.clear(); - - m_faces.clear(); - m_faceMatIds.clear(); - - m_vertexOldToNew.clear(); - m_vertexNewToOld.clear(); - } - - const char* SetPositions(const float* pVec3, int count, int stride, const float scale) - { - if (count <= 0) - { - return "bad position count"; - } - if (stride < 0 || (stride > 0 && stride < sizeof(Vec3))) - { - return "bad position stride"; - } - - m_positions.resize(count); - - for (int i = 0; i < count; ++i) - { - const float* const p = (const float*)(((const char*)pVec3) + ((size_t)i * stride)); - if (!_finite(p[0]) || !_finite(p[1]) || !_finite(p[2])) - { - m_positions.clear(); - return "Illegal (NAN) vertex position. Fix the 3d Model."; - } - m_positions[i].x = p[0] * scale; - m_positions[i].y = p[1] * scale; - m_positions[i].z = p[2] * scale; - } - - return 0; - } - - const char* SetTopologyIds(const int* pTopo, int count, int stride) - { - if (count <= 0) - { - return "bad topologyId count"; - } - if (stride < 0 || (stride > 0 && stride < sizeof(int))) - { - return "bad topologyId stride"; - } - - m_topologyIds.resize(count); - - for (int i = 0; i < count; ++i) - { - const int* const p = (const int*)(((const char*)pTopo) + ((size_t)i * stride)); - m_topologyIds[i] = p[0]; - } - - return 0; - } - - const char* SetNormals(const float* pVec3, int count, int stride) - { - if (count <= 0) - { - return "bad normal count"; - } - if (stride < 0 || (stride > 0 && stride < sizeof(Vec3))) - { - return "bad normal stride"; - } - - m_normals.resize(count); - - for (int i = 0; i < count; ++i) - { - const float* const p = (const float*)(((const char*)pVec3) + ((size_t)i * stride)); - if (!_finite(p[0]) || !_finite(p[1]) || !_finite(p[2])) - { - m_normals.clear(); - return "Illegal (NAN) vertex normal. Fix the 3d Model."; - } - m_normals[i].x = p[0]; - m_normals[i].y = p[1]; - m_normals[i].z = p[2]; - m_normals[i] = m_normals[i].GetNormalizedSafe(Vec3_OneZ); - } - - return 0; - } - - const char* SetTexCoords(const float* pVec2, int count, int stride, bool bFlipT, uint streamIndex) - { - if (count <= 0) - { - return "bad texCoord count"; - } - if (stride < 0 || (stride > 0 && stride < sizeof(float) * 2)) - { - return "bad texCoord stride"; - } - if (m_texCoords.size() <= streamIndex) - { - m_texCoords.resize(streamIndex + 1); - } - - m_texCoords[streamIndex].resize(count); - - for (int i = 0; i < count; ++i) - { - const float* const p = (const float*)(((const char*)pVec2) + ((size_t)i * stride)); - if (!_finite(p[0]) || !_finite(p[1])) - { - m_texCoords[streamIndex].clear(); - return "Illegal (NAN) texture coordinate. Fix the 3d Model."; - } - m_texCoords[streamIndex][i].x = p[0]; - m_texCoords[streamIndex][i].y = bFlipT ? 1 - p[1] : p[1]; - } - - return 0; - } - - const char* SetColors(const uint8* pRgb, int count, int stride) - { - if (count <= 0) - { - return "bad color count"; - } - if (stride < 0 || (stride > 0 && stride < 3)) - { - return "bad color stride"; - } - - m_colors.resize(count); - - for (int i = 0; i < count; ++i) - { - const uint8* const p = (((const uint8*)pRgb) + ((size_t)i * stride)); - m_colors[i].r = p[0]; - m_colors[i].g = p[1]; - m_colors[i].b = p[2]; - } - - return 0; - } - - const char* SetAlphas(const uint8* pAlpha, int count, int stride) - { - if (count <= 0) - { - return "bad alpha count"; - } - if (stride < 0) - { - return "bad alpha stride"; - } - - m_alphas.resize(count); - - for (int i = 0; i < count; ++i) - { - const uint8* const p = (((const uint8*)pAlpha) + ((size_t)i * stride)); - m_alphas[i] = p[0]; - } - - return 0; - } - - const char* SetFaces(const int* pVertIdx3, int count, int stride) - { - if (count <= 0) - { - return "bad face count"; - } - if (stride < 0 || (stride > 0 && stride < 3 * sizeof(int))) - { - return "bad face stride"; - } - - m_faces.resize(count); - - for (int i = 0; i < count; ++i) - { - const int* const p = (const int*)(((const char*)pVertIdx3) + ((size_t)i * stride)); - for (int j = 0; j < 3; ++j) - { - if (p[j] < 0 || p[j] >= m_positions.size()) - { - return "bad vertex index found in a face"; - } - m_faces[i].vertexIndex[j] = p[j]; - } - } - - return 0; - } - - const char* SetFaceMatIds(const int* pMatIds, int count, int stride, int maxMaterialId) - { - if (count <= 0) - { - return "bad face materialId count"; - } - if (stride < 0 || (stride > 0 && stride < sizeof(int))) - { - return "bad face materialIdstride"; - } - - m_faceMatIds.resize(count); - - for (int i = 0; i < count; ++i) - { - const int* const p = (const int*)(((const char*)pMatIds) + ((size_t)i * stride)); - if (p[0] < 0) - { - return "negative material ID found in a face"; - } - if (p[0] >= maxMaterialId) - { - return "material ID found in a face is outside of allowed ranges"; - } - m_faceMatIds[i] = p[0]; - } - - return 0; - } - - const char* SetAux(size_t auxSizeof, const void* pData, int count, int stride) - { - if (auxSizeof <= 0) - { - return "bad aux sizeof"; - } - if (count <= 0) - { - return "bad aux count"; - } - if (stride < 0 || (stride > 0 && stride < auxSizeof)) - { - return "bad aux stride"; - } - - m_auxSizeof = auxSizeof; - - m_aux.resize(count * m_auxSizeof); - - for (int i = 0; i < count; ++i) - { - const uint8* const p = (((const uint8*)pData) + ((size_t)i * stride)); - memcpy(&m_aux[i * m_auxSizeof], p, m_auxSizeof); - } - - return 0; - } - - ////////////////////////////////////////////////////////////////////////// - // Validation - - // Returns 0 if ok, or pointer to the error text - const char* Validate() const - { - const int nVerts = (int)m_positions.size(); - if (nVerts <= 0) - { - return "No vertices"; - } - - const int nFaces = (int)m_faces.size(); - if (nFaces <= 0) - { - return "No faces"; - } - - if (!m_topologyIds.empty() && nVerts != (int)m_topologyIds.size()) - { - return "Mismatch in the number of topology IDs"; - } - - if (!m_normals.empty() && nVerts != (int)m_normals.size()) - { - return "Mismatch in the number of normals"; - } - - for (uint streamIndex = 0; streamIndex < m_texCoords.size(); ++streamIndex) - { - if (!m_texCoords[streamIndex].empty() && nVerts != (int)m_texCoords[streamIndex].size()) - { - return "Mismatch in the number of texture coordinates"; - } - } - - if (!m_colors.empty() && nVerts != (int)m_colors.size()) - { - return "Mismatch in the number of colors"; - } - - if (!m_alphas.empty() && nVerts != (int)m_alphas.size()) - { - return "Mismatch in the number of alphas"; - } - - if (!m_links.empty() && nVerts != (int)m_links.size()) - { - return "Mismatch in the number of vertex-bone links"; - } - - for (size_t i = 0; i < m_links.size(); ++i) - { - if (m_links[i].links.empty()) - { - return "Found a vertex without bone linking"; - } - } - - if (!m_vertexMatIds.empty() && nVerts != (int)m_vertexMatIds.size()) - { - return "Mismatch in the number of vertex materials"; - } - - if (!m_aux.empty() && nVerts != (int)(m_aux.size() / m_auxSizeof)) - { - return "Mismatch in the number of auxiliary elements"; - } - - if (!m_faceMatIds.empty() && nFaces != (int)m_faceMatIds.size()) - { - return "Mismatch in the number of face materials"; - } - - return 0; - } - - ////////////////////////////////////////////////////////////////////////// - // Computation - - void RemoveDegenerateFaces() - { - int writePos = 0; - for (int readPos = 0; readPos < (int)m_faces.size(); ++readPos) - { - const Face& face = m_faces[readPos]; - if (face.vertexIndex[0] != face.vertexIndex[1] && - face.vertexIndex[1] != face.vertexIndex[2] && - face.vertexIndex[0] != face.vertexIndex[2]) - { - m_faces[writePos] = m_faces[readPos]; - if (!m_faceMatIds.empty()) - { - m_faceMatIds[writePos] = m_faceMatIds[readPos]; - } - ++writePos; - } - } - m_faces.resize(writePos); - if (!m_faceMatIds.empty()) - { - m_faceMatIds.resize(writePos); - } - } - - int AddVertexCopy(int sourceVertexIndex) - { - if (sourceVertexIndex < 0 || sourceVertexIndex >= m_positions.size()) - { - assert(0); - return -1; - } - - m_positions.push_back(m_positions[sourceVertexIndex]); - if (!m_topologyIds.empty()) - { - m_topologyIds.push_back(m_topologyIds[sourceVertexIndex]); - } - if (!m_normals.empty()) - { - m_normals.push_back(m_normals[sourceVertexIndex]); - } - for (uint streamIndex = 0; streamIndex < m_texCoords.size(); ++streamIndex) - { - if (!m_texCoords[streamIndex].empty()) - { - m_texCoords[streamIndex].push_back(m_texCoords[streamIndex][sourceVertexIndex]); - } - } - if (!m_colors.empty()) - { - m_colors.push_back(m_colors[sourceVertexIndex]); - } - if (!m_alphas.empty()) - { - m_alphas.push_back(m_alphas[sourceVertexIndex]); - } - if (!m_links.empty()) - { - m_links.push_back(m_links[sourceVertexIndex]); - } - if (!m_vertexMatIds.empty()) - { - m_vertexMatIds.push_back(m_vertexMatIds[sourceVertexIndex]); - } - if (!m_aux.empty()) - { - m_aux.resize(m_aux.size() + m_auxSizeof); - memcpy(&m_aux[m_aux.size() - m_auxSizeof], &m_aux[sourceVertexIndex * m_auxSizeof], m_auxSizeof); - } - return (int)m_positions.size() - 1; - } - - // Note: might create new vertices and modify vertex indices in faces - void SetVertexMaterialIdsFromFaceMaterialIds() - { - m_vertexMatIds.clear(); - if (m_faceMatIds.empty()) - { - return; - } - m_vertexMatIds.resize(m_positions.size(), -1); - - for (size_t i = 0; i < m_faces.size(); ++i) - { - const int faceMatId = m_faceMatIds[i]; - for (int j = 0; j < 3; ++j) - { - int v = m_faces[i].vertexIndex[j]; - if (m_vertexMatIds[v] >= 0 && m_vertexMatIds[v] != faceMatId) - { - v = AddVertexCopy(v); - m_faces[i].vertexIndex[j] = v; - } - m_vertexMatIds[v] = faceMatId; - } - } - } - - // Computes m_vertexOldToNew and m_vertexNewToOld by detecting duplicate vertices - void ComputeVertexRemapping() - { - const size_t nVerts = m_positions.size(); - - m_vertexNewToOld.resize(nVerts); - for (size_t i = 0; i < nVerts; ++i) - { - m_vertexNewToOld[i] = i; - } - - VertexLess less(*this); - std::sort(m_vertexNewToOld.begin(), m_vertexNewToOld.end(), less); - - m_vertexOldToNew.resize(nVerts); - - int nVertsNew = 0; - for (size_t i = 0; i < nVerts; ++i) - { - if (i == 0 || less(m_vertexNewToOld[i - 1], m_vertexNewToOld[i])) - { - m_vertexNewToOld[nVertsNew++] = m_vertexNewToOld[i]; - } - m_vertexOldToNew[m_vertexNewToOld[i]] = nVertsNew - 1; - } - m_vertexNewToOld.resize(nVertsNew); - } - - // Changes order of vertices, number of vertices, vertex indices in faces - void RemoveVerticesByUsingComputedRemapping() - { - CompactVertices(m_positions, m_vertexNewToOld); - CompactVertices(m_topologyIds, m_vertexNewToOld); - CompactVertices(m_normals, m_vertexNewToOld); - for (uint streamIndex = 0; streamIndex < m_texCoords.size(); ++streamIndex) - { - CompactVertices(m_texCoords[streamIndex], m_vertexNewToOld); - } - CompactVertices(m_colors, m_vertexNewToOld); - CompactVertices(m_alphas, m_vertexNewToOld); - CompactVertices(m_links, m_vertexNewToOld); - CompactVertices(m_vertexMatIds, m_vertexNewToOld); - CompactVerticesRaw(m_aux, m_auxSizeof, m_vertexNewToOld); - - for (size_t i = 0, count = m_faces.size(); i < count; ++i) - { - for (int j = 0; j < 3; ++j) - { - const int oldVertedIdx = m_faces[i].vertexIndex[j]; - assert(oldVertedIdx >= 0 && (size_t)oldVertedIdx < m_vertexOldToNew.size()); - const int newVertexIndex = m_vertexOldToNew[oldVertedIdx]; - m_faces[i].vertexIndex[j] = newVertexIndex; - } - } - } - - // Deleting degraded faces (faces with two or more vertices - // sharing same position in space) - void RemoveDegradedFaces() - { - size_t j = 0; - - for (size_t i = 0, count = m_faces.size(); i < count; ++i) - { - const Vec3& p0 = m_positions[m_faces[i].vertexIndex[0]]; - const Vec3& p1 = m_positions[m_faces[i].vertexIndex[1]]; - const Vec3& p2 = m_positions[m_faces[i].vertexIndex[2]]; - if (p0 != p1 && p1 != p2 && p2 != p0) - { - m_faces[j] = m_faces[i]; - if (!m_faceMatIds.empty()) - { - m_faceMatIds[j] = m_faceMatIds[i]; - } - ++j; - } - } - - m_faces.resize(j); - if (!m_faceMatIds.empty()) - { - m_faceMatIds.resize(j); - } - } - - private: - ////////////////////////////////////////////////////////////////////////// - // Internal helpers - - template - static void CompactVertices(std::vector& arr, const std::vector& newToOld) - { - if (arr.empty()) - { - return; - } - - const size_t newCount = newToOld.size(); - - std::vector tmp; - tmp.reserve(newCount); - - for (size_t i = 0; i < newCount; ++i) - { - tmp.push_back(arr[newToOld[i]]); - } - - arr.swap(tmp); - } - - static void CompactVerticesRaw(std::vector& arr, size_t elemSizeof, const std::vector& newToOld) - { - if (arr.empty()) - { - return; - } - - const size_t newCount = newToOld.size(); - - std::vector tmp; - tmp.resize(newCount * elemSizeof); - - for (size_t i = 0; i < newCount; ++i) - { - memcpy(&tmp[i * elemSizeof], &arr[newToOld[i] * elemSizeof], elemSizeof); - } - - arr.swap(tmp); - } - - struct VertexLess - { - const Mesh& m; - - VertexLess(const Mesh& mesh) - : m(mesh) - { - } - - bool operator()(int a, int b) const - { - if (!m.m_topologyIds.empty()) - { - const int res = m.m_topologyIds[a] - m.m_topologyIds[b]; - if (res != 0) - { - return res < 0; - } - } - - { - const int res = memcmp(&m.m_positions[a], &m.m_positions[b], sizeof(m.m_positions[0])); - if (res != 0) - { - return res < 0; - } - } - - int res = 0; - - if (res == 0 && !m.m_normals.empty()) - { - res = memcmp(&m.m_normals[a], &m.m_normals[b], sizeof(m.m_normals[0])); - } - - for (uint streamIndex = 0; streamIndex < m.m_texCoords.size(); ++streamIndex) - { - if (res == 0 && !m.m_texCoords[streamIndex].empty()) - { - res = memcmp(&m.m_texCoords[streamIndex][a], &m.m_texCoords[streamIndex][b], sizeof(m.m_texCoords[streamIndex][0])); - } - } - - if (res == 0 && !m.m_colors.empty()) - { - res = memcmp(&m.m_colors[a], &m.m_colors[b], sizeof(m.m_colors[0])); - } - - if (res == 0 && !m.m_alphas.empty()) - { - res = (int)m.m_alphas[a] - (int)m.m_alphas[b]; - } - - if (res == 0 && !m.m_links.empty()) - { - if (m.m_links[a].links.size() != m.m_links[b].links.size()) - { - res = (m.m_links[a].links.size() < m.m_links[b].links.size()) ? -1 : +1; - } - else - { - res = memcmp(&m.m_links[a].links[0], &m.m_links[b].links[0], sizeof(m.m_links[a].links[0]) * m.m_links[a].links.size()); - } - } - - if (res == 0 && !m.m_vertexMatIds.empty()) - { - res = m.m_vertexMatIds[a] - m.m_vertexMatIds[b]; - } - - if (res == 0 && !m.m_aux.empty()) - { - res = memcmp(&m.m_aux[a * m.m_auxSizeof], &m.m_aux[b * m.m_auxSizeof], m.m_auxSizeof); - } - - return res < 0; - } - }; - }; -} // namespace MeshUtils - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MESHUTILS_H diff --git a/Code/Tools/CryCommonTools/Export/ModelData.cpp b/Code/Tools/CryCommonTools/Export/ModelData.cpp deleted file mode 100644 index 5a6baf170c..0000000000 --- a/Code/Tools/CryCommonTools/Export/ModelData.cpp +++ /dev/null @@ -1,118 +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 "StdAfx.h" -#include "ModelData.h" - -int ModelData::AddModel(const void* handle, const char* modelName, int parentModelIndex, bool geometry, const SHelperData& helperData, const std::string& propertiesString) -{ - int modelIndex = int(m_models.size()); - m_models.push_back(ModelEntry(handle, modelName, parentModelIndex, geometry, helperData, propertiesString)); - if (parentModelIndex >= 0) - { - m_models[parentModelIndex].children.push_back(modelIndex); - } - else - { - m_roots.push_back(modelIndex); - } - return modelIndex; -} - -const void* ModelData::GetModelHandle(int modelIndex) const -{ - return m_models[modelIndex].handle; -} - -const char* ModelData::GetModelName(int modelIndex) const -{ - return m_models[modelIndex].name.c_str(); -} - -void ModelData::SetTranslationRotationScale(int const modelIndex, const float* const translation, const float* const rotation, const float* const scale) -{ - for (int i = 0; i < 3; ++i) - { - m_models[modelIndex].translation[i] = translation[i]; - m_models[modelIndex].rotation[i] = rotation[i]; - m_models[modelIndex].scale[i] = scale[i]; - } -} - -void ModelData::GetTranslationRotationScale(int const modelIndex, float* const translation, float* const rotation, float* const scale) const -{ - for (int i = 0; i < 3; ++i) - { - translation[i] = m_models[modelIndex].translation[i]; - rotation[i] = m_models[modelIndex].rotation[i]; - scale[i] = m_models[modelIndex].scale[i]; - } -} - -const SHelperData& ModelData::GetHelperData(int modelIndex) const -{ - return m_models[modelIndex].helperData; -} - -const std::string& ModelData::GetProperties(int modelIndex) const -{ - return m_models[modelIndex].propertiesString; -} - -bool ModelData::IsRoot(int modelIndex) const -{ - return (m_models[modelIndex].parentIndex < 0); -} - -int ModelData::GetModelCount() const -{ - return int(m_models.size()); -} - -int ModelData::GetRootCount() const -{ - return int(m_roots.size()); -} - -int ModelData::GetRootIndex(int rootIndex) const -{ - return m_roots[rootIndex]; -} - -int ModelData::GetChildCount(int modelIndex) const -{ - return int(m_models[modelIndex].children.size()); -} - -int ModelData::GetChildIndex(int modelIndex, int childIndexIndex) const -{ - return m_models[modelIndex].children[childIndexIndex]; -} - -bool ModelData::HasGeometry(int modelIndex) const -{ - return m_models[modelIndex].geometry; -} - -ModelData::ModelEntry::ModelEntry(const void* a_handle, const std::string& a_name, int a_parentIndex, bool a_geometry, const SHelperData& a_helperData, const std::string& a_propertiesString) - : handle(a_handle) - , name(a_name) - , parentIndex(a_parentIndex) - , geometry(a_geometry) - , helperData(a_helperData) - , propertiesString(a_propertiesString) -{ - translation[0] = translation[1] = translation[2] = 0.0f; - rotation[0] = rotation[1] = rotation[2] = 0.0f; - scale[0] = scale[1] = scale[2] = 1.0f; -} diff --git a/Code/Tools/CryCommonTools/Export/ModelData.h b/Code/Tools/CryCommonTools/Export/ModelData.h deleted file mode 100644 index f6dcb1a921..0000000000 --- a/Code/Tools/CryCommonTools/Export/ModelData.h +++ /dev/null @@ -1,63 +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_CRYCOMMONTOOLS_EXPORT_MODELDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MODELDATA_H -#pragma once - - -#include "IModelData.h" - -class ModelData - : public IModelData -{ -public: - // IModelData - virtual int AddModel(const void* handle, const char* name, int parentModelIndex, bool geometry, const SHelperData& helperData, const std::string& propertiesString); - virtual int GetModelCount() const; - virtual const void* GetModelHandle(int modelIndex) const; - virtual const char* GetModelName(int modelIndex) const; - virtual void SetTranslationRotationScale(int modelIndex, const float* translation, const float* rotation, const float* scale); - virtual void GetTranslationRotationScale(int modelIndex, float* translation, float* rotation, float* scale) const; - virtual const SHelperData& GetHelperData(int modelIndex) const; - virtual const std::string& GetProperties(int modelIndex) const; - virtual bool IsRoot(int modelIndex) const; - - int GetRootCount() const; - int GetRootIndex(int rootIndex) const; - int GetChildCount(int modelIndex) const; - int GetChildIndex(int modelIndex, int childIndexIndex) const; - bool HasGeometry(int modelIndex) const; - -private: - struct ModelEntry - { - ModelEntry(const void* handle, const std::string& name, int parentIndex, bool geometry, const SHelperData& helperData, const std::string& propertiesString); - - const void* handle; - std::string name; - int parentIndex; - bool geometry; - std::vector children; - float translation[3]; - float rotation[3]; - float scale[3]; - SHelperData helperData; - std::string propertiesString; - }; - - std::vector m_models; - std::vector m_roots; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MODELDATA_H diff --git a/Code/Tools/CryCommonTools/Export/MorphData.cpp b/Code/Tools/CryCommonTools/Export/MorphData.cpp deleted file mode 100644 index feadb87a33..0000000000 --- a/Code/Tools/CryCommonTools/Export/MorphData.cpp +++ /dev/null @@ -1,55 +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 "StdAfx.h" -#include "MorphData.h" - -MorphData::MorphData() - : m_handle(0) -{ -} - -void MorphData::SetHandle(const void* handle) -{ - m_handle = handle; -} - -void MorphData::AddMorph(const void* handle, const char* name, const char* fullname) -{ - m_morphs.push_back(Entry(handle, name, fullname ? fullname : "")); -} - -const void* MorphData::GetHandle() const -{ - return m_handle; -} - -int MorphData::GetMorphCount() const -{ - return int(m_morphs.size()); -} - -std::string MorphData::GetMorphName(int morphIndex) const -{ - return m_morphs[morphIndex].name; -} - -std::string MorphData::GetMorphFullName(int morphIndex) const -{ - return m_morphs[morphIndex].fullname.length() > 0 ? m_morphs[morphIndex].fullname : m_morphs[morphIndex].name; -} - -const void* MorphData::GetMorphHandle(int morphIndex) const -{ - return m_morphs[morphIndex].handle; -} diff --git a/Code/Tools/CryCommonTools/Export/MorphData.h b/Code/Tools/CryCommonTools/Export/MorphData.h deleted file mode 100644 index c9c942905a..0000000000 --- a/Code/Tools/CryCommonTools/Export/MorphData.h +++ /dev/null @@ -1,52 +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_CRYCOMMONTOOLS_EXPORT_MORPHDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MORPHDATA_H -#pragma once - - -#include "IMorphData.h" - -class MorphData - : public IMorphData -{ -public: - MorphData(); - - virtual void SetHandle(const void* handle); - virtual void AddMorph(const void* handle, const char* name, const char* fullname); - virtual const void* GetHandle() const; - virtual int GetMorphCount() const; - virtual const void* GetMorphHandle(int morphIndex) const; - - std::string GetMorphName(int morphIndex) const; - std::string GetMorphFullName(int morphIndex) const; - -private: - struct Entry - { - Entry(const void* handle, const std::string& name, const std::string& fullname) - : handle(handle) - , name(name) - , fullname(fullname) {} - const void* handle; - std::string name; - std::string fullname; - }; - - const void* m_handle; - std::vector m_morphs; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MORPHDATA_H diff --git a/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.cpp b/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.cpp deleted file mode 100644 index be924eedf3..0000000000 --- a/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.cpp +++ /dev/null @@ -1,86 +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 "StdAfx.h" -#include "SingleAnimationExportSourceAdapter.h" -#include "IGeometryFileData.h" -#include - -SingleAnimationExportSourceAdapter::SingleAnimationExportSourceAdapter(IExportSource* source, IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) - : ExportSourceDecoratorBase(source) - , animationIndex(animationIndex) - , geometryFileData(geometryFileData) - , geometryFileIndex(geometryFileIndex) -{ - assert(this->animationIndex < this->source->GetAnimationCount()); -} - -float SingleAnimationExportSourceAdapter::GetDCCFrameRate() const -{ - return this->source->GetDCCFrameRate(); -} - -void SingleAnimationExportSourceAdapter::ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData) -{ - const int geometryFileIndex = geometryFileData->AddGeometryFile( - this->geometryFileData->GetGeometryFileHandle(this->geometryFileIndex), - this->geometryFileData->GetGeometryFileName(this->geometryFileIndex), - this->geometryFileData->GetProperties(this->geometryFileIndex)); -} - -void SingleAnimationExportSourceAdapter::ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData) -{ - assert(geometryFileIndex == 0); - this->source->ReadModels(this->geometryFileData, this->geometryFileIndex, modelData); -} - -void SingleAnimationExportSourceAdapter::ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* const modelData, int modelIndex, ISkeletonData* skeletonData) -{ - this->source->ReadSkinning(context, skinningData, modelData, modelIndex, skeletonData); -} - -bool SingleAnimationExportSourceAdapter::ReadSkeleton(const IGeometryFileData* const geometryFileData, int geometryFileIndex, const IModelData* const modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData) -{ - assert(geometryFileIndex == 0); - return this->source->ReadSkeleton(this->geometryFileData, this->geometryFileIndex, modelData, modelIndex, materialData, skeletonData); -} - -int SingleAnimationExportSourceAdapter::GetAnimationCount() const -{ - return 1; -} - -std::string SingleAnimationExportSourceAdapter::GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const -{ - assert(geometryFileIndex == 0); - assert(animationIndex == 0); - return this->source->GetAnimationName(this->geometryFileData, this->geometryFileIndex, this->animationIndex); -} - -void SingleAnimationExportSourceAdapter::GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const -{ - assert(animationIndex == 0); - this->source->GetAnimationTimeSpan(start, stop, this->animationIndex); -} - -void SingleAnimationExportSourceAdapter::ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* const geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const -{ - assert(animationIndex == 0); - this->source->ReadAnimationFlags(context, animationData, geometryFileData, modelData, modelIndex, skeletonData, this->animationIndex); -} - -IAnimationData* SingleAnimationExportSourceAdapter::ReadAnimation(IExportContext* context, const IGeometryFileData* const geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const -{ - assert(animationIndex == 0); - return this->source->ReadAnimation(context, geometryFileData, modelData, modelIndex, skeletonData, this->animationIndex, fps); -} diff --git a/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.h b/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.h deleted file mode 100644 index 13da9b47a0..0000000000 --- a/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.h +++ /dev/null @@ -1,45 +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_CRYCOMMONTOOLS_EXPORT_SINGLEANIMATIONEXPORTSOURCEADAPTER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SINGLEANIMATIONEXPORTSOURCEADAPTER_H -#pragma once - - -#include "ExportSourceDecoratorBase.h" - -class SingleAnimationExportSourceAdapter - : public ExportSourceDecoratorBase -{ -public: - SingleAnimationExportSourceAdapter(IExportSource* source, IGeometryFileData* geometryData, int geometryFileIndex, int animationIndex); - - virtual float GetDCCFrameRate() const; - - virtual void ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData); - virtual void ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData); - virtual void ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* modelData, int modelIndex, ISkeletonData* skeletonData); - virtual bool ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData); - virtual int GetAnimationCount() const; - virtual std::string GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const; - virtual void GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const; - virtual void ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const; - virtual IAnimationData* ReadAnimation(IExportContext* context, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const; - -private: - int animationIndex; - IGeometryFileData* geometryFileData; - int geometryFileIndex; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SINGLEANIMATIONEXPORTSOURCEADAPTER_H diff --git a/Code/Tools/CryCommonTools/Export/SkeletonData.cpp b/Code/Tools/CryCommonTools/Export/SkeletonData.cpp deleted file mode 100644 index 13d38678b2..0000000000 --- a/Code/Tools/CryCommonTools/Export/SkeletonData.cpp +++ /dev/null @@ -1,309 +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 "StdAfx.h" -#include "SkeletonData.h" -#include - -int SkeletonData::AddBone(const void* handle, const char* name, int parentIndex) -{ - int modelIndex = int(m_bones.size()); - m_bones.push_back(BoneEntry(handle, name, parentIndex)); - m_nameBoneIndexMap.insert(std::make_pair(name, modelIndex)); - if (parentIndex >= 0) - { - m_bones[parentIndex].children.push_back(modelIndex); - } - else - { - m_roots.push_back(modelIndex); - } - return modelIndex; -} - -int SkeletonData::FindBone(const char* name) const -{ - std::map::const_iterator modelPos = m_nameBoneIndexMap.find(name); - return (modelPos != m_nameBoneIndexMap.end() ? (*modelPos).second : -1); -} - -const void* SkeletonData::GetBoneHandle(int boneIndex) const -{ - return m_bones[boneIndex].handle; -} - -int SkeletonData::GetBoneParentIndex(int boneIndex) const -{ - return m_bones[boneIndex].parentIndex; -} - -int SkeletonData::GetBoneCount() const -{ - return int(m_bones.size()); -} - -void SkeletonData::SetTranslation(int modelIndex, const float* vec) -{ - for (int i = 0; i < 3; ++i) - { - m_bones[modelIndex].translation[i] = vec[i]; - } -} - -void SkeletonData::SetRotation(int modelIndex, const float* vec) -{ - for (int i = 0; i < 3; ++i) - { - m_bones[modelIndex].rotation[i] = vec[i]; - } -} - -void SkeletonData::SetScale(int modelIndex, const float* vec) -{ - for (int i = 0; i < 3; ++i) - { - m_bones[modelIndex].scale[i] = vec[i]; - } -} - -void SkeletonData::SetParentFrameTranslation(int boneIndex, const float* vec) -{ - EnsureParentFrameExists(boneIndex); - std::copy(vec, vec + 3, m_bones[boneIndex].parentFrameTranslation); -} - -void SkeletonData::SetParentFrameRotation(int boneIndex, const float* vec) -{ - EnsureParentFrameExists(boneIndex); - std::copy(vec, vec + 3, m_bones[boneIndex].parentFrameRotation); -} - -void SkeletonData::SetParentFrameScale(int boneIndex, const float* vec) -{ - EnsureParentFrameExists(boneIndex); - std::copy(vec, vec + 3, m_bones[boneIndex].parentFrameScale); -} - -void SkeletonData::SetLimit(int boneIndex, Axis axis, Limit extreme, float limit) -{ - m_bones[boneIndex].limits.insert(std::make_pair(AxisLimit(axis, extreme), limit)); -} - -void SkeletonData::SetSpringTension(int boneIndex, Axis axis, float springTension) -{ - m_bones[boneIndex].springTensions.insert(std::make_pair(axis, springTension)); -} - -void SkeletonData::SetSpringAngle(int boneIndex, Axis axis, float springAngle) -{ - m_bones[boneIndex].springAngles.insert(std::make_pair(axis, springAngle)); -} - -void SkeletonData::SetAxisDamping(int boneIndex, Axis axis, float damping) -{ - m_bones[boneIndex].dampings.insert(std::make_pair(axis, damping)); -} - -void SkeletonData::SetPhysicalized(int boneIndex, bool physicalized) -{ - m_bones[boneIndex].physicalized = physicalized; -} - -void SkeletonData::SetHasGeometry(int boneIndex, bool hasGeometry) -{ - m_bones[boneIndex].hasGeometry = hasGeometry; -} - -void SkeletonData::SetBoneProperties(int boneIndex, const char* propertiesString) -{ - m_bones[boneIndex].propertiesString = propertiesString; -} - -void SkeletonData::SetBoneGeomProperties(int boneIndex, const char* propertiesString) -{ - m_bones[boneIndex].geomPropertiesString = propertiesString; -} - -bool SkeletonData::HasParentFrame(int boneIndex) const -{ - return m_bones[boneIndex].hasParentFrame; -} - -void SkeletonData::GetParentFrameTranslation(int boneIndex, float* vec) const -{ - std::copy(m_bones[boneIndex].parentFrameTranslation, m_bones[boneIndex].parentFrameTranslation + 3, vec); -} - -void SkeletonData::GetParentFrameRotation(int boneIndex, float* vec) const -{ - std::copy(m_bones[boneIndex].parentFrameRotation, m_bones[boneIndex].parentFrameRotation + 3, vec); -} - -void SkeletonData::GetParentFrameScale(int boneIndex, float* vec) const -{ - std::copy(m_bones[boneIndex].parentFrameScale, m_bones[boneIndex].parentFrameScale + 3, vec); -} - -bool SkeletonData::HasLimit(int boneIndex, Axis axis, Limit extreme) const -{ - return m_bones[boneIndex].limits.find(AxisLimit(axis, extreme)) != m_bones[boneIndex].limits.end(); -} - -float SkeletonData::GetLimit(int boneIndex, Axis axis, Limit extreme) const -{ - return (*m_bones[boneIndex].limits.find(AxisLimit(axis, extreme))).second; -} - -bool SkeletonData::HasSpringTension(int boneIndex, Axis axis) const -{ - return m_bones[boneIndex].springTensions.find(axis) != m_bones[boneIndex].springTensions.end(); -} - -float SkeletonData::GetSpringTension(int boneIndex, Axis axis) const -{ - return (*m_bones[boneIndex].springTensions.find(axis)).second; -} - -bool SkeletonData::HasSpringAngle(int boneIndex, Axis axis) const -{ - return m_bones[boneIndex].springAngles.find(axis) != m_bones[boneIndex].springAngles.end(); -} - -float SkeletonData::GetSpringAngle(int boneIndex, Axis axis) const -{ - return (*m_bones[boneIndex].springAngles.find(axis)).second; -} - -bool SkeletonData::HasAxisDamping(int boneIndex, Axis axis) const -{ - return m_bones[boneIndex].dampings.find(axis) != m_bones[boneIndex].dampings.end(); -} - -float SkeletonData::GetAxisDamping(int boneIndex, Axis axis) const -{ - return (*m_bones[boneIndex].dampings.find(axis)).second; -} - -bool SkeletonData::GetPhysicalized(int boneIndex) const -{ - return m_bones[boneIndex].physicalized; -} - -bool SkeletonData::HasGeometry(int boneIndex) const -{ - return m_bones[boneIndex].hasGeometry; -} - -int SkeletonData::GetRootCount() const -{ - return int(m_roots.size()); -} - -int SkeletonData::GetRootIndex(int rootIndex) const -{ - return m_roots[rootIndex]; -} - -int SkeletonData::GetParentIndex(int modelIndex) const -{ - return m_bones[modelIndex].parentIndex; -} - -const std::string SkeletonData::GetName(int modelIndex) const -{ - std::string copy(m_bones[modelIndex].name); - for (int i = 0, count = int(copy.size()); i < count; ++i) - { - if (!std::isalnum(copy[i]) && copy[i] != ' ') - { - copy[i] = '_'; - } - } - return copy; -} - - -const std::string SkeletonData::GetSafeName(int modelIndex) const -{ - std::string name = GetName(modelIndex); - std::replace_if(name.begin(), name.end(), std::isspace, '_'); - return name; -} - -int SkeletonData::GetChildCount(int modelIndex) const -{ - return int(m_bones[modelIndex].children.size()); -} - -int SkeletonData::GetChildIndex(int modelIndex, int childIndexIndex) const -{ - return m_bones[modelIndex].children[childIndexIndex]; -} - -void SkeletonData::GetTranslation(float* vec, int modelIndex) const -{ - for (int i = 0; i < 3; ++i) - { - vec[i] = m_bones[modelIndex].translation[i]; - } -} - -void SkeletonData::GetRotation(float* vec, int modelIndex) const -{ - for (int i = 0; i < 3; ++i) - { - vec[i] = m_bones[modelIndex].rotation[i]; - } -} - -void SkeletonData::GetScale(float* vec, int modelIndex) const -{ - for (int i = 0; i < 3; ++i) - { - vec[i] = m_bones[modelIndex].scale[i]; - } -} - -const std::string SkeletonData::GetBoneProperties(int boneIndex) const -{ - return m_bones[boneIndex].propertiesString; -} - -const std::string SkeletonData::GetBoneGeomProperties(int boneIndex) const -{ - return m_bones[boneIndex].geomPropertiesString; -} - -void SkeletonData::EnsureParentFrameExists(int boneIndex) -{ - if (!m_bones[boneIndex].hasParentFrame) - { - std::fill(m_bones[boneIndex].parentFrameTranslation, m_bones[boneIndex].parentFrameTranslation + 3, 0.0f); - std::fill(m_bones[boneIndex].parentFrameRotation, m_bones[boneIndex].parentFrameRotation + 3, 0.0f); - std::fill(m_bones[boneIndex].parentFrameScale, m_bones[boneIndex].parentFrameScale + 3, 0.0f); - m_bones[boneIndex].hasParentFrame = true; - } -} - -SkeletonData::BoneEntry::BoneEntry(const void* handle, const std::string& name, int parentIndex) - : handle(handle) - , name(name) - , parentIndex(parentIndex) - , hasParentFrame(false) - , physicalized(false) - , hasGeometry(hasGeometry) -{ - translation[0] = translation[1] = translation[2] = 0.0f; - rotation[0] = rotation[1] = rotation[2] = 0.0f; - scale[0] = scale[1] = scale[2] = 1.0f; -} diff --git a/Code/Tools/CryCommonTools/Export/SkeletonData.h b/Code/Tools/CryCommonTools/Export/SkeletonData.h deleted file mode 100644 index 60bd8274b7..0000000000 --- a/Code/Tools/CryCommonTools/Export/SkeletonData.h +++ /dev/null @@ -1,116 +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_CRYCOMMONTOOLS_EXPORT_SKELETONDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKELETONDATA_H -#pragma once - - -#include "ISkeletonData.h" -#include -#include -#include - -class SkeletonData - : public ISkeletonData -{ -public: - // ISkeletonData - virtual int AddBone(const void* handle, const char* name, int parentIndex); - virtual int FindBone(const char* name) const; - virtual const void* GetBoneHandle(int boneIndex) const; - virtual int GetBoneParentIndex(int boneIndex) const; - virtual int GetBoneCount() const; - virtual void SetTranslation(int boneIndex, const float* vec); - virtual void SetRotation(int boneIndex, const float* vec); - virtual void SetScale(int boneIndex, const float* vec); - virtual void SetParentFrameTranslation(int boneIndex, const float* vec); - virtual void SetParentFrameRotation(int boneIndex, const float* vec); - virtual void SetParentFrameScale(int boneIndex, const float* vec); - virtual void SetLimit(int boneIndex, Axis axis, Limit extreme, float limit); - virtual void SetSpringTension(int boneIndex, Axis axis, float springTension); - virtual void SetSpringAngle(int boneIndex, Axis axis, float springAngle); - virtual void SetAxisDamping(int boneIndex, Axis axis, float damping); - virtual void SetPhysicalized(int boneIndex, bool physicalized); - virtual void SetHasGeometry(int boneIndex, bool hasGeometry); - virtual void SetBoneProperties(int boneIndex, const char* propertiesString); - virtual void SetBoneGeomProperties(int boneIndex, const char* propertiesString); - - bool HasParentFrame(int boneIndex) const; - void GetParentFrameTranslation(int boneIndex, float* vec) const; - void GetParentFrameRotation(int boneIndex, float* vec) const; - void GetParentFrameScale(int boneIndex, float* vec) const; - bool HasLimit(int boneIndex, Axis axis, Limit extreme) const; - float GetLimit(int boneIndex, Axis axis, Limit extreme) const; - bool HasSpringTension(int boneIndex, Axis axis) const; - float GetSpringTension(int boneIndex, Axis axis) const; - bool HasSpringAngle(int boneIndex, Axis axis) const; - float GetSpringAngle(int boneIndex, Axis axis) const; - bool HasAxisDamping(int boneIndex, Axis axis) const; - float GetAxisDamping(int boneIndex, Axis axis) const; - bool GetPhysicalized(int boneIndex) const; - bool HasGeometry(int boneIndex) const; - - int GetRootCount() const; - int GetRootIndex(int rootIndex) const; - int GetParentIndex(int boneIndex) const; - const std::string GetName(int boneIndex) const; - const std::string GetSafeName(int boneIndex) const; - int GetChildCount(int boneIndex) const; - int GetChildIndex(int boneIndex, int childIndexIndex) const; - void GetTranslation(float* vec, int boneIndex) const; - void GetRotation(float* vec, int boneIndex) const; - void GetScale(float* vec, int boneIndex) const; - const std::string GetBoneProperties(int boneIndex) const; - const std::string GetBoneGeomProperties(int boneIndex) const; - -private: - void EnsureParentFrameExists(int boneIndex); - - typedef std::pair AxisLimit; - typedef std::map AxisLimitLimitMap; - typedef std::map AxisSpringTensionMap; - typedef std::map AxisSpringAngleMap; - typedef std::map AxisDampingMap; - - struct BoneEntry - { - public: - BoneEntry(const void* handle, const std::string& name, int parentIndex); - const void* handle; - std::string name; - int parentIndex; - AxisLimitLimitMap limits; - AxisSpringTensionMap springTensions; - AxisSpringAngleMap springAngles; - AxisDampingMap dampings; - bool hasParentFrame; - float parentFrameTranslation[3]; - float parentFrameRotation[3]; - float parentFrameScale[3]; - bool physicalized; - std::vector children; - float translation[3]; - float rotation[3]; - float scale[3]; - bool hasGeometry; - std::string propertiesString; - std::string geomPropertiesString; - }; - - std::vector m_bones; - std::vector m_roots; - std::map m_nameBoneIndexMap; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKELETONDATA_H diff --git a/Code/Tools/CryCommonTools/Export/SkinningData.cpp b/Code/Tools/CryCommonTools/Export/SkinningData.cpp deleted file mode 100644 index eeef150cad..0000000000 --- a/Code/Tools/CryCommonTools/Export/SkinningData.cpp +++ /dev/null @@ -1,45 +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 "StdAfx.h" -#include "SkinningData.h" - -void SkinningData::SetVertexCount(int vertexCount) -{ - m_weights.resize(vertexCount); -} - -void SkinningData::AddWeight(int vertexIndex, int boneIndex, float weight) -{ - m_weights[vertexIndex].push_back(BoneWeight(boneIndex, weight)); -} - -int SkinningData::GetVertexCount() const -{ - return int(m_weights.size()); -} - -int SkinningData::GetBoneLinkCount(int vertexIndex) const -{ - return int(m_weights[vertexIndex].size()); -} - -int SkinningData::GetBoneIndex(int vertexIndex, int linkIndex) const -{ - return m_weights[vertexIndex][linkIndex].boneIndex; -} - -float SkinningData::GetWeight(int vertexIndex, int linkIndex) const -{ - return m_weights[vertexIndex][linkIndex].weight; -} diff --git a/Code/Tools/CryCommonTools/Export/SkinningData.h b/Code/Tools/CryCommonTools/Export/SkinningData.h deleted file mode 100644 index 6e3a9a6712..0000000000 --- a/Code/Tools/CryCommonTools/Export/SkinningData.h +++ /dev/null @@ -1,46 +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_CRYCOMMONTOOLS_EXPORT_SKINNINGDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKINNINGDATA_H -#pragma once - - -#include "ISkinningData.h" - -class SkinningData - : public ISkinningData -{ -public: - virtual void SetVertexCount(int vertexCount); - virtual void AddWeight(int vertexIndex, int boneIndex, float weight); - - int GetVertexCount() const; - int GetBoneLinkCount(int vertexIndex) const; - int GetBoneIndex(int vertexIndex, int linkIndex) const; - float GetWeight(int vertexIndex, int linkIndex) const; - -private: - struct BoneWeight - { - BoneWeight(int boneIndex, float weight) - : boneIndex(boneIndex) - , weight(weight) {} - int boneIndex; - float weight; - }; - - std::vector > m_weights; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKINNINGDATA_H diff --git a/Code/Tools/CryCommonTools/Export/TransformHelpers.h b/Code/Tools/CryCommonTools/Export/TransformHelpers.h deleted file mode 100644 index cdddd78337..0000000000 --- a/Code/Tools/CryCommonTools/Export/TransformHelpers.h +++ /dev/null @@ -1,119 +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_CRYCOMMONTOOLS_EXPORT_TRANSFORMHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_TRANSFORMHELPERS_H -#pragma once - - -#include "Cry_Math.h" - - -namespace TransformHelpers -{ - // Format of forwardUpAxes: "". - // Example of forwardUpAxes: "-Y+Z". - // Returns 0 if successful, or returns a pointer to an error message in case of an error. - // In case of success: X axis in res represents "forward" direction, - // Y axis represents "up" direction. - inline const char* GetForwardUpAxesMatrix(Matrix33& res, const char* forwardUpAxes) - { - Vec3 axisX(ZERO); - Vec3 axisY(ZERO); - - for (int i = 0; i < 2; ++i) - { - Vec3& v = (i == 0) ? axisX : axisY; - - const float val = forwardUpAxes[i * 2 + 0] == '-' ? -1.0f : +1.0f; - - switch (forwardUpAxes[i * 2 + 1]) - { - case 'X': - case 'x': - v.x = val; - break; - case 'Y': - case 'y': - v.y = val; - break; - case 'Z': - case 'z': - v.z = val; - break; - default: - assert(0); - return "Found a bad axis character in forwardUpAxes string"; - } - } - - if (axisX == axisY) - { - assert(0); - return "Forward and up axes are equal in forwardUpAxes string"; - } - - const Vec3 axisZ = axisX.cross(axisY); - - res.SetFromVectors(axisX, axisY, axisZ); - - return 0; - } - - - // Computes transform matrix that converts everything from forwardUpAxesSrc - // coordinate system to forwardUpAxesDst coordinate system. - // Format of forwardUpAxesXXX: "". - // Example of forwardUpAxesXXX: "-Y+Z". - // Returns 0 if successful, or returns a pointer to an error message in case of an error. - // In case of success puts computed transform into res. - // See comments to GetForwardUpAxesMatrix(). - inline const char* ComputeForwardUpAxesTransform(Matrix34& res, const char* forwardUpAxesSrc, const char* forwardUpAxesDst) - { - Matrix33 srcToWorld; - Matrix33 dstToWorld; - - const char* const err0 = GetForwardUpAxesMatrix(srcToWorld, forwardUpAxesSrc); - const char* const err1 = GetForwardUpAxesMatrix(dstToWorld, forwardUpAxesDst); - - if (err0 || err1) - { - return err0 ? err0 : err1; - } - - res = Matrix34(dstToWorld * srcToWorld.GetTransposed()); - - return 0; - } - - - inline Matrix34 ComputeOrthonormalMatrix(const Matrix34& m) - { - Vec3 x = m.GetColumn0(); - x.Normalize(); - - Vec3 y = m.GetColumn1(); - - Vec3 z = x.cross(y); - z.Normalize(); - - y = z.cross(x); - - Matrix34 result; - result.SetFromVectors(x, y, z, m.GetTranslation()); - - return result; - } -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_TRANSFORMHELPERS_H diff --git a/Code/Tools/CryCommonTools/UI/EULADialog.cpp b/Code/Tools/CryCommonTools/UI/EULADialog.cpp deleted file mode 100644 index a4b8696eea..0000000000 --- a/Code/Tools/CryCommonTools/UI/EULADialog.cpp +++ /dev/null @@ -1,132 +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 "StdAfx.h" -#include "EULADialog.h" -#include "Win32GUI.h" -#include "ModuleHelpers.h" -#include "Richedit.h" -#include - -EULADialog::EULADialog() - : m_frameWindow() - , m_cancelButton(_T("Cancel"), this, &EULADialog::CancelPressed) - , m_buttonSpacer(0, 0, 2000, 0) - , m_acceptButton(_T("Accept"), this, &EULADialog::AcceptPressed) - , m_buttonLayout(Layout::DirectionHorizontal) - , m_edit() -{ - Win32GUI::Initialize(); - - m_buttonLayout.AddComponent(&m_buttonSpacer); - m_buttonLayout.AddComponent(&m_cancelButton); - m_buttonLayout.AddComponent(&m_acceptButton); - - m_frameWindow.AddComponent(&m_edit); - m_frameWindow.AddComponent(&m_buttonLayout); -} - -namespace -{ - class EditStreamCallbackObject - { - public: - EditStreamCallbackObject(const char* data, int size) - : data(data) - , position(0) - , size(size) {} - static DWORD WINAPI EditStreamCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG* pcb) - { - return ((EditStreamCallbackObject*)dwCookie)->EditStreamCallback_Member(dwCookie, pbBuff, cb, pcb); - } - - private: - DWORD EditStreamCallback_Member(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG* pcb) - { - int bytesToRead = (std::min)(this->size - this->position, (int)cb); - std::memcpy(pbBuff, this->data + this->position, bytesToRead); - this->position += bytesToRead; - if (pcb) - { - *pcb = bytesToRead; - } - return 0; - } - - const char* data; - int position; - int size; - }; -} - -EULADialog::UserResponse EULADialog::Run(int width, int height, TCHAR* resourceID) -{ - m_frameWindow.Show(true, width, height); - - // Attempt to load the resource. - HINSTANCE module = ModuleHelpers::GetCurrentModule(ModuleHelpers::CurrentModuleSpecifier_Library); - HRSRC resource = (resourceID ? FindResource(module, resourceID, RT_RCDATA) : 0); - int resourceLength = (resource ? SizeofResource(module, resource) : 0); - HGLOBAL resourceGlobal = (resource ? LoadResource(module, resource) : 0); - void* resourceData = (resourceGlobal ? LockResource(resourceGlobal) : 0); - // No need to unlock/delete data. - - m_userResponse = UserResponseNone; - - // Load the text. - if (resourceData && resourceLength > 0) - { - EditStreamCallbackObject callbackObject((const char*)resourceData, resourceLength); - EDITSTREAM editStream; - std::memset(&editStream, 0, sizeof(editStream)); - editStream.dwCookie = (DWORD_PTR)&callbackObject; - editStream.pfnCallback = &EditStreamCallbackObject::EditStreamCallback; - SendMessage((HWND)m_edit.m_edit, EM_STREAMIN, SF_RTF, (LPARAM)&editStream); - } - - MSG msg; - BOOL status; - bool waitingAcceptance = false; - while (m_userResponse == UserResponseNone && (status = GetMessage(&msg, HWND(0), UINT(0), UINT(0))) != 0) - { - if (status == -1) - { - break; - } - else - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - - m_frameWindow.Show(false, 0, 0); - - return m_userResponse; -} - -void EULADialog::CancelPressed() -{ - m_userResponse = UserResponseCancel; -} - -void EULADialog::AcceptPressed() -{ - m_userResponse = UserResponseAccept; -} - -EULADialog::UserResponse EULADialog::Show(int width, int height, TCHAR* resourceID) -{ - EULADialog dlg; - return dlg.Run(width, height, resourceID); -} diff --git a/Code/Tools/CryCommonTools/UI/EULADialog.h b/Code/Tools/CryCommonTools/UI/EULADialog.h deleted file mode 100644 index 4af9bde758..0000000000 --- a/Code/Tools/CryCommonTools/UI/EULADialog.h +++ /dev/null @@ -1,55 +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_CRYCOMMONTOOLS_UI_EULADIALOG_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_EULADIALOG_H -#pragma once - - -#include "FrameWindow.h" -#include "EditControl.h" -#include "Spacer.h" -#include "Layout.h" -#include "PushButton.h" - -class EULADialog -{ -public: - enum UserResponse - { - UserResponseNone, - UserResponseCancel, - UserResponseAccept - }; - - static UserResponse Show(int width, int height, TCHAR* resourceID); - -private: - EULADialog(); - - UserResponse Run(int width, int height, TCHAR* resourceID); - - void CancelPressed(); - void AcceptPressed(); - - FrameWindow m_frameWindow; - PushButton m_cancelButton; - Spacer m_buttonSpacer; - PushButton m_acceptButton; - Layout m_buttonLayout; - EditControl m_edit; - - UserResponse m_userResponse; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_EULADIALOG_H diff --git a/Code/Tools/CryCommonTools/UI/EditControl.cpp b/Code/Tools/CryCommonTools/UI/EditControl.cpp deleted file mode 100644 index 61ac51f41d..0000000000 --- a/Code/Tools/CryCommonTools/UI/EditControl.cpp +++ /dev/null @@ -1,48 +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 "StdAfx.h" -#include "EditControl.h" -#include "Win32GUI.h" -#include -#include -#include - -EditControl::EditControl() - : m_edit(0) -{ -} - -void EditControl::CreateUI(void* window, int left, int top, int width, int height) -{ - m_edit = Win32GUI::CreateControl(RICHEDIT_CLASS, ES_MULTILINE /*| ES_READONLY*/, (HWND)window, left, top, width, height); -} - -void EditControl::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_edit, left, top, width, height, true); -} - -void EditControl::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_edit); - m_edit = 0; -} - -void EditControl::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 20; - maxWidth = 2000; - minHeight = 20; - maxHeight = 2000; -} diff --git a/Code/Tools/CryCommonTools/UI/EditControl.h b/Code/Tools/CryCommonTools/UI/EditControl.h deleted file mode 100644 index da00059e94..0000000000 --- a/Code/Tools/CryCommonTools/UI/EditControl.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_EDITCONTROL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_EDITCONTROL_H -#pragma once - - -#include "IUIComponent.h" - -class EditControl - : public IUIComponent -{ -public: - EditControl(); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - - void* m_edit; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_EDITCONTROL_H diff --git a/Code/Tools/CryCommonTools/UI/FrameWindow.cpp b/Code/Tools/CryCommonTools/UI/FrameWindow.cpp deleted file mode 100644 index feaa7ab293..0000000000 --- a/Code/Tools/CryCommonTools/UI/FrameWindow.cpp +++ /dev/null @@ -1,116 +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 "StdAfx.h" -#include "FrameWindow.h" -#include "Win32GUI.h" -#include "IUIComponent.h" -#include -#include - -FrameWindow::FrameWindow() - : m_hwnd(0) - , m_layout(Layout::DirectionVertical) -{ -} - -FrameWindow::~FrameWindow() -{ - if (m_hwnd) - { - Show(false, 0, 0); - } -} - -void FrameWindow::AddComponent(IUIComponent* component) -{ - assert(m_hwnd == 0); - m_layout.AddComponent(component); -} - -void FrameWindow::Show(bool show, int width, int height) -{ - if (show) - { - assert(m_hwnd == 0); - TCHAR* className = _T("CustomFrameWindowClass212"); - Win32GUI::RegisterFrameClass(className); - m_hwnd = Win32GUI::CreateFrame(className, WS_MINIMIZEBOX | WS_OVERLAPPED | WS_THICKFRAME | WS_CAPTION | WS_SYSMENU | WS_MAXIMIZEBOX, width, height); - Win32GUI::SetCallback((HWND)m_hwnd, this, &FrameWindow::CalculateExtremeDimensions); - Win32GUI::SetCallback((HWND)m_hwnd, this, &FrameWindow::OnSizeChanged); - std::pair size = InitializeSize(); - m_layout.CreateUI(m_hwnd, 0, 0, size.first, size.second); - ShowWindow((HWND)m_hwnd, SW_SHOWDEFAULT); - } - else - { - m_layout.DestroyUI(m_hwnd); - assert(m_hwnd != 0); - DestroyWindow((HWND)m_hwnd); - m_hwnd = 0; - } -} - -void FrameWindow::SetCaption(const TCHAR* caption) -{ - SendMessage((HWND)m_hwnd, WM_SETTEXT, 0, (LPARAM)caption); -} - -void* FrameWindow::GetHWND() -{ - return m_hwnd; -} - -std::pair FrameWindow::InitializeSize() -{ - int minW, maxW, minH, maxH; - CalculateExtremeDimensions(minW, maxW, minH, maxH); - RECT rect; - GetWindowRect((HWND)m_hwnd, &rect); - int width = int((std::min)(maxW, (std::max)(minW, int(rect.right - rect.left)))); - int height = int((std::min)(maxH, (std::max)(minH, int(rect.bottom - rect.top)))); - MoveWindow((HWND)m_hwnd, rect.left, rect.top, width, height, false); - return std::make_pair(width, height); -} - -void FrameWindow::CalculateExtremeDimensions(int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - int minW = 0; - int maxW = 0; - int minH = 0; - int maxH = 0; - m_layout.GetExtremeDimensions(m_hwnd, minW, maxW, minH, maxH); - - // Add the space required for the window decorations. - RECT rect; - rect.left = 0, rect.top = 0, rect.right = minW, rect.bottom = minH; - unsigned style = GetWindowLong((HWND)m_hwnd, GWL_STYLE); - AdjustWindowRect(&rect, style, false); - minW = rect.right - rect.left; - minH = rect.bottom - rect.top; - - rect.left = 0, rect.top = 0, rect.right = maxW, rect.bottom = maxH; - AdjustWindowRect(&rect, style, false); - maxW = rect.right - rect.left; - maxH = rect.bottom - rect.top; - - minWidth = minW; - maxWidth = maxW; - minHeight = minH; - maxHeight = maxH; -} - -void FrameWindow::OnSizeChanged(int width, int height) -{ - m_layout.Resize(m_hwnd, 0, 0, width, height); -} diff --git a/Code/Tools/CryCommonTools/UI/FrameWindow.h b/Code/Tools/CryCommonTools/UI/FrameWindow.h deleted file mode 100644 index ff1bba893d..0000000000 --- a/Code/Tools/CryCommonTools/UI/FrameWindow.h +++ /dev/null @@ -1,44 +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_CRYCOMMONTOOLS_UI_FRAMEWINDOW_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_FRAMEWINDOW_H -#pragma once - - -#include -#include "Layout.h" - -class IUIComponent; - -class FrameWindow -{ -public: - FrameWindow(); - ~FrameWindow(); - void AddComponent(IUIComponent* component); - void Show(bool show, int width, int height); - void SetCaption(const TCHAR* caption); - void* GetHWND(); - -private: - void UpdateComponentUI(bool create); - std::pair InitializeSize(); - void CalculateExtremeDimensions(int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - void OnSizeChanged(int width, int height); - - void* m_hwnd; - Layout m_layout; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_FRAMEWINDOW_H diff --git a/Code/Tools/CryCommonTools/UI/IUIComponent.h b/Code/Tools/CryCommonTools/UI/IUIComponent.h deleted file mode 100644 index 08b06c424b..0000000000 --- a/Code/Tools/CryCommonTools/UI/IUIComponent.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_IUICOMPONENT_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_IUICOMPONENT_H -#pragma once - - -class IUIComponent -{ -public: - virtual void CreateUI(void* window, int left, int top, int width, int height) = 0; - virtual void Resize(void* window, int left, int top, int width, int height) = 0; - virtual void DestroyUI(void* window) = 0; - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_IUICOMPONENT_H diff --git a/Code/Tools/CryCommonTools/UI/Layout.cpp b/Code/Tools/CryCommonTools/UI/Layout.cpp deleted file mode 100644 index 3225544be2..0000000000 --- a/Code/Tools/CryCommonTools/UI/Layout.cpp +++ /dev/null @@ -1,233 +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 "StdAfx.h" -#include "Layout.h" -#include -#include - -Layout::Layout(Direction direction) - : m_direction(direction) -{ -} - -void Layout::AddComponent(IUIComponent* component) -{ - m_components.push_back(ComponentEntry(component)); -} - -void Layout::CreateUI(void* window, int left, int top, int width, int height) -{ - UpdateLayout(window, left, top, width, height); - - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - component->CreateUI(window, m_components[componentIndex].left, m_components[componentIndex].top, m_components[componentIndex].width, m_components[componentIndex].height); - } -} - -void Layout::Resize(void* window, int left, int top, int width, int height) -{ - UpdateLayout(window, left, top, width, height); - - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - component->Resize(window, m_components[componentIndex].left, m_components[componentIndex].top, m_components[componentIndex].width, m_components[componentIndex].height); - } -} - -void Layout::DestroyUI(void* window) -{ - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - component->DestroyUI(window); - } -} - -void Layout::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - int minW = 0; - int maxW = 0; - int minH = 0; - int maxH = 0; - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - int compMinW, compMaxW, compMinH, compMaxH; - component->GetExtremeDimensions(window, compMinW, compMaxW, compMinH, compMaxH); - switch (m_direction) - { - case DirectionVertical: - minW = (minW > compMinW ? minW : compMinW); - maxW = (maxW > compMaxW ? maxW : compMaxW); // Deliberately take the larger maximum. - minH += compMinH; - maxH += compMaxH; - break; - case DirectionHorizontal: - minW += compMinW; - maxW += compMaxW; - minH = (minH > compMinH ? minH : compMinH); - maxH = (maxH > compMaxH ? maxH : compMaxH); // Deliberately take the larger maximum. - break; - } - } - - // Make sure the window is at least a certain size; - minW = (minW >= 10 ? minW : 10); - maxW = (maxW >= minW ? maxW : minW); - minH = (minH >= 10 ? minH : 10); - maxH = (maxH >= minH ? maxH : minH); - - minWidth = minW; - maxWidth = maxW; - minHeight = minH; - maxHeight = maxH; -} - -void Layout::UpdateLayout(void* window, int left, int top, int width, int height) -{ - assert(window); - - int remainingToAllocate; - switch (m_direction) - { - case DirectionVertical: - remainingToAllocate = height; - break; - case DirectionHorizontal: - remainingToAllocate = width; - break; - } - - int smallestAllocationAmount = INT_MAX; - int canBeExtendedCount = 0; - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - int compMinW, compMaxW, compMinH, compMaxH; - component->GetExtremeDimensions(window, compMinW, compMaxW, compMinH, compMaxH); - - switch (m_direction) - { - case DirectionVertical: - { - int allocationAmount = compMaxH - compMinH; - if (allocationAmount > 0) - { - ++canBeExtendedCount; - smallestAllocationAmount = (smallestAllocationAmount < allocationAmount ? smallestAllocationAmount : allocationAmount); - } - m_components[componentIndex].height = compMinH; - m_components[componentIndex].width = (width > compMaxW ? compMaxW : width); - remainingToAllocate -= m_components[componentIndex].height; - } - break; - - case DirectionHorizontal: - { - int allocationAmount = compMaxW - compMinW; - if (allocationAmount > 0) - { - ++canBeExtendedCount; - smallestAllocationAmount = (smallestAllocationAmount < allocationAmount ? smallestAllocationAmount : allocationAmount); - } - m_components[componentIndex].width = compMinW; - m_components[componentIndex].height = (height > compMaxH ? compMaxH : height); - remainingToAllocate -= m_components[componentIndex].width; - } - break; - } - } - - while (remainingToAllocate > 0 && canBeExtendedCount > 0) - { - int equitablePerCompAllocation = remainingToAllocate / canBeExtendedCount; - int compAllocation = (equitablePerCompAllocation < smallestAllocationAmount ? equitablePerCompAllocation : smallestAllocationAmount); - compAllocation = (compAllocation > 0 ? compAllocation : 1); - canBeExtendedCount = 0; - smallestAllocationAmount = INT_MAX; - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - int compMinW, compMaxW, compMinH, compMaxH; - component->GetExtremeDimensions(window, compMinW, compMaxW, compMinH, compMaxH); - switch (m_direction) - { - case DirectionVertical: - { - int componentExpandAmount = compMaxH - m_components[componentIndex].height; - if (componentExpandAmount > 0) - { - m_components[componentIndex].height += compAllocation; - assert(m_components[componentIndex].height <= compMaxH); - componentExpandAmount -= compAllocation; - remainingToAllocate -= compAllocation; - if (componentExpandAmount > 0) - { - smallestAllocationAmount = (smallestAllocationAmount < componentExpandAmount ? smallestAllocationAmount : componentExpandAmount); - ++canBeExtendedCount; - } - } - } - break; - - case DirectionHorizontal: - { - int componentExpandAmount = compMaxW - m_components[componentIndex].width; - if (componentExpandAmount > 0) - { - m_components[componentIndex].width += compAllocation; - assert(m_components[componentIndex].width <= compMaxW); - componentExpandAmount -= compAllocation; - remainingToAllocate -= compAllocation; - if (componentExpandAmount > 0) - { - smallestAllocationAmount = (smallestAllocationAmount < componentExpandAmount ? smallestAllocationAmount : componentExpandAmount); - ++canBeExtendedCount; - } - } - } - break; - } - } - } - - switch (m_direction) - { - case DirectionVertical: - { - int posY = top; - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - m_components[componentIndex].left = left; - m_components[componentIndex].top = posY; - posY += m_components[componentIndex].height; - } - } - break; - case DirectionHorizontal: - { - int posX = left; - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - m_components[componentIndex].top = top; - m_components[componentIndex].left = posX; - posX += m_components[componentIndex].width; - } - } - break; - } -} diff --git a/Code/Tools/CryCommonTools/UI/Layout.h b/Code/Tools/CryCommonTools/UI/Layout.h deleted file mode 100644 index a2de6c4f69..0000000000 --- a/Code/Tools/CryCommonTools/UI/Layout.h +++ /dev/null @@ -1,61 +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_CRYCOMMONTOOLS_UI_LAYOUT_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_LAYOUT_H -#pragma once - - -#include "IUIComponent.h" -#include - -class Layout - : public IUIComponent -{ -public: - enum Direction - { - DirectionHorizontal, - DirectionVertical - }; - Layout(Direction direction); - void AddComponent(IUIComponent* component); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - void UpdateLayout(void* window, int left, int top, int width, int height); - - struct ComponentEntry - { - explicit ComponentEntry(IUIComponent* component) - : component(component) - , left(0) - , top(0) - , width(0) - , height(0) {} - IUIComponent* component; - int left; - int top; - int width; - int height; - }; - std::vector m_components; - Direction m_direction; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_LAYOUT_H diff --git a/Code/Tools/CryCommonTools/UI/ListView.cpp b/Code/Tools/CryCommonTools/UI/ListView.cpp deleted file mode 100644 index dc43d41fc8..0000000000 --- a/Code/Tools/CryCommonTools/UI/ListView.cpp +++ /dev/null @@ -1,96 +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 "StdAfx.h" -#include "ListView.h" -#include "Win32GUI.h" -#include "resource.h" -#include "ModuleHelpers.h" -#include -#include -#include - -ListView::ListView() - : m_list(0) -{ -} - -void ListView::Add(int imageIndex, const TCHAR* message) -{ - int itemCount = int(SendMessage((HWND)m_list, LVM_GETITEMCOUNT, 0, 0)); - - LVITEM item; - std::memset(&item, 0, sizeof(item)); - item.mask = LVIF_TEXT | LVIF_IMAGE; - item.iItem = itemCount; - item.iSubItem = 0; - item.pszText = (TCHAR*)message; - item.iImage = imageIndex; - - SendMessage((HWND)m_list, LVM_INSERTITEM, 0, (LPARAM)&item); -} - -void ListView::Clear() -{ - SendMessage((HWND)m_list, LVM_DELETEALLITEMS, 0, 0); -} - -void ListView::CreateUI(void* window, int left, int top, int width, int height) -{ - m_list = Win32GUI::CreateControl(WC_LISTVIEW, LVS_REPORT | LVS_NOCOLUMNHEADER, (HWND)window, left, top, width, height); - - LVCOLUMN column; - std::memset(&column, 0, sizeof(column)); - column.mask = LVCF_TEXT | LVCF_WIDTH; - column.pszText = _T("Message"); - column.cx = width; - SendMessage((HWND)m_list, LVM_INSERTCOLUMN, 0, (LPARAM)&column); - - HIMAGELIST imageList = (HIMAGELIST)CreateImageList(); - SendMessage((HWND)m_list, LVM_SETIMAGELIST, LVSIL_SMALL, (LPARAM)imageList); -} - -void ListView::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_list, left, top, width, height, true); - SendMessage((HWND)m_list, LVM_SETCOLUMNWIDTH, 0, width); -} - -void ListView::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_list); - m_list = 0; -} - -void ListView::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 20; - maxWidth = 2000; - minHeight = 20; - maxHeight = 2000; -} - -void* ListView::CreateImageList() -{ - HINSTANCE instance = ModuleHelpers::GetCurrentModule(ModuleHelpers::CurrentModuleSpecifier_Library); - - HBITMAP image = (HBITMAP)LoadImage(instance, MAKEINTRESOURCE(IDB_LOG_ICONS), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION); - DIBSECTION dibSection; - GetObject(image, sizeof(dibSection), &dibSection); - int height = dibSection.dsBmih.biHeight; - int width = height; - int count = dibSection.dsBmih.biWidth / width; - HIMAGELIST imageList = ImageList_Create(16, 16, ILC_COLOR32, count, 0); - ImageList_Add(imageList, image, 0); - return imageList; -} diff --git a/Code/Tools/CryCommonTools/UI/ListView.h b/Code/Tools/CryCommonTools/UI/ListView.h deleted file mode 100644 index 60531dd13d..0000000000 --- a/Code/Tools/CryCommonTools/UI/ListView.h +++ /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. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_LISTVIEW_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_LISTVIEW_H -#pragma once - - -#include "IUIComponent.h" - -class ListView - : public IUIComponent -{ -public: - ListView(); - - void Add(int imageIndex, const TCHAR* message); - void Clear(); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - void* CreateImageList(); - - void* m_list; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_LISTVIEW_H diff --git a/Code/Tools/CryCommonTools/UI/LogWindow.cpp b/Code/Tools/CryCommonTools/UI/LogWindow.cpp deleted file mode 100644 index af96a389e1..0000000000 --- a/Code/Tools/CryCommonTools/UI/LogWindow.cpp +++ /dev/null @@ -1,158 +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 "StdAfx.h" -#include "LogWindow.h" - -LogWindow::LogWindow() - : m_mainLayout(Layout::DirectionVertical) - , m_toolbarLayout(Layout::DirectionHorizontal) - , m_filterFlags(0) -{ - m_buttons.push_back(new ToggleButton(_T("Debug"), this, &LogWindow::DebugToggled)); - m_buttons.push_back(new ToggleButton(_T("Info"), this, &LogWindow::InfoToggled)); - m_buttons.push_back(new ToggleButton(_T("Warnings"), this, &LogWindow::WarningsToggled)); - m_buttons.push_back(new ToggleButton(_T("Errors"), this, &LogWindow::ErrorsToggled)); - - SetFilter(ILogger::eSeverity_Error, true); - SetFilter(ILogger::eSeverity_Warning, true); - SetFilter(ILogger::eSeverity_Info, true); - SetFilter(ILogger::eSeverity_Debug, false); - - m_toolbarLayout.AddComponent(m_buttons[3]); - m_toolbarLayout.AddComponent(m_buttons[2]); - m_toolbarLayout.AddComponent(m_buttons[1]); - m_toolbarLayout.AddComponent(m_buttons[0]); - - m_mainLayout.AddComponent(&m_toolbarLayout); - m_mainLayout.AddComponent(&m_list); -} - -LogWindow::~LogWindow() -{ - for (std::vector::iterator button = m_buttons.begin(), end = m_buttons.end(); button != end; ++button) - { - delete *button; - } -} - -void LogWindow::Log(ILogger::ESeverity eSeverity, const TCHAR* message) -{ - m_messages.push_back(LogMessage(eSeverity, message)); - - if (m_filterFlags & (1 << GetSeverityIndex(eSeverity))) - { - m_list.Add(GetImageIndex(eSeverity), message); - } -} - -void LogWindow::SetFilter(ILogger::ESeverity eSeverity, bool visible) -{ - int index = GetSeverityIndex(eSeverity); - if (visible) - { - m_filterFlags |= (1 << index); - } - else - { - m_filterFlags &= ~(1 << index); - } - m_buttons[index]->SetState(visible); - RefillList(); -} - -void LogWindow::CreateUI(void* window, int left, int top, int width, int height) -{ - m_mainLayout.CreateUI(window, left, top, width, height); -} - -void LogWindow::Resize(void* window, int left, int top, int width, int height) -{ - m_mainLayout.Resize(window, left, top, width, height); -} - -void LogWindow::DestroyUI(void* window) -{ - m_mainLayout.DestroyUI(window); -} - -void LogWindow::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - m_mainLayout.GetExtremeDimensions(window, minWidth, maxWidth, minHeight, maxHeight); -} - -void LogWindow::ErrorsToggled(bool value) -{ - SetFilter(ILogger::eSeverity_Error, value); -} - -void LogWindow::WarningsToggled(bool value) -{ - SetFilter(ILogger::eSeverity_Warning, value); -} - -void LogWindow::InfoToggled(bool value) -{ - SetFilter(ILogger::eSeverity_Info, value); -} - -void LogWindow::DebugToggled(bool value) -{ - SetFilter(ILogger::eSeverity_Debug, value); -} - -void LogWindow::RefillList() -{ - m_list.Clear(); - for (int messageIndex = 0, messageCount = int(m_messages.size()); messageIndex < messageCount; ++messageIndex) - { - if (m_filterFlags & (1 << m_messages[messageIndex].severity)) - { - m_list.Add(GetImageIndex(m_messages[messageIndex].severity), m_messages[messageIndex].message.c_str()); - } - } -} - -int LogWindow::GetImageIndex(ILogger::ESeverity eSeverity) -{ - switch (eSeverity) - { - case ILogger::eSeverity_Debug: - return 2; - case ILogger::eSeverity_Info: - return -1; - case ILogger::eSeverity_Warning: - return 1; - case ILogger::eSeverity_Error: - return 0; - default: - return 0; - } -} - -int LogWindow::GetSeverityIndex(ILogger::ESeverity eSeverity) -{ - switch (eSeverity) - { - case ILogger::eSeverity_Debug: - return 0; - case ILogger::eSeverity_Info: - return 1; - case ILogger::eSeverity_Warning: - return 2; - case ILogger::eSeverity_Error: - return 3; - default: - return 3; - } -} diff --git a/Code/Tools/CryCommonTools/UI/LogWindow.h b/Code/Tools/CryCommonTools/UI/LogWindow.h deleted file mode 100644 index 13afeac57c..0000000000 --- a/Code/Tools/CryCommonTools/UI/LogWindow.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_LOGWINDOW_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_LOGWINDOW_H -#pragma once - - -#include "IUIComponent.h" -#include "Layout.h" -#include "ListView.h" -#include "ToggleButton.h" -#include -#include "ILogger.h" - -class LogWindow - : public IUIComponent -{ -public: - LogWindow(); - ~LogWindow(); - - void Log(ILogger::ESeverity eSeverity, const TCHAR* message); - void SetFilter(ILogger::ESeverity eSeverity, bool visible); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - struct LogMessage - { - LogMessage(ILogger::ESeverity severity, tstring message) - : severity(severity) - , message(message) - { - } - ILogger::ESeverity severity; - tstring message; - }; - - void ErrorsToggled(bool value); - void WarningsToggled(bool value); - void InfoToggled(bool value); - void DebugToggled(bool value); - void RefillList(); - static int GetImageIndex(ILogger::ESeverity eSeverity); - static int GetSeverityIndex(ILogger::ESeverity eSeverity); - - Layout m_mainLayout; - Layout m_toolbarLayout; - ListView m_list; - std::vector m_buttons; - std::vector m_messages; - - unsigned m_filterFlags; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_LOGWINDOW_H diff --git a/Code/Tools/CryCommonTools/UI/ProgressBar.cpp b/Code/Tools/CryCommonTools/UI/ProgressBar.cpp deleted file mode 100644 index d83c8bf3ad..0000000000 --- a/Code/Tools/CryCommonTools/UI/ProgressBar.cpp +++ /dev/null @@ -1,65 +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 "StdAfx.h" -#include "ProgressBar.h" -#include -#include - -ProgressBar::ProgressBar() - : m_progressBar(0) -{ -} - -void ProgressBar::CreateUI(void* window, int left, int top, int width, int height) -{ - m_progressBar = CreateWindowEx( - 0, - PROGRESS_CLASS, - 0, - WS_CHILD | WS_VISIBLE, - left, - top, - width, - height, - (HWND)window, - (HMENU)0, - GetModuleHandle(0), - 0); - SendMessage((HWND)m_progressBar, PBM_SETRANGE, 0, MAKELPARAM(0, 1000)); - SendMessage((HWND)m_progressBar, PBM_SETSTEP, (WPARAM) 1, 0); -} - -void ProgressBar::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_progressBar, left, top, width, height, true); -} - -void ProgressBar::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_progressBar); -} - -void ProgressBar::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 200; - maxWidth = 2000; - minHeight = 30; - maxHeight = 30; -} - -void ProgressBar::SetProgress(float progress) -{ - int newPos = int(progress * 1000.0f); - SendMessage((HWND)m_progressBar, PBM_SETPOS, newPos, 0); -} diff --git a/Code/Tools/CryCommonTools/UI/ProgressBar.h b/Code/Tools/CryCommonTools/UI/ProgressBar.h deleted file mode 100644 index 16ce456abe..0000000000 --- a/Code/Tools/CryCommonTools/UI/ProgressBar.h +++ /dev/null @@ -1,39 +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_CRYCOMMONTOOLS_UI_PROGRESSBAR_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_PROGRESSBAR_H -#pragma once - - -#include "IUIComponent.h" - -class ProgressBar - : public IUIComponent -{ -public: - ProgressBar(); - - void SetProgress(float progress); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - void* m_progressBar; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_PROGRESSBAR_H diff --git a/Code/Tools/CryCommonTools/UI/PushButton.cpp b/Code/Tools/CryCommonTools/UI/PushButton.cpp deleted file mode 100644 index e1458db0d6..0000000000 --- a/Code/Tools/CryCommonTools/UI/PushButton.cpp +++ /dev/null @@ -1,64 +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 "StdAfx.h" -#include "PushButton.h" -#include "Win32GUI.h" - -PushButton::~PushButton() -{ - m_callback->Release(); -} - -void PushButton::Enable(bool enabled) -{ - m_enabled = enabled; - EnableWindow((HWND)m_button, m_enabled); -} - -void PushButton::CreateUI(void* window, int left, int top, int width, int height) -{ - m_button = Win32GUI::CreateControl(_T("BUTTON"), WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON, (HWND)window, left, top, 40, 20); - m_font = Win32GUI::CreateFont(); - SendMessage((HWND)m_button, WM_SETFONT, (WPARAM)m_font, 0); - SendMessage((HWND)m_button, WM_SETTEXT, 0, (LPARAM)m_text.c_str()); - EnableWindow((HWND)m_button, m_enabled); - - Win32GUI::SetCallback((HWND)m_button, this, &PushButton::OnPushed); -} - -void PushButton::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_button, left, top, width, height, true); -} - -void PushButton::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_button); - m_button = 0; - DeleteObject(m_font); - m_font = 0; -} - -void PushButton::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 50; - maxWidth = 50; - minHeight = 20; - maxHeight = 20; -} - -void PushButton::OnPushed() -{ - m_callback->Call(); -} diff --git a/Code/Tools/CryCommonTools/UI/PushButton.h b/Code/Tools/CryCommonTools/UI/PushButton.h deleted file mode 100644 index a6199208d5..0000000000 --- a/Code/Tools/CryCommonTools/UI/PushButton.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_PUSHBUTTON_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_PUSHBUTTON_H -#pragma once - - -#include "IUIComponent.h" -#include - -class PushButton - : public IUIComponent -{ -public: - template - PushButton(const TCHAR* text, T* object, void (T::* method)()); - ~PushButton(); - - void Enable(bool enabled); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - PushButton(const PushButton&); - PushButton& operator=(const PushButton&); - - struct ICallback - { - virtual void Release() = 0; - virtual void Call() = 0; - }; - - template - struct Callback - : public ICallback - { - Callback(T* object, void (T::* method)()) - : object(object) - , method(method) {} - virtual void Release() {delete this; } - virtual void Call() {(object->*method)(); } - T* object; - void (T::* method)(); - }; - - void OnPushed(); - - std::basic_string m_text; - void* m_button; - void* m_font; - ICallback* m_callback; - bool m_enabled; -}; - -template -PushButton::PushButton(const TCHAR* text, T* object, void (T::* method)()) - : m_text(text) - , m_callback(new Callback(object, method)) - , m_enabled(true) -{ -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_PUSHBUTTON_H diff --git a/Code/Tools/CryCommonTools/UI/Spacer.cpp b/Code/Tools/CryCommonTools/UI/Spacer.cpp deleted file mode 100644 index 822831116e..0000000000 --- a/Code/Tools/CryCommonTools/UI/Spacer.cpp +++ /dev/null @@ -1,43 +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 "StdAfx.h" -#include "Spacer.h" - -Spacer::Spacer(int minWidth, int minHeight, int maxWidth, int maxHeight) - : m_minWidth(minWidth) - , m_minHeight(minHeight) - , m_maxWidth(maxWidth) - , m_maxHeight(maxHeight) -{ -} - -void Spacer::CreateUI(void* window, int left, int top, int width, int height) -{ -} - -void Spacer::Resize(void* window, int left, int top, int width, int height) -{ -} - -void Spacer::DestroyUI(void* window) -{ -} - -void Spacer::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = m_minWidth; - maxWidth = m_maxWidth; - minHeight = m_minHeight; - maxHeight = m_maxHeight; -} diff --git a/Code/Tools/CryCommonTools/UI/Spacer.h b/Code/Tools/CryCommonTools/UI/Spacer.h deleted file mode 100644 index 173fb7ab13..0000000000 --- a/Code/Tools/CryCommonTools/UI/Spacer.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_CRYCOMMONTOOLS_UI_SPACER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_SPACER_H -#pragma once - - -#include "IUIComponent.h" - -class Spacer - : public IUIComponent -{ -public: - Spacer(int minWidth, int minHeight, int maxWidth, int maxHeight); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - int m_minWidth; - int m_minHeight; - int m_maxWidth; - int m_maxHeight; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_SPACER_H diff --git a/Code/Tools/CryCommonTools/UI/TaskList.cpp b/Code/Tools/CryCommonTools/UI/TaskList.cpp deleted file mode 100644 index 477041fd59..0000000000 --- a/Code/Tools/CryCommonTools/UI/TaskList.cpp +++ /dev/null @@ -1,148 +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 "StdAfx.h" -#include "TaskList.h" -#include "Win32GUI.h" -#include -#include -#include -#include - -TaskList::TaskList() - : m_edit(0) -{ -} - -void TaskList::AddTask(const std::string& id, const std::string description) -{ - int taskIndex = int(m_tasks.size()); - m_tasks.push_back(std::make_pair(id, description)); - m_idTaskMap.insert(std::make_pair(id, taskIndex)); -} - -void TaskList::SetCurrentTask(const std::string& id) -{ - SetText(id); -} - -void TaskList::SetColor() -{ - SendMessage((HWND)m_edit, EM_SETBKGNDCOLOR, 0, GetSysColor(COLOR_3DFACE)); -} - -void TaskList::SetText(const std::string& highlightedTask) -{ - PARAFORMAT2 paragraphFormat; - std::memset(¶graphFormat, 0, sizeof(paragraphFormat)); - paragraphFormat.cbSize = sizeof(paragraphFormat); - paragraphFormat.dwMask = PFM_LINESPACING | PFM_SPACEBEFORE; - paragraphFormat.bLineSpacingRule = 5; // Specify spacing in 20ths of a line. - paragraphFormat.dyLineSpacing = 22; - paragraphFormat.dySpaceBefore = 70; - SendMessage((HWND)m_edit, EM_SETPARAFORMAT, 0, (LPARAM)¶graphFormat); - - CHARFORMAT format; - std::memset(&format, 0, sizeof(format)); - format.cbSize = sizeof(format); - format.dwMask = CFM_BOLD; - format.dwEffects = 0; - SendMessage((HWND)m_edit, EM_SETCHARFORMAT, 0, (LPARAM)&format); - - SETTEXTEX textEx; - std::memset(&textEx, 0, sizeof(textEx)); - textEx.flags = ST_DEFAULT; - textEx.codepage = CP_ACP; - SendMessage((HWND)m_edit, EM_SETTEXTEX, (WPARAM)&textEx, (LPARAM)_T("")); - int highlightedLineStart = 0; - int highlightedLineEnd = 0; - - for (std::vector >::const_iterator taskPos = m_tasks.begin(), taskEnd = m_tasks.end(); taskPos != taskEnd; ++taskPos) - { - textEx.flags = ST_SELECTION; - const std::string& id = (*taskPos).first; - const std::string& description = (*taskPos).second; - const char* margin = " "; - if (highlightedTask == id) - { - margin = "* "; - CHARRANGE range; - SendMessage((HWND)m_edit, EM_EXGETSEL, 0, (LPARAM)&range); - highlightedLineStart = range.cpMin; - } - SendMessageA((HWND)m_edit, EM_SETTEXTEX, (WPARAM)&textEx, (LPARAM)margin); - SendMessageA((HWND)m_edit, EM_SETTEXTEX, (WPARAM)&textEx, (LPARAM)description.c_str()); - SendMessageA((HWND)m_edit, EM_SETTEXTEX, (WPARAM)&textEx, (LPARAM)"\n"); - if (highlightedTask == id) - { - CHARRANGE range; - SendMessage((HWND)m_edit, EM_EXGETSEL, 0, (LPARAM)&range); - highlightedLineEnd = range.cpMin; - } - } - - CHARRANGE range = {highlightedLineStart, highlightedLineEnd}; - SendMessage((HWND)m_edit, EM_EXSETSEL, 0, (LPARAM)&range); - - format.dwEffects = CFE_BOLD; - SendMessage((HWND)m_edit, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format); - - range.cpMin = 0; - range.cpMax = 0; - SendMessage((HWND)m_edit, EM_EXSETSEL, 0, (LPARAM)&range); -} - -void TaskList::CreateUI(void* window, int left, int top, int width, int height) -{ - // Create the window. - LoadLibrary(_T("Riched20.dll")); - m_edit = CreateWindowEx( - 0, //DWORD dwExStyle, - RICHEDIT_CLASS, //LPCTSTR lpClassName, - 0, //LPCTSTR lpWindowName, - WS_CHILD | WS_VISIBLE | ES_LEFT | ES_MULTILINE | ES_READONLY, //DWORD dwStyle, - left, //int x, - top, //int y, - width, //int nWidth, - height, //int nHeight, - (HWND)window, //HWND hWndParent, - 0, //HMENU hMenu, - GetModuleHandle(0), //HINSTANCE hInstance, - 0); //LPVOID lpParam); - HFONT font = Win32GUI::CreateFont(); - SendMessage((HWND)m_edit, WM_SETFONT, (WPARAM)font, 0); - DeleteObject(font); - SetColor(); - - SetText(""); -} - -void TaskList::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_edit, left, top, width, height, true); -} - -void TaskList::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_edit); - m_edit = 0; -} - -void TaskList::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 10; - maxWidth = 2000; - int height = 25 * int(m_tasks.size()); - minHeight = height; - maxHeight = height; -} diff --git a/Code/Tools/CryCommonTools/UI/TaskList.h b/Code/Tools/CryCommonTools/UI/TaskList.h deleted file mode 100644 index 54f825a5b5..0000000000 --- a/Code/Tools/CryCommonTools/UI/TaskList.h +++ /dev/null @@ -1,48 +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_CRYCOMMONTOOLS_UI_TASKLIST_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_TASKLIST_H -#pragma once - - -#include "IUIComponent.h" -#include -#include -#include - -class TaskList - : public IUIComponent -{ -public: - TaskList(); - - void AddTask(const std::string& id, const std::string description); - void SetCurrentTask(const std::string& id); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - void SetColor(); - void SetText(const std::string& highlightedTask); - - std::map m_idTaskMap; - std::vector > m_tasks; - void* m_edit; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_TASKLIST_H diff --git a/Code/Tools/CryCommonTools/UI/ToggleButton.cpp b/Code/Tools/CryCommonTools/UI/ToggleButton.cpp deleted file mode 100644 index 6f93a9c303..0000000000 --- a/Code/Tools/CryCommonTools/UI/ToggleButton.cpp +++ /dev/null @@ -1,65 +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 "StdAfx.h" -#include "ToggleButton.h" -#include "Win32GUI.h" - -ToggleButton::~ToggleButton() -{ - m_callback->Release(); -} - -void ToggleButton::SetState(bool state) -{ - m_state = state; - SendMessage((HWND)m_button, BM_SETCHECK, m_state, 0); -} - -void ToggleButton::CreateUI(void* window, int left, int top, int width, int height) -{ - m_button = Win32GUI::CreateControl(_T("BUTTON"), WS_VISIBLE | WS_CHILD | BS_AUTOCHECKBOX | BS_NOTIFY | BS_PUSHLIKE, (HWND)window, left, top, 40, 20); - m_font = Win32GUI::CreateFont(); - SendMessage((HWND)m_button, WM_SETFONT, (WPARAM)m_font, 0); - SendMessage((HWND)m_button, WM_SETTEXT, 0, (LPARAM)m_text.c_str()); - SendMessage((HWND)m_button, BM_SETCHECK, m_state, 0); - - Win32GUI::SetCallback((HWND)m_button, this, &ToggleButton::OnChecked); -} - -void ToggleButton::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_button, left, top, width, height, true); -} - -void ToggleButton::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_button); - m_button = 0; - DeleteObject(m_font); - m_font = 0; -} - -void ToggleButton::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 50; - maxWidth = 50; - minHeight = 20; - maxHeight = 20; -} - -void ToggleButton::OnChecked(bool checked) -{ - m_state = checked; - m_callback->Call(checked); -} diff --git a/Code/Tools/CryCommonTools/UI/ToggleButton.h b/Code/Tools/CryCommonTools/UI/ToggleButton.h deleted file mode 100644 index 27eec0906c..0000000000 --- a/Code/Tools/CryCommonTools/UI/ToggleButton.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_TOGGLEBUTTON_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_TOGGLEBUTTON_H -#pragma once - - -#include "IUIComponent.h" -#include - -class ToggleButton - : public IUIComponent -{ -public: - template - ToggleButton(const TCHAR* text, T* object, void (T::* method)(bool value)); - ~ToggleButton(); - - void SetState(bool value); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - ToggleButton(const ToggleButton&); - ToggleButton& operator=(const ToggleButton); - - struct ICallback - { - virtual void Release() = 0; - virtual void Call(bool value) = 0; - }; - - template - struct Callback - : public ICallback - { - Callback(T* object, void (T::* method)(bool value)) - : object(object) - , method(method) {} - virtual void Release() {delete this; } - virtual void Call(bool value) {(object->*method)(value); } - T* object; - void (T::* method)(bool value); - }; - - void OnChecked(bool checked); - - tstring m_text; - void* m_button; - void* m_font; - bool m_state; - ICallback* m_callback; -}; - -template -ToggleButton::ToggleButton(const TCHAR* text, T* object, void (T::* method)(bool value)) - : m_text(text) - , m_state(false) - , m_callback(new Callback(object, method)) -{ -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_TOGGLEBUTTON_H diff --git a/Code/Tools/CryCommonTools/UI/Win32GUI.cpp b/Code/Tools/CryCommonTools/UI/Win32GUI.cpp deleted file mode 100644 index e34348271d..0000000000 --- a/Code/Tools/CryCommonTools/UI/Win32GUI.cpp +++ /dev/null @@ -1,390 +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 "StdAfx.h" -#include "Win32GUI.h" -#include -#include -#include -#include -#include "commctrl.h" -#include "StringHelpers.h" - -namespace Win32GUI -{ - const int WM_REFLECT_BASE = WM_USER + 0x1c00; - const int WM_COMMAND_REFLECT = WM_REFLECT_BASE + WM_COMMAND; - const int WM_NOTIFY_REFLECT = WM_REFLECT_BASE + WM_NOTIFY; - - class Window - { - public: - typedef LRESULT (Window::* WindowProcMethod)(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - - Window(WindowProcMethod windowProc); - ~Window(); - static LRESULT CALLBACK StaticWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - LRESULT WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - LRESULT FrameWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - - void Subclass(HWND window); - void Unsubclass(HWND window); - - WNDPROC m_oldWndProc; - WindowProcMethod m_windowProc; - typedef std::multimap CallbackMap; - CallbackMap m_callbackMap; - }; -} - -void Win32GUI::Initialize() -{ - InitCommonControls(); - LoadLibrary(_T("riched20.dll")); -} - -void Win32GUI::RegisterFrameClass(const TCHAR* name) -{ - WNDCLASS cls; - std::memset(&cls, 0, sizeof(cls)); - cls.style = 0; - cls.lpfnWndProc = &Window::StaticWindowProc; - cls.cbClsExtra = 0; - cls.cbWndExtra = 0; - cls.hInstance = GetModuleHandle(0); - cls.hIcon = 0; - cls.hCursor = LoadCursor(0, IDC_ARROW); - cls.hbrBackground = GetSysColorBrush(COLOR_BTNFACE); - cls.lpszMenuName = 0; - cls.lpszClassName = name; - - RegisterClass(&cls); -} - -HWND Win32GUI::CreateFrame(const TCHAR* className, unsigned style, int width, int height) -{ - Window* window = new Window(&Window::FrameWindowProc); - - HWND hwnd = CreateWindow( - className, // LPCTSTR lpClassName, - TEXT(""), // LPCTSTR lpWindowName, - style, // DWORD dwStyle, - CW_USEDEFAULT, // int x, - CW_USEDEFAULT, // int y, - width, // int nWidth, - height, // int nHeight, - 0, // HWND hWndParent, - 0, // HMENU hMenu, - GetModuleHandle(0), // HINSTANCE hInstance, - window); // LPVOID lpParam - - return hwnd; -} - -HWND Win32GUI::CreateControl(const TCHAR* className, unsigned style, HWND parent, int left, int top, int width, int height) -{ - Window* window = new Window(&Window::WindowProc); - - HWND hwnd = CreateWindow( - className, // LPCTSTR lpClassName, - 0, // LPCTSTR lpWindowName, - style | WS_CHILD | WS_VISIBLE, // DWORD dwStyle, - left, // int x, - top, // int y, - width, // int nWidth, - height, // int nHeight, - parent, // HWND hWndParent, - 0, // HMENU hMenu, - GetModuleHandle(0), // HINSTANCE hInstance, - 0); // LPVOID lpParam - - window->Subclass(hwnd); - - return hwnd; -} - -int Win32GUI::Run() -{ - MSG msg; - BOOL status; - while ((status = GetMessage(&msg, HWND(0), UINT(0), UINT(0))) != 0) - { - if (status == -1) - { - return -1; - } - else - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - - return (int)msg.wParam; -} - -Win32GUI::Window::Window(WindowProcMethod windowProc) - : m_windowProc(windowProc) - , m_oldWndProc(0) -{ -} - -Win32GUI::Window::~Window() -{ - for (CallbackMap::iterator callbackPos = m_callbackMap.begin(); callbackPos != m_callbackMap.end(); ++callbackPos) - { - (*callbackPos).second->Release(); - } -} - -LRESULT CALLBACK Win32GUI::Window::StaticWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - Window* window = 0; - { - if (uMsg == WM_CREATE) - { - CREATESTRUCT* create_struct = (CREATESTRUCT*)lParam; - window = (Window*)create_struct->lpCreateParams; -#if defined(_WIN64) - SetWindowLongPtr(hwnd, GWLP_USERDATA, LONG_PTR(window)); -#else //defined(_WIN64) - SetWindowLong(hwnd, GWL_USERDATA, PtrToLong(window)); -#endif //defined(_WIN64) - } - else - { -#if defined(_WIN64) - window = (Window*)GetWindowLongPtr(hwnd, GWLP_USERDATA); -#else //defined(_WIN64) - window = (Window*)LongToPtr(GetWindowLong(hwnd, GWL_USERDATA)); -#endif //defined(_WIN64) - } - } - - LRESULT result = 0; - if (window) - { - result = (window->*(window->m_windowProc))(hwnd, uMsg, wParam, lParam); - } - else - { - result = DefWindowProc(hwnd, uMsg, wParam, lParam); - } - - if (uMsg == WM_DESTROY) - { - delete window; -#if defined(_WIN64) - SetWindowLongPtr(hwnd, GWLP_USERDATA, 0); -#else //defined(_WIN64) - SetWindowLong(hwnd, GWL_USERDATA, 0); -#endif //defined(_WIN64) - } - - return result; -} - -LRESULT Win32GUI::Window::WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - switch (uMsg) - { - case WM_COMMAND: - { - HWND control = (HWND)lParam; - if (control) - { - SendMessage(control, WM_COMMAND_REFLECT, wParam, lParam); - } - } - break; - - case WM_NOTIFY: - { - NMHDR* notify_header = reinterpret_cast(lParam); - if (notify_header->hwndFrom) - { - SendMessage(notify_header->hwndFrom, WM_NOTIFY_REFLECT, wParam, lParam); - } - } - break; - - case WM_COMMAND_REFLECT: - switch (HIWORD(wParam)) - { - case EN_CHANGE: - { - std::string text = GetWindowString(hwnd); - - std::pair range = m_callbackMap.equal_range(EventCallbacks::TextChanged::ID); - for (CallbackMap::iterator callbackPos = range.first; callbackPos != range.second; ++callbackPos) - { - EventCallbacks::IStringCallback* callback = static_cast((*callbackPos).second); - callback->Call(text); - } - } - break; - - case BN_CLICKED: - { - if (GetWindowLong(hwnd, GWL_STYLE) & BS_CHECKBOX) - { - bool checked = (0 != SendMessage(hwnd, BM_GETCHECK, 0, 0)); - std::pair range = m_callbackMap.equal_range(EventCallbacks::Checked::ID); - for (CallbackMap::iterator callbackPos = range.first; callbackPos != range.second; ++callbackPos) - { - EventCallbacks::IBoolCallback* callback = static_cast((*callbackPos).second); - callback->Call(checked); - } - } - else - { - std::pair range = m_callbackMap.equal_range(EventCallbacks::Pushed::ID); - for (CallbackMap::iterator callbackPos = range.first; callbackPos != range.second; ++callbackPos) - { - EventCallbacks::IVoidCallback* callback = static_cast((*callbackPos).second); - callback->Call(); - } - } - } - break; - } - break; - - case WM_GETMINMAXINFO: - { - int minW = 0, maxW = 0, minH = 100000, maxH = 100000; - - std::pair range = m_callbackMap.equal_range(EventCallbacks::GetDimensions::ID); - for (CallbackMap::iterator callbackPos = range.first; callbackPos != range.second; ++callbackPos) - { - EventCallbacks::IGetDimensionsCallback* callback = static_cast((*callbackPos).second); - callback->Call(minW, maxW, minH, maxH); - } - - MINMAXINFO* minMaxInfo = (MINMAXINFO*)lParam; - minMaxInfo->ptMinTrackSize.x = minW; - minMaxInfo->ptMaxTrackSize.x = maxW; - minMaxInfo->ptMinTrackSize.y = minH; - minMaxInfo->ptMaxTrackSize.y = maxH; - } - break; - - case WM_SIZE: - { - int width = LOWORD(lParam); - int height = HIWORD(lParam); - std::pair range = m_callbackMap.equal_range(EventCallbacks::SizeChanged::ID); - for (CallbackMap::iterator callbackPos = range.first; callbackPos != range.second; ++callbackPos) - { - EventCallbacks::ISizeCallback* callback = static_cast((*callbackPos).second); - callback->Call(width, height); - } - } - break; - - case WM_NOTIFY_REFLECT: - break; - } - - LRESULT result = 0; - if (m_oldWndProc) - { - result = CallWindowProc(m_oldWndProc, hwnd, uMsg, wParam, lParam); - } - else - { - result = DefWindowProc(hwnd, uMsg, wParam, lParam); - } - - return result; -} - -LRESULT Win32GUI::Window::FrameWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - switch (uMsg) - { - case WM_CLOSE: - PostQuitMessage(0); - break; - } - - return WindowProc(hwnd, uMsg, wParam, lParam); -} - -void Win32GUI::Window::Subclass(HWND window) -{ -#if defined(_WIN64) - SetWindowLongPtr(window, GWLP_USERDATA, LONG_PTR(this)); - m_oldWndProc = (WNDPROC)GetWindowLongPtr(window, GWLP_WNDPROC); - SetWindowLongPtr(window, GWLP_WNDPROC, LONG_PTR(&Window::StaticWindowProc)); -#else //defined(_WIN64) - SetWindowLong(window, GWL_USERDATA, PtrToLong(this)); - m_oldWndProc = (WNDPROC)LongToPtr(GetWindowLong(window, GWL_WNDPROC)); - SetWindowLong(window, GWL_WNDPROC, PtrToLong(&Window::StaticWindowProc)); -#endif //defined(_WIN64) -} - -void Win32GUI::Window::Unsubclass(HWND window) -{ -#if defined(_WIN64) - SetWindowLongPtr(window, GWLP_USERDATA, 0); - SetWindowLongPtr(window, GWLP_WNDPROC, LONG_PTR(m_oldWndProc)); -#else //defined(_WIN64) - SetWindowLongPtr(window, GWL_USERDATA, 0); - SetWindowLong(window, GWLP_WNDPROC, PtrToLong(m_oldWndProc)); -#endif //defined(_WIN64) - m_oldWndProc = 0; -} - -std::string Win32GUI::GetWindowString(HWND hwnd) -{ - LRESULT length = SendMessage(hwnd, WM_GETTEXTLENGTH, 0, 0); - std::wstring wtext(length, 0); - SendMessageW(hwnd, WM_GETTEXT, length + 1, (LPARAM)&wtext[0]); - return StringHelpers::ConvertUtf16ToAnsi(wtext.c_str(), '?'); -} - -void Win32GUI::SetWindowString(HWND hwnd, const std::string& text) -{ - std::wstring wtext = StringHelpers::ConvertAnsiToUtf16(text.c_str()); - SendMessageW(hwnd, WM_SETTEXT, 0, (LPARAM)&wtext[0]); -} - -HFONT Win32GUI::CreateFont() -{ - HFONT hFont = 0; - HFONT hGuiFont = static_cast(::GetStockObject(DEFAULT_GUI_FONT)); - - LOGFONT lfGuiFont = { 0 }; - if (::GetObject(hGuiFont, sizeof(LOGFONT), &lfGuiFont) == sizeof(LOGFONT)) - { - _tcsncpy(lfGuiFont.lfFaceName, _T("MS Shell Dlg 2"), sizeof(lfGuiFont.lfFaceName) / sizeof(TCHAR)); - lfGuiFont.lfFaceName[(sizeof(lfGuiFont.lfFaceName) / sizeof(TCHAR)) - 1] = '\0'; - - hFont = ::CreateFontIndirect(&lfGuiFont); - - return hFont; - } - return 0; -} - -void Win32GUI::SetCallbackObject(HWND hwnd, unsigned eventID, EventCallbacks::ICallback* callback) -{ -#if defined(_WIN64) - Window* window = (Window*)GetWindowLongPtr(hwnd, GWLP_USERDATA); -#else //defined(_WIN64) - Window* window = (Window*)LongToPtr(GetWindowLong(hwnd, GWL_USERDATA)); -#endif //defined(_WIN64) - - window->m_callbackMap.insert(std::make_pair(eventID, callback)); -} diff --git a/Code/Tools/CryCommonTools/UI/Win32GUI.h b/Code/Tools/CryCommonTools/UI/Win32GUI.h deleted file mode 100644 index 60b91ece9f..0000000000 --- a/Code/Tools/CryCommonTools/UI/Win32GUI.h +++ /dev/null @@ -1,216 +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_CRYCOMMONTOOLS_UI_WIN32GUI_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_WIN32GUI_H -#pragma once - - -#include -#include - -namespace Win32GUI -{ - void Initialize(); - void RegisterFrameClass(const TCHAR* name); - HWND CreateFrame(const TCHAR* className, unsigned style, int width, int height); - HWND CreateControl(const TCHAR* className, unsigned style, HWND parent, int left, int top, int width, int height); - int Run(); - std::string GetWindowString(HWND hwnd); - void SetWindowString(HWND hwnd, const std::string& text); - HFONT CreateFont(); - - namespace EventCallbacks - { - class ICallback - { - public: - virtual ~ICallback() {} - virtual void Release() = 0; - }; - - struct IVoidCallback - : public ICallback - { - virtual void Call() = 0; - }; - - struct VoidCallback - { - template - struct Callback - : public IVoidCallback - { - typedef void (O::* Signature)(); - - Callback(O* object, Signature method) - : m_object(object) - , m_method(method) {} - virtual void Release() {delete this; } - virtual void Call() {(m_object->*m_method)(); } - O* m_object; - Signature m_method; - }; - }; - - struct IStringCallback - : public ICallback - { - virtual void Call(const std::string& text) = 0; - }; - - struct StringCallback - { - template - struct Callback - : public IStringCallback - { - typedef void (O::* Signature)(const std::string& text); - - Callback(O* object, Signature method) - : m_object(object) - , m_method(method) {} - virtual void Release() {delete this; } - virtual void Call(const std::string& text) {(m_object->*m_method)(text); } - O* m_object; - Signature m_method; - }; - }; - - struct IGetDimensionsCallback - : public ICallback - { - virtual void Call(int& minW, int& maxW, int& minH, int& maxH) = 0; - }; - - struct GetDimensionsCallback - { - template - struct Callback - : public IGetDimensionsCallback - { - typedef void (O::* Signature)(int& minW, int& maxW, int& minH, int& maxH); - - Callback(O* object, Signature method) - : m_object(object) - , m_method(method) {} - virtual void Release() {delete this; } - virtual void Call(int& minW, int& maxW, int& minH, int& maxH) {(m_object->*m_method)(minW, maxW, minH, maxH); } - O* m_object; - Signature m_method; - }; - }; - - struct ISizeCallback - : public ICallback - { - virtual void Call(int width, int height) = 0; - }; - - struct SizeCallback - { - template - struct Callback - : public ISizeCallback - { - typedef void (O::* Signature)(int width, int height); - - Callback(O* object, Signature method) - : m_object(object) - , m_method(method) {} - virtual void Release() {delete this; } - virtual void Call(int width, int height) {(m_object->*m_method)(width, height); } - O* m_object; - Signature m_method; - }; - }; - - struct IBoolCallback - : public ICallback - { - virtual void Call(bool value) = 0; - }; - - struct BoolCallback - { - template - struct Callback - : public IBoolCallback - { - typedef void (O::* Signature)(bool callback); - Callback(O* object, Signature method) - : m_object(object) - , m_method(method) {} - virtual void Release() {delete this; } - virtual void Call(bool value) {(m_object->*m_method)(value); } - O* m_object; - Signature m_method; - }; - }; - - struct TextChanged - : public StringCallback - { - enum - { - ID = 0x00005001 - }; - }; - struct GetDimensions - : public GetDimensionsCallback - { - enum - { - ID = 0x00005002 - }; - }; - struct SizeChanged - : public SizeCallback - { - enum - { - ID = 0x00005003 - }; - }; - struct Pushed - : public VoidCallback - { - enum - { - ID = 0x00005004 - }; - }; - struct Checked - : public BoolCallback - { - enum - { - ID = 0x00005005 - }; - }; - }; - - void SetCallbackObject(HWND hwnd, unsigned eventID, EventCallbacks::ICallback* callback); - template - inline void SetCallback(HWND hwnd, O* object, typename T::template Callback::Signature method); -} - -template -inline void Win32GUI::SetCallback(HWND hwnd, O* object, typename T::template Callback::Signature method) -{ - typedef T::template Callback Callback; - Callback* callback = new Callback(object, method); - SetCallbackObject(hwnd, T::ID, callback); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_WIN32GUI_H diff --git a/Gems/LyShine/Code/Editor/PropertyHandlerSprite.cpp b/Gems/LyShine/Code/Editor/PropertyHandlerSprite.cpp index 20721d4624..5123d120d5 100644 --- a/Gems/LyShine/Code/Editor/PropertyHandlerSprite.cpp +++ b/Gems/LyShine/Code/Editor/PropertyHandlerSprite.cpp @@ -27,8 +27,6 @@ #include "SpriteBorderEditorCommon.h" -#include - #include #include From 33f7da764e16ad7ee5026aa4ac4c2c8a39a01e41 Mon Sep 17 00:00:00 2001 From: Shirang Jia Date: Wed, 12 May 2021 10:05:42 -0700 Subject: [PATCH 075/100] Remove unneeded scripts that have internal service references (#683) --- scripts/build/tools/alert_build_failures.py | 76 ------------ scripts/build/tools/email_to_lionbridge.py | 128 -------------------- 2 files changed, 204 deletions(-) delete mode 100755 scripts/build/tools/alert_build_failures.py delete mode 100755 scripts/build/tools/email_to_lionbridge.py diff --git a/scripts/build/tools/alert_build_failures.py b/scripts/build/tools/alert_build_failures.py deleted file mode 100755 index 486d84123d..0000000000 --- a/scripts/build/tools/alert_build_failures.py +++ /dev/null @@ -1,76 +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. -# - -import os -from incremental_build_util import get_iam_role_credentials -try: - import requests -except ImportError: - import pip - pip.main(['install', 'requests', '--ignore-installed', '-q']) - import requests -try: - from requests_aws4auth import AWS4Auth -except ImportError: - import pip - pip.main(['install', 'requests_aws4auth', '--ignore-installed', '-q']) - from requests_aws4auth import AWS4Auth - -IAM_ROLE_NAME = 'ec2-jenkins-node' -TEAM = 'lumberyard-build' -CHIME_ROOM_WEB_HOOK = "https://hooks.chime.aws/incomingwebhooks/2a6018c9-3bf5-4e03-851c-32ba82c7c4e2?token=YWhTVXZsWVJ8MXxaLTg5RkVZNlA5Q1NiMVdfQndGeS1TSHNnYW5VREVha3pjX1pUUEd5b1JF" - - -def find_curr_oncalls_for_team(team): - host = "who-is-oncall-pdx.corp.amazon.com" - service_name = "who-is-oncall" - aws_region = "us-west-2" - headers = {"content-type": "application/json", "host": host} - - credentials = get_iam_role_credentials(IAM_ROLE_NAME) - try: - aws_access_key_id = credentials['AccessKeyId'] - aws_secret_access_key = credentials['SecretAccessKey'] - aws_session_token = credentials['Token'] - except Exception as e: - print(f'ERROR: Cannot get AWS credentials.\n{e}') - return ['All'] - - auth = AWS4Auth(aws_access_key_id, aws_secret_access_key, aws_region, service_name, session_token=aws_session_token) - r = requests.get(f"https://who-is-oncall-pdx.corp.amazon.com/teams/{team}", headers=headers, auth=auth, verify=False) - if r.ok: - res = r.json() - try: - return res['currOncalls'] - except KeyError: - return ['All'] - return ['All'] - - -def send_alert_to_chime_room(web_hook, content): - data = '{"Content":"' + content + '"}' - headers = {'Content-Type': 'application/json'} - requests.post(web_hook, headers=headers, data=data) - - -def create_content(): - content = '' - oncalls = find_curr_oncalls_for_team(TEAM) - for oncall in oncalls: - content += f'@{oncall} ' - job_name = os.environ['JOB_NAME'] - build_url = os.environ['BUILD_URL'] - content += fr'\nJob {job_name} failed\nBuild URL: {build_url}\n' - return content - - -send_alert_to_chime_room(CHIME_ROOM_WEB_HOOK, create_content()) - diff --git a/scripts/build/tools/email_to_lionbridge.py b/scripts/build/tools/email_to_lionbridge.py deleted file mode 100755 index 7f522bb564..0000000000 --- a/scripts/build/tools/email_to_lionbridge.py +++ /dev/null @@ -1,128 +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. -# - -""" -This script will be used in the Sandobx Jenkins job PACKAGE_COPY_S3 -PACKAGE_COPY_S3 is a downstream job of nightly packaging job, it copies the nightly packages from Infra S3 bucket to Lionbridge S3 bucket based on the INCLUDE_FILTER passed from packaging job -""" -import os -import re -import json -import requests -from requests.auth import HTTPBasicAuth -import boto3 -from util import error, warn - - -# Write EMAIL_TEMPLATE to a file and inject it into the email sent to Lionbridge -EMAIL_TEMPLATE = '''Packages are uploaded to S3 bucket {} -Package List: -{} - - -Changelists: -{} -''' - - -def get_jenkins_env(key): - try: - return os.environ[key] - except KeyError: - print('Error: Jenkins parameters {} is not set.'.format(key)) - return None - - -JENKINS_USERNAME = get_jenkins_env('JENKINS_USERNAME') -JENKINS_API_TOKEN = get_jenkins_env('JENKINS_API_TOKEN') -JENKINS_URL = get_jenkins_env('JENKINS_URL') -WORKSPACE = get_jenkins_env('WORKSPACE') -S3_TARGET = get_jenkins_env('S3_TARGET') -INCLUDE_FILTER = get_jenkins_env('INCLUDE_FILTER') -EMAIL_TEMPLATE_FILE = get_jenkins_env('EMAIL_TEMPLATE_FILE') -if None in [JENKINS_USERNAME, JENKINS_API_TOKEN, JENKINS_URL, WORKSPACE, S3_TARGET, INCLUDE_FILTER, EMAIL_TEMPLATE_FILE]: - error('Please make sure all Jenkins parameters are set correctly.') - - -def parse_include_filter(include_filter): - try: - res = re.search('^(\w*)-*lumberyard-(\d+)\.(\d+)-(\d+)-(\w+).*\*(\d+)\.\*', include_filter) - branch = res.group(1) - major_version = int(res.group(2)) - minor_version = int(res.group(3)) - changelist_number = res.group(4) - platform = res.group(5) - build_number = res.group(6) - return branch, major_version, minor_version, changelist_number, platform, build_number - except (AttributeError, IndexError): - error('Unable to parse INCLUDE_FILTER, please make sure the INCLUDE_FILTER is set correctly') - - -# Get the changelists that trigger the build -def get_changelists(job_name, build_number): - changelists = [] - headers = {'Content-type': 'application/json', 'Accept': 'application/json'} - try: - res = requests.get('{}/job/{}/{}/api/json'.format(JENKINS_URL, job_name, build_number), - auth=HTTPBasicAuth(JENKINS_USERNAME, JENKINS_API_TOKEN), headers=headers, verify=False) - res = json.loads(res.content) - changelists = res.get('changeSet').get('items') - return changelists - except: - warn('Error: Failed to get changes from build {} in job {}'.format(build_number, job_name)) - return [] - - -def get_packaging_job_name(branch, major_version, minor_version, platform): - if branch == '': - branch = 'ML' if major_version + minor_version == 0 else 'v{}_{}'.format(major_version, minor_version) - job_name = 'PKG_{}_{}'.format(branch, platform.capitalize()) - return job_name - - -# Get package names by looking up S3 bucket -def get_package_names(branch, major_version, minor_version, include_filter, build_number): - package_names = [] - prefix = include_filter[:include_filter.find('*')] - pattern = '.*{}.*{}..*'.format(prefix, build_number) - if branch == '': - bucket_name = 'ly-packages-mainline' if major_version + minor_version == 0 else 'ly-packages-release-candidate' - folder = 'lumberyard-packages' - else: - bucket_name = 'ly-packages-feature-branches' - folder = 'lumberyard-packages/{}'.format(branch) - s3 = boto3.resource('s3') - bucket = s3.Bucket(bucket_name) - for obj in bucket.objects.filter(Prefix='{}/{}'.format(folder, prefix)): - package_name = obj.key - if re.match(pattern, package_name): - package_names.append(package_name.replace('{}/'.format(folder), '')) - return package_names - - -if __name__ == "__main__": - branch, major_version, minor_version, changelist_number, platform, build_number = parse_include_filter(INCLUDE_FILTER) - packaging_job_name = get_packaging_job_name(branch, major_version, minor_version, platform) - changelists = get_changelists(packaging_job_name, build_number) - package_names = get_package_names(branch, major_version, minor_version, INCLUDE_FILTER, build_number) - with open(os.path.join(WORKSPACE, EMAIL_TEMPLATE_FILE), 'w+') as output: - if len(package_names) > 0: - package_list_str = '\n'.join(package_names) - changelists_str = '' - for item in changelists: - changelists_str += '---------------------------------------------------------------------------------------------\n' - try: - changelists_str += 'CL{} by {} on {}\n{}\n'.format(item['changeNumber'], item['author']['fullName'], item['changeTime'], item['msg'].encode('utf-8', 'ignore')) - except KeyError: - error('Internal error, check the output of Jenkins API.') - output.write(EMAIL_TEMPLATE.format(S3_TARGET, package_list_str, changelists_str)) - - From 3383cfc95a33145114893ba6dd98cc9775a90ab5 Mon Sep 17 00:00:00 2001 From: amzn-sj Date: Wed, 12 May 2021 10:20:03 -0700 Subject: [PATCH 076/100] Fix Jenkins failure during engine registration for iOS --- scripts/build/Platform/iOS/build_config.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/build/Platform/iOS/build_config.json b/scripts/build/Platform/iOS/build_config.json index 4566d243ee..bb5f2d2fe6 100644 --- a/scripts/build/Platform/iOS/build_config.json +++ b/scripts/build/Platform/iOS/build_config.json @@ -27,7 +27,7 @@ "PARAMETERS": { "CONFIGURATION": "debug", "OUTPUT_DIRECTORY": "build/ios", - "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "-destination generic/platform=iOS" @@ -44,7 +44,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/ios", - "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "-destination generic/platform=iOS" @@ -60,7 +60,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/ios", - "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=FALSE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=FALSE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "-destination generic/platform=iOS" @@ -94,7 +94,7 @@ "PARAMETERS": { "CONFIGURATION": "release", "OUTPUT_DIRECTORY": "build/ios", - "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "-destination generic/platform=iOS" From 3569ac9b873f1a996d306eb06646195574710095 Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Wed, 12 May 2021 13:13:28 -0500 Subject: [PATCH 077/100] Bringing back RHI modules to tools deps --- .../Source/Platform/Linux/additional_linux_tool_deps.cmake | 3 +++ .../Code/Source/Platform/Mac/additional_mac_tool_deps.cmake | 3 +++ .../Source/Platform/Windows/additional_windows_tool_deps.cmake | 3 +++ 3 files changed, 9 insertions(+) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake index 908417b1f8..c76527afa0 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake @@ -10,6 +10,9 @@ # set(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Vulkan.Private + Gem::Atom_RHI_DX12.Private + Gem::Atom_RHI_Metal.Private Gem::Atom_RHI_Vulkan.Builders Gem::Atom_RHI_DX12.Builders Gem::Atom_RHI_Metal.Builders diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake index 445a416a68..81046d3071 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake @@ -10,6 +10,9 @@ # set(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Metal.Private + Gem::Atom_RHI_Vulkan.Private + Gem::Atom_RHI_DX12.Private Gem::Atom_RHI_Metal.Builders Gem::Atom_RHI_Vulkan.Builders Gem::Atom_RHI_DX12.Builders diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake index 908417b1f8..c76527afa0 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake @@ -10,6 +10,9 @@ # set(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Vulkan.Private + Gem::Atom_RHI_DX12.Private + Gem::Atom_RHI_Metal.Private Gem::Atom_RHI_Vulkan.Builders Gem::Atom_RHI_DX12.Builders Gem::Atom_RHI_Metal.Builders From b5d7ae829a4c44a9d89bb104b55135ffc9059d19 Mon Sep 17 00:00:00 2001 From: zsolleci Date: Wed, 12 May 2021 14:10:54 -0500 Subject: [PATCH 078/100] addressed internal review feedback --- .../scripting/Node_HappyPath_DuplicateNode.py | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py b/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py index 9d8cccd027..77d3b2fcde 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py @@ -12,9 +12,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # fmt: off class Tests(): - open_sc_window = ("Script Canvas window is opened", "Failed to open Script Canvas window") - node_added = ("Successfully added node to graph", "Failed to add node to graph") - node_duplicated = ("Successfully duplicated node", "Failed to duplicate the node") + node_duplicated = ("Successfully duplicated node", "Failed to duplicate the node") # fmt: on @@ -30,9 +28,8 @@ def Node_HappyPath_DuplicateNode(): 1) Open Script Canvas window (Tools > Script Canvas) 2) Open a new graph 3) Add node to graph - 4) Select node in graph to verify existence - 5) Mock Ctrl+D to duplicate node - 6) Verify the node was duplicated + 4) Duplicate node + 5) Verify the node was duplicated6) Verify the node was duplicated Note: - This test file must be called from the Open 3D Engine Editor command terminal @@ -68,11 +65,9 @@ def Node_HappyPath_DuplicateNode(): def grab_title_text(): scroll_area = node_inspector.findChild(QtWidgets.QScrollArea, "") QtTest.QTest.keyClick(graph, "a", Qt.ControlModifier, WAIT_FRAMES) - general.idle_wait(1.0) background = scroll_area.findChild(QtWidgets.QFrame, "Background") title = background.findChild(QtWidgets.QLabel, "Title") text = title.findChild(QtWidgets.QLabel, "Title") - print(text.text()) return text.text() # 1) Open Script Canvas window (Tools > Script Canvas) @@ -80,29 +75,35 @@ def Node_HappyPath_DuplicateNode(): general.open_pane("Script Canvas") helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) - # # 2) Open a new graph + # 2) Open a new graph editor_window = pyside_utils.get_editor_main_window() sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") sc_main = sc.findChild(QtWidgets.QMainWindow) create_new_graph = pyside_utils.find_child_by_pattern( sc_main, {"objectName": "action_New_Script", "type": QtWidgets.QAction} ) + if sc.findChild(QtWidgets.QDockWidget, "NodeInspector") is None: + action = pyside_utils.find_child_by_pattern(sc, {"text": "Node Inspector", "type": QtWidgets.QAction}) + action.trigger() node_inspector = sc.findChild(QtWidgets.QDockWidget, "NodeInspector") create_new_graph.trigger() # 3) Add node command_line_input("add_node Print") - # 4) Select node in graph to verify existence + # 4) Duplicate node graph_view = sc.findChild(QtWidgets.QFrame, "graphicsViewFrame") graph = graph_view.findChild(QtWidgets.QWidget, "") - - # 5) Duplicate node + # There are currently no utilities available to directly duplicate the node, + # therefore the node is selected using CTRL+A on the graph to select + # it and then CTRL+D to duplicate sc_main.activateWindow() QtTest.QTest.keyClick(graph, "a", Qt.ControlModifier, WAIT_FRAMES) QtTest.QTest.keyClick(graph, "d", Qt.ControlModifier, WAIT_FRAMES) - # 6) Verify the node was duplicated + # 5) Verify the node was duplicated + # As direct interaction with node is not available the text on the label + # inside the Node Inspector is validated showing two nodes exist after_dup = grab_title_text() Report.result(Tests.node_duplicated, after_dup == EXPECTED_STRING) From 98a579abefc0ac64e6ee4ae021c7e8e824dafaa5 Mon Sep 17 00:00:00 2001 From: srikappa Date: Wed, 12 May 2021 12:17:36 -0700 Subject: [PATCH 079/100] Added a comment --- .../AzToolsFramework/Prefab/PrefabPublicHandler.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 3214905721..9649818ed9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -149,6 +149,7 @@ namespace AzToolsFramework undoBatch.GetUndoBatch(), containerEntityId, false); }); + // Create a link between the templates of the newly created instance and the instance it's being parented under. CreateLink( topLevelEntities, instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch(), commonRootEntityId); From 2787e5053d8514afd470df38881da916d231bb39 Mon Sep 17 00:00:00 2001 From: catdo Date: Wed, 12 May 2021 13:18:32 -0700 Subject: [PATCH 080/100] addressed some nits and added comments --- .../prefab/PrefabLevel_OpensLevelWithEntities.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py index ca59bbc2f8..3401c6a0a9 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py +++ b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py @@ -14,7 +14,7 @@ class Tests(): find_empty_entity = ("Entity: 'EmptyEntity' found", "Entity: 'EmptyEntity' *not* found in level") empty_entity_pos = ("'EmptyEntity' position is at the expected position", "'EmptyEntity' position is *not* at the expected position") find_pxentity = ("Entity: 'EntityWithPxCollider' found", "Entity: 'EntityWithPxCollider' *not* found in level") - pxentity_component = ("Entity: 'EntityWithPxCollider' has a Physx Collider", "Entity: 'EntityWithPxCollider' has *not* a Physx Collider") + pxentity_component = ("Entity: 'EntityWithPxCollider' has a Physx Collider", "Entity: 'EntityWithPxCollider' does *not* have a Physx Collider") # fmt:on @@ -50,17 +50,19 @@ def PrefabLevel_OpensLevelWithEntities(): if entityIds[0].IsValid(): return entityIds[0] return None - +#Checks for an entity called "EmptyEntity" helper.wait_for_condition(lambda: find_entity("EmptyEntity").IsValid(), 5.0) empty_entity_id = find_entity("EmptyEntity") Report.result(Tests.find_empty_entity, empty_entity_id.IsValid()) +# Checks if the EmptyEntity is in the correct position and if it fails, it will provide the expected postion and the actual postion of the entity in the Editor log empty_entity_pos = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTranslation", empty_entity_id) is_at_position = empty_entity_pos.IsClose(EXPECTED_EMPTY_ENTITY_POS) Report.result(Tests.empty_entity_pos, is_at_position) if not is_at_position: Report.info(f'Expected position: {EXPECTED_EMPTY_ENTITY_POS.ToString()}, actual position: {empty_entity_pos.ToString()}') +#Checks for an entity called "EntityWithPxCollider" and if it has the PhysX Collider component pxentity = find_entity("EntityWithPxCollider") Report.result(Tests.find_pxentity, pxentity.IsValid()) From 059f69e5e639a006b3cefaaa64b7055770d5c93a Mon Sep 17 00:00:00 2001 From: greerdv Date: Wed, 12 May 2021 21:20:23 +0100 Subject: [PATCH 081/100] tidy up NonUniformScaleService compatibility --- .../Components/NonUniformScaleComponent.cpp | 23 ------------------- .../EditorNonUniformScaleComponent.cpp | 23 ------------------- .../Code/Source/DebugDrawObbComponent.cpp | 2 +- .../Integration/Components/ActorComponent.h | 1 + .../Components/SimpleMotionComponent.h | 1 + .../Components/GradientTransformComponent.cpp | 1 + .../Source/Shape/CapsuleShapeComponent.cpp | 1 + .../Source/Shape/CompoundShapeComponent.h | 1 + .../Source/Shape/CylinderShapeComponent.cpp | 1 + .../Code/Source/Shape/DiskShapeComponent.cpp | 1 + .../Shape/EditorCapsuleShapeComponent.cpp | 6 +++++ .../Shape/EditorCapsuleShapeComponent.h | 2 ++ .../Shape/EditorCompoundShapeComponent.cpp | 6 +++++ .../Shape/EditorCompoundShapeComponent.h | 2 ++ .../Shape/EditorCylinderShapeComponent.cpp | 6 +++++ .../Shape/EditorCylinderShapeComponent.h | 2 ++ .../Source/Shape/EditorDiskShapeComponent.cpp | 6 +++++ .../Source/Shape/EditorDiskShapeComponent.h | 1 + .../Shape/EditorSphereShapeComponent.cpp | 6 +++++ .../Source/Shape/EditorSphereShapeComponent.h | 2 ++ .../Source/Shape/EditorSplineComponent.cpp | 1 + .../Source/Shape/EditorTubeShapeComponent.cpp | 6 +++++ .../Source/Shape/EditorTubeShapeComponent.h | 1 + .../Source/Shape/SphereShapeComponent.cpp | 1 + .../Code/Source/Shape/SplineComponent.h | 1 + .../Code/Source/Shape/TubeShapeComponent.cpp | 1 + .../Components/EditorSequenceComponent.h | 1 + .../Source/Components/SequenceComponent.cpp | 5 ++++ .../Source/Components/SequenceComponent.h | 2 ++ .../Code/Source/Components/ClothComponent.cpp | 5 ++++ .../Code/Source/Components/ClothComponent.h | 1 + .../Components/EditorClothComponent.cpp | 5 ++++ .../Source/Components/EditorClothComponent.h | 1 + .../Code/Source/EditorBallJointComponent.cpp | 5 ++++ .../Code/Source/EditorBallJointComponent.h | 1 + .../Code/Source/EditorFixedJointComponent.cpp | 5 ++++ .../Code/Source/EditorFixedJointComponent.h | 1 + .../Code/Source/EditorHingeJointComponent.cpp | 5 ++++ .../Code/Source/EditorHingeJointComponent.h | 1 + .../Components/CharacterControllerComponent.h | 1 + .../Components/CharacterGameplayComponent.cpp | 1 + .../EditorCharacterControllerComponent.h | 1 + .../EditorCharacterGameplayComponent.cpp | 1 + .../Components/RagdollComponent.h | 1 + .../EditorWhiteBoxColliderComponent.cpp | 5 ++++ .../EditorWhiteBoxColliderComponent.h | 1 + .../Components/WhiteBoxColliderComponent.cpp | 5 ++++ .../Components/WhiteBoxColliderComponent.h | 1 + .../Code/Source/EditorWhiteBoxComponent.cpp | 5 ++++ .../Code/Source/EditorWhiteBoxComponent.h | 1 + 50 files changed, 119 insertions(+), 47 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.cpp b/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.cpp index 57f14ddb38..d51f3645d3 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.cpp @@ -37,29 +37,6 @@ namespace AzFramework void NonUniformScaleComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); - - incompatible.push_back(AZ_CRC_CE("DebugDrawObbService")); - incompatible.push_back(AZ_CRC_CE("DebugDrawService")); - incompatible.push_back(AZ_CRC_CE("EMotionFXActorService")); - incompatible.push_back(AZ_CRC_CE("EMotionFXSimpleMotionService")); - incompatible.push_back(AZ_CRC_CE("GradientTransformService")); - incompatible.push_back(AZ_CRC_CE("LegacyMeshService")); - incompatible.push_back(AZ_CRC_CE("LookAtService")); - incompatible.push_back(AZ_CRC_CE("SequenceService")); - incompatible.push_back(AZ_CRC_CE("ClothMeshService")); - incompatible.push_back(AZ_CRC_CE("PhysXJointService")); - incompatible.push_back(AZ_CRC_CE("PhysXCharacterControllerService")); - incompatible.push_back(AZ_CRC_CE("PhysXRagdollService")); - incompatible.push_back(AZ_CRC_CE("WhiteBoxService")); - incompatible.push_back(AZ_CRC_CE("NavigationAreaService")); - incompatible.push_back(AZ_CRC_CE("GeometryService")); - incompatible.push_back(AZ_CRC_CE("CapsuleShapeService")); - incompatible.push_back(AZ_CRC_CE("CompoundShapeService")); - incompatible.push_back(AZ_CRC_CE("CylinderShapeService")); - incompatible.push_back(AZ_CRC_CE("DiskShapeService")); - incompatible.push_back(AZ_CRC_CE("SphereShapeService")); - incompatible.push_back(AZ_CRC_CE("SplineService")); - incompatible.push_back(AZ_CRC_CE("TubeShapeService")); } void NonUniformScaleComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp index 989398f196..a61f042049 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp @@ -63,29 +63,6 @@ namespace AzToolsFramework void EditorNonUniformScaleComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); - - incompatible.push_back(AZ_CRC_CE("DebugDrawObbService")); - incompatible.push_back(AZ_CRC_CE("DebugDrawService")); - incompatible.push_back(AZ_CRC_CE("EMotionFXActorService")); - incompatible.push_back(AZ_CRC_CE("EMotionFXSimpleMotionService")); - incompatible.push_back(AZ_CRC_CE("GradientTransformService")); - incompatible.push_back(AZ_CRC_CE("LegacyMeshService")); - incompatible.push_back(AZ_CRC_CE("LookAtService")); - incompatible.push_back(AZ_CRC_CE("SequenceService")); - incompatible.push_back(AZ_CRC_CE("ClothMeshService")); - incompatible.push_back(AZ_CRC_CE("PhysXJointService")); - incompatible.push_back(AZ_CRC_CE("PhysXCharacterControllerService")); - incompatible.push_back(AZ_CRC_CE("PhysXRagdollService")); - incompatible.push_back(AZ_CRC_CE("WhiteBoxService")); - incompatible.push_back(AZ_CRC_CE("NavigationAreaService")); - incompatible.push_back(AZ_CRC_CE("GeometryService")); - incompatible.push_back(AZ_CRC_CE("CapsuleShapeService")); - incompatible.push_back(AZ_CRC_CE("CompoundShapeService")); - incompatible.push_back(AZ_CRC_CE("CylinderShapeService")); - incompatible.push_back(AZ_CRC_CE("DiskShapeService")); - incompatible.push_back(AZ_CRC_CE("SphereShapeService")); - incompatible.push_back(AZ_CRC_CE("SplineService")); - incompatible.push_back(AZ_CRC_CE("TubeShapeService")); } void EditorNonUniformScaleComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) diff --git a/Gems/DebugDraw/Code/Source/DebugDrawObbComponent.cpp b/Gems/DebugDraw/Code/Source/DebugDrawObbComponent.cpp index df13bb56ce..72bbaba2b7 100644 --- a/Gems/DebugDraw/Code/Source/DebugDrawObbComponent.cpp +++ b/Gems/DebugDraw/Code/Source/DebugDrawObbComponent.cpp @@ -71,7 +71,7 @@ namespace DebugDraw void DebugDrawObbComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { - (void)incompatible; + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void DebugDrawObbComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h index 416705bff4..8188da19b4 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h @@ -136,6 +136,7 @@ namespace EMotionFX { incompatible.push_back(AZ_CRC("EMotionFXActorService", 0xd6e8f48d)); incompatible.push_back(AZ_CRC("MeshService", 0x71d8a455)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/SimpleMotionComponent.h b/Gems/EMotionFX/Code/Source/Integration/Components/SimpleMotionComponent.h index 5f5066b9bb..6820bfe33f 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/SimpleMotionComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/Components/SimpleMotionComponent.h @@ -87,6 +87,7 @@ namespace EMotionFX { incompatible.push_back(AZ_CRC("EMotionFXAnimGraphService", 0x9ec3c819)); incompatible.push_back(AZ_CRC("EMotionFXSimpleMotionService", 0xea7a05d8)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void Reflect(AZ::ReflectContext* /*context*/); diff --git a/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp b/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp index 0b967a6957..f99a8a8dfb 100644 --- a/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp @@ -200,6 +200,7 @@ namespace GradientSignal void GradientTransformComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& services) { services.push_back(AZ_CRC("GradientTransformService", 0x8c8c5ecc)); + services.push_back(AZ_CRC_CE("NonUniformScaleService")); } void GradientTransformComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& services) diff --git a/Gems/LmbrCentral/Code/Source/Shape/CapsuleShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/CapsuleShapeComponent.cpp index 46eb69dbd8..2341f93dbb 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/CapsuleShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/CapsuleShapeComponent.cpp @@ -32,6 +32,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("CapsuleShapeService", 0x9bc1122c)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void CapsuleShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/LmbrCentral/Code/Source/Shape/CompoundShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/CompoundShapeComponent.h index 25204cd4c0..1000609cf3 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/CompoundShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/CompoundShapeComponent.h @@ -76,6 +76,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("CompoundShapeService", 0x4f7c640a)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void Reflect(AZ::ReflectContext* context); diff --git a/Gems/LmbrCentral/Code/Source/Shape/CylinderShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/CylinderShapeComponent.cpp index 493cdef3e8..ff4ae9a9c5 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/CylinderShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/CylinderShapeComponent.cpp @@ -31,6 +31,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("CylinderShapeService", 0x507c688e)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void CylinderShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/LmbrCentral/Code/Source/Shape/DiskShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/DiskShapeComponent.cpp index 2d0673f299..f4a0f778c5 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/DiskShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/DiskShapeComponent.cpp @@ -28,6 +28,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("DiskShapeService", 0xd90c482b)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void DiskShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.cpp index 93fdfae29f..6c37d2f1ec 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.cpp @@ -78,6 +78,12 @@ namespace LmbrCentral EditorBaseShapeComponent::Deactivate(); } + void EditorCapsuleShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorCapsuleShapeComponent::DisplayEntityViewport( [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.h index 6bb34b1b9e..3accb8f29d 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.h @@ -40,6 +40,8 @@ namespace LmbrCentral provided.push_back(AZ_CRC("CapsuleShapeService", 0x9bc1122c)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + // EditorComponentBase void BuildGameEntity(AZ::Entity* gameEntity) override; diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.cpp index c61f54ab08..18957fae36 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.cpp @@ -59,6 +59,12 @@ namespace LmbrCentral } } + void EditorCompoundShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorCompoundShapeComponent::Init() { // setup the contained runtime component so that it can manage the child entities in the editor. diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.h index 24f06ee336..c725c2ef34 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.h @@ -41,6 +41,8 @@ namespace LmbrCentral provided.push_back(AZ_CRC("CompoundShapeService", 0x4f7c640a)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + AZ::u32 ConfigurationChanged(); private: diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.cpp index 89de8410f5..fe5a525fa8 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.cpp @@ -55,6 +55,12 @@ namespace LmbrCentral } } + void EditorCylinderShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorCylinderShapeComponent::Init() { EditorBaseShapeComponent::Init(); diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.h index a34ec6f548..3bbcf3286b 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.h @@ -40,6 +40,8 @@ namespace LmbrCentral provided.push_back(AZ_CRC("CylinderShapeService", 0x507c688e)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + // EditorComponentBase void BuildGameEntity(AZ::Entity* gameEntity) override; diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.cpp index 3d6181cde6..c1bfc04e7d 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.cpp @@ -55,6 +55,12 @@ namespace LmbrCentral provided.push_back(AZ_CRC("DiskShapeService", 0xd90c482b)); } + void EditorDiskShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorDiskShapeComponent::Init() { EditorBaseShapeComponent::Init(); diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.h index 1d20f2a338..d936a4a9ec 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.h @@ -39,6 +39,7 @@ namespace LmbrCentral protected: static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); private: AZ_DISABLE_COPY_MOVE(EditorDiskShapeComponent) diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.cpp index 0d9885191d..0323ec2dfe 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.cpp @@ -60,6 +60,12 @@ namespace LmbrCentral } } + void EditorSphereShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorSphereShapeComponent::Init() { EditorBaseShapeComponent::Init(); diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.h index f4a80d91ed..48f1d6cb2e 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.h @@ -44,6 +44,8 @@ namespace LmbrCentral provided.push_back(AZ_CRC("SphereShapeService", 0x90c8dc80)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + private: AZ_DISABLE_COPY_MOVE(EditorSphereShapeComponent) diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorSplineComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorSplineComponent.cpp index 144713c8ec..212ec49c93 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorSplineComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorSplineComponent.cpp @@ -44,6 +44,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("VariableVertexContainerService", 0x70c58740)); incompatible.push_back(AZ_CRC("FixedVertexContainerService", 0x83f1bbf2)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void EditorSplineComponent::Reflect(AZ::ReflectContext* context) diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.cpp index c8c03e2811..6ffb9e3308 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.cpp @@ -59,6 +59,12 @@ namespace LmbrCentral } } + void EditorTubeShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorTubeShapeComponent::Init() { EditorBaseShapeComponent::Init(); diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.h index b7b57310e5..6ffe7e9b73 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.h @@ -57,6 +57,7 @@ namespace LmbrCentral required.push_back(AZ_CRC("SplineService", 0x2b674d3c)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); private: AZ_DISABLE_COPY_MOVE(EditorTubeShapeComponent) diff --git a/Gems/LmbrCentral/Code/Source/Shape/SphereShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/SphereShapeComponent.cpp index 3bddc9b695..7faa455398 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/SphereShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/SphereShapeComponent.cpp @@ -29,6 +29,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("SphereShapeService", 0x90c8dc80)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void SphereShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/LmbrCentral/Code/Source/Shape/SplineComponent.h b/Gems/LmbrCentral/Code/Source/Shape/SplineComponent.h index eaa3fde457..f4cd73574b 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/SplineComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/SplineComponent.h @@ -103,6 +103,7 @@ namespace LmbrCentral incompatible.push_back(AZ_CRC("SplineService", 0x2b674d3c)); incompatible.push_back(AZ_CRC("VariableVertexContainerService", 0x70c58740)); incompatible.push_back(AZ_CRC("FixedVertexContainerService", 0x83f1bbf2)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/LmbrCentral/Code/Source/Shape/TubeShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/TubeShapeComponent.cpp index f757da2107..014612daa1 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/TubeShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/TubeShapeComponent.cpp @@ -28,6 +28,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("TubeShapeService", 0x3fe791b4)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void TubeShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.h b/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.h index 294f7b4370..f5689f3f65 100644 --- a/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.h +++ b/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.h @@ -98,6 +98,7 @@ namespace Maestro { // This guarantees that only one SequenceComponent will ever be on an entity incompatible.push_back(AZ_CRC("SequenceService", 0x7cbe5938)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } // Required Reflect function. diff --git a/Gems/Maestro/Code/Source/Components/SequenceComponent.cpp b/Gems/Maestro/Code/Source/Components/SequenceComponent.cpp index c1470ccf15..f1951c12a3 100644 --- a/Gems/Maestro/Code/Source/Components/SequenceComponent.cpp +++ b/Gems/Maestro/Code/Source/Components/SequenceComponent.cpp @@ -139,6 +139,11 @@ namespace Maestro } } + void SequenceComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void SequenceComponent::ReflectCinematicsLib(AZ::ReflectContext* context) { // The Movie System itself diff --git a/Gems/Maestro/Code/Source/Components/SequenceComponent.h b/Gems/Maestro/Code/Source/Components/SequenceComponent.h index 20e7d22fe3..48cd7f25c9 100644 --- a/Gems/Maestro/Code/Source/Components/SequenceComponent.h +++ b/Gems/Maestro/Code/Source/Components/SequenceComponent.h @@ -97,6 +97,8 @@ namespace Maestro provided.push_back(AZ_CRC("SequenceService", 0x7cbe5938)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + // Required Reflect function. static void Reflect(AZ::ReflectContext* context); private: diff --git a/Gems/NvCloth/Code/Source/Components/ClothComponent.cpp b/Gems/NvCloth/Code/Source/Components/ClothComponent.cpp index ddd2d6fa36..912255c798 100644 --- a/Gems/NvCloth/Code/Source/Components/ClothComponent.cpp +++ b/Gems/NvCloth/Code/Source/Components/ClothComponent.cpp @@ -47,6 +47,11 @@ namespace NvCloth required.push_back(AZ_CRC("TransformService", 0x8ee22c50)); } + void ClothComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void ClothComponent::Activate() { // Cloth components do not run on dedicated servers. diff --git a/Gems/NvCloth/Code/Source/Components/ClothComponent.h b/Gems/NvCloth/Code/Source/Components/ClothComponent.h index 9b8458d276..bb7a645b61 100644 --- a/Gems/NvCloth/Code/Source/Components/ClothComponent.h +++ b/Gems/NvCloth/Code/Source/Components/ClothComponent.h @@ -38,6 +38,7 @@ namespace NvCloth static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); const ClothComponentMesh* GetClothComponentMesh() const { return m_clothComponentMesh.get(); } diff --git a/Gems/NvCloth/Code/Source/Components/EditorClothComponent.cpp b/Gems/NvCloth/Code/Source/Components/EditorClothComponent.cpp index 4705a9f2c2..1254a13cb2 100644 --- a/Gems/NvCloth/Code/Source/Components/EditorClothComponent.cpp +++ b/Gems/NvCloth/Code/Source/Components/EditorClothComponent.cpp @@ -415,6 +415,11 @@ namespace NvCloth required.push_back(AZ_CRC("MeshService", 0x71d8a455)); } + void EditorClothComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + const MeshNodeList& EditorClothComponent::GetMeshNodeList() const { return m_meshNodeList; diff --git a/Gems/NvCloth/Code/Source/Components/EditorClothComponent.h b/Gems/NvCloth/Code/Source/Components/EditorClothComponent.h index 9727895a43..2ef3123942 100644 --- a/Gems/NvCloth/Code/Source/Components/EditorClothComponent.h +++ b/Gems/NvCloth/Code/Source/Components/EditorClothComponent.h @@ -39,6 +39,7 @@ namespace NvCloth static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); const MeshNodeList& GetMeshNodeList() const; const AZStd::unordered_set& GetMeshNodesWithBackstopData() const; diff --git a/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp b/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp index f3bdb83325..deb1d0d231 100644 --- a/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp @@ -63,6 +63,11 @@ namespace PhysX required.push_back(AZ_CRC("PhysXRigidBodyService", 0x1d4c64a8)); } + void EditorBallJointComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorBallJointComponent::Activate() { EditorJointComponent::Activate(); diff --git a/Gems/PhysX/Code/Source/EditorBallJointComponent.h b/Gems/PhysX/Code/Source/EditorBallJointComponent.h index fbff44b38e..44f96b3fa8 100644 --- a/Gems/PhysX/Code/Source/EditorBallJointComponent.h +++ b/Gems/PhysX/Code/Source/EditorBallJointComponent.h @@ -33,6 +33,7 @@ namespace PhysX static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // AZ::Component void Activate() override; diff --git a/Gems/PhysX/Code/Source/EditorFixedJointComponent.cpp b/Gems/PhysX/Code/Source/EditorFixedJointComponent.cpp index a2b496672c..1645d8c932 100644 --- a/Gems/PhysX/Code/Source/EditorFixedJointComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorFixedJointComponent.cpp @@ -60,6 +60,11 @@ namespace PhysX required.push_back(AZ_CRC("PhysXRigidBodyService", 0x1d4c64a8)); } + void EditorFixedJointComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorFixedJointComponent::Activate() { EditorJointComponent::Activate(); diff --git a/Gems/PhysX/Code/Source/EditorFixedJointComponent.h b/Gems/PhysX/Code/Source/EditorFixedJointComponent.h index c66ba661be..8642f83472 100644 --- a/Gems/PhysX/Code/Source/EditorFixedJointComponent.h +++ b/Gems/PhysX/Code/Source/EditorFixedJointComponent.h @@ -33,6 +33,7 @@ namespace PhysX static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // AZ::Component void Activate() override; diff --git a/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp b/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp index fde1ff980b..6d136e898b 100644 --- a/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp @@ -63,6 +63,11 @@ namespace PhysX required.push_back(AZ_CRC("PhysXRigidBodyService", 0x1d4c64a8)); } + void EditorHingeJointComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorHingeJointComponent::Activate() { EditorJointComponent::Activate(); diff --git a/Gems/PhysX/Code/Source/EditorHingeJointComponent.h b/Gems/PhysX/Code/Source/EditorHingeJointComponent.h index 3b3182068b..ef555d145e 100644 --- a/Gems/PhysX/Code/Source/EditorHingeJointComponent.h +++ b/Gems/PhysX/Code/Source/EditorHingeJointComponent.h @@ -33,6 +33,7 @@ namespace PhysX static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // AZ::Component void Activate() override; diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterControllerComponent.h b/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterControllerComponent.h index 31f5051ac4..a7a1a92ad2 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterControllerComponent.h +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterControllerComponent.h @@ -59,6 +59,7 @@ namespace PhysX static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("PhysXCharacterControllerService", 0x428de4fa)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterGameplayComponent.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterGameplayComponent.cpp index 70373f8db2..d557919627 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterGameplayComponent.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterGameplayComponent.cpp @@ -51,6 +51,7 @@ namespace PhysX void CharacterGameplayComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("PhysXCharacterGameplayService", 0xfacd7876)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void CharacterGameplayComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterControllerComponent.h b/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterControllerComponent.h index d42c1c9537..cc2a93d0b8 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterControllerComponent.h +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterControllerComponent.h @@ -64,6 +64,7 @@ namespace PhysX incompatible.push_back(AZ_CRC("PhysXCharacterControllerService", 0x428de4fa)); incompatible.push_back(AZ_CRC("LegacyCryPhysicsService", 0xbb370351)); incompatible.push_back(AZ_CRC("PhysXRigidBodyService", 0x1d4c64a8)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterGameplayComponent.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterGameplayComponent.cpp index 03ff0e0aea..dc67870fb2 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterGameplayComponent.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterGameplayComponent.cpp @@ -23,6 +23,7 @@ namespace PhysX void EditorCharacterGameplayComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("PhysXCharacterGameplayService", 0xfacd7876)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void EditorCharacterGameplayComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h b/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h index e7397af877..a02e9c47fb 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h @@ -49,6 +49,7 @@ namespace PhysX { incompatible.push_back(AZ_CRC("PhysXRagdollService", 0x6d889c70)); incompatible.push_back(AZ_CRC("LegacyCryPhysicsService", 0xbb370351)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp index 6e2e4be0a2..97bce7631d 100644 --- a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp +++ b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp @@ -75,6 +75,11 @@ namespace WhiteBox required.push_back(AZ_CRC("WhiteBoxService", 0x2f2f42b8)); } + void EditorWhiteBoxColliderComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorWhiteBoxColliderComponent::Activate() { AzToolsFramework::Components::EditorComponentBase::Activate(); diff --git a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.h b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.h index 5b46d0b99e..635abbb1bd 100644 --- a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.h +++ b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.h @@ -46,6 +46,7 @@ namespace WhiteBox private: static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // AZ::Component ... void Activate() override; diff --git a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp index 3179a2cd72..117b175cda 100644 --- a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp +++ b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp @@ -44,6 +44,11 @@ namespace WhiteBox required.push_back(AZ_CRC("TransformService", 0x8ee22c50)); } + void WhiteBoxColliderComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + WhiteBoxColliderComponent::WhiteBoxColliderComponent( const Physics::CookedMeshShapeConfiguration& shapeConfiguration, const Physics::ColliderConfiguration& physicsColliderConfiguration, diff --git a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.h b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.h index 1ad773652d..0b50c834d8 100644 --- a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.h +++ b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.h @@ -41,6 +41,7 @@ namespace WhiteBox private: static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // AZ::Component ... void Activate() override; diff --git a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp index d4ab543404..e8e03556e2 100644 --- a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp +++ b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp @@ -265,6 +265,11 @@ namespace WhiteBox provided.push_back(AZ_CRC("WhiteBoxService", 0x2f2f42b8)); } + void EditorWhiteBoxComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + EditorWhiteBoxComponent::EditorWhiteBoxComponent() = default; EditorWhiteBoxComponent::~EditorWhiteBoxComponent() diff --git a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.h b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.h index 02b50a9407..c4dd6c2b0b 100644 --- a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.h +++ b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.h @@ -89,6 +89,7 @@ namespace WhiteBox private: static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // EditorComponentBase overrides ... void BuildGameEntity(AZ::Entity* gameEntity) override; From d0b006c209573e0be961b6bc27fd3bde1cbaf3ad Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 13:41:18 -0700 Subject: [PATCH 082/100] Some cleanup to better support backward reconciliation as well as dynamic player spawning on connect --- Code/CryEngine/CrySystem/SystemInit.cpp | 2 +- Gems/Multiplayer/Code/Include/IMultiplayer.h | 79 +++++++++++++++++-- .../Code/Include/INetworkEntityManager.h | 42 +++++----- Gems/Multiplayer/Code/Include/INetworkTime.h | 34 ++------ .../AutoGen/AutoComponentTypes_Source.jinja | 2 +- .../Source/AutoGen/AutoComponent_Source.jinja | 23 ++++-- .../LocalPredictionPlayerInputComponent.cpp | 6 +- .../Source/MultiplayerSystemComponent.cpp | 71 ++++++++++++----- .../Code/Source/MultiplayerSystemComponent.h | 5 ++ .../EntityReplicationManager.cpp | 2 +- .../EntityReplication/EntityReplicator.cpp | 4 +- .../NetworkEntity/NetworkEntityManager.cpp | 29 +++++-- .../NetworkEntity/NetworkEntityManager.h | 19 +++-- .../Source/NetworkInput/NetworkInputChild.cpp | 2 +- .../NetworkInputMigrationVector.cpp | 2 +- .../Code/Source/NetworkTime/NetworkTime.cpp | 52 ++++++++---- .../Code/Source/NetworkTime/NetworkTime.h | 7 +- .../Source/NetworkTime/RewindableObject.inl | 4 +- .../ServerToClientReplicationWindow.cpp | 2 +- .../ServerToClientReplicationWindow.h | 2 +- 20 files changed, 261 insertions(+), 128 deletions(-) diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index 8bf2fb8930..6181fde615 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -1247,7 +1247,7 @@ bool CSystem::InitShine([[maybe_unused]] const SSystemInitParams& initParams) if (!m_env.pLyShine) { - AZ_Error(AZ_TRACE_SYSTEM_WINDOW, false, "LYShine System did not initialize correctly. Please check that the LyShine gem is enabled for this project in ProjectConfigurator."); + AZ_Error(AZ_TRACE_SYSTEM_WINDOW, false, "LYShine System did not initialize correctly. Please check that the LyShine gem is enabled for this project in *_dependencies.cmake."); return false; } return true; diff --git a/Gems/Multiplayer/Code/Include/IMultiplayer.h b/Gems/Multiplayer/Code/Include/IMultiplayer.h index 039b86b2a6..80bdaa68eb 100644 --- a/Gems/Multiplayer/Code/Include/IMultiplayer.h +++ b/Gems/Multiplayer/Code/Include/IMultiplayer.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -46,6 +47,7 @@ namespace Multiplayer using ConnectionAcquiredEvent = AZ::Event; using SessionInitEvent = AZ::Event; using SessionShutdownEvent = AZ::Event; + using OnConnectFunctor = AZStd::function; //! IMultiplayer provides insight into the Multiplayer session and its Agents class IMultiplayer @@ -55,26 +57,30 @@ namespace Multiplayer virtual ~IMultiplayer() = default; - //! Gets the type of Agent this IMultiplayer impl represents + //! Gets the type of Agent this IMultiplayer impl represents. //! @return The type of agents represented virtual MultiplayerAgentType GetAgentType() const = 0; - //! Sets the type of this Multiplayer connection and calls any related callback + //! Sets the type of this Multiplayer connection and calls any related callback. //! @param state The state of this connection virtual void InitializeMultiplayer(MultiplayerAgentType state) = 0; - //! Adds a ConnectionAcquiredEvent Handler which is invoked when a new endpoint connects to the session + //! Adds a ConnectionAcquiredEvent Handler which is invoked when a new endpoint connects to the session. //! @param handler The SessionInitEvent Handler to add virtual void AddConnectionAcquiredHandler(ConnectionAcquiredEvent::Handler& handler) = 0; - //! Adds a SessionInitEvent Handler which is invoked when a new network session starts + //! Adds a SessionInitEvent Handler which is invoked when a new network session starts. //! @param handler The SessionInitEvent Handler to add virtual void AddSessionInitHandler(SessionInitEvent::Handler& handler) = 0; - //! Adds a SessionShutdownEvent Handler which is invoked when the current network session ends + //! Adds a SessionShutdownEvent Handler which is invoked when the current network session ends. //! @param handler The SessionShutdownEvent handler to add virtual void AddSessionShutdownHandler(SessionShutdownEvent::Handler& handler) = 0; + //! Overrides the default connect behaviour with the provided functor. + //! @param functor the function to invoke during a new connection event + virtual void SetOnConnectFunctor(const OnConnectFunctor& functor) = 0; + //! Sends a packet telling if entity update messages can be sent //! @param readyForEntityUpdates Ready for entity updates or not virtual void SendReadyForEntityUpdates(bool readyForEntityUpdates) = 0; @@ -87,6 +93,14 @@ namespace Multiplayer //! @return the current server time in milliseconds virtual AZ::TimeMs GetCurrentHostTimeMs() const = 0; + //! Returns the network time instance bound to this multiplayer instance. + //! @return pointer to the network time instance bound to this multiplayer instance + virtual INetworkTime* GetNetworkTime() = 0; + + //! Returns the network entity manager instance bound to this multiplayer instance. + //! @return pointer to the network entity manager instance bound to this multiplayer instance + virtual INetworkEntityManager* GetNetworkEntityManager() = 0; + //! Returns the gem name associated with the provided component index. //! @param netComponentId the componentId to return the gem name of //! @return the name of the gem that contains the requested component @@ -117,6 +131,61 @@ namespace Multiplayer MultiplayerStats m_stats; }; + // Convenience helpers + inline IMultiplayer* GetMultiplayer() + { + return AZ::Interface::Get(); + } + + inline INetworkTime* GetNetworkTime() + { + return GetMultiplayer()->GetNetworkTime(); + } + + inline INetworkEntityManager* GetNetworkEntityManager() + { + return GetMultiplayer()->GetNetworkEntityManager(); + } + + inline NetworkEntityTracker* GetNetworkEntityTracker() + { + return GetNetworkEntityManager()->GetNetworkEntityTracker(); + } + + inline NetworkEntityAuthorityTracker* GetNetworkEntityAuthorityTracker() + { + return GetNetworkEntityManager()->GetNetworkEntityAuthorityTracker(); + } + + inline MultiplayerComponentRegistry* GetMultiplayerComponentRegistry() + { + return GetNetworkEntityManager()->GetMultiplayerComponentRegistry(); + } + + //! @class ScopedAlterTime + //! @brief This is a wrapper that temporarily adjusts global program time for backward reconciliation purposes. + class ScopedAlterTime final + { + public: + inline ScopedAlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId connectionId) + { + INetworkTime* time = GetNetworkTime(); + m_previousHostFrameId = time->GetHostFrameId(); + m_previousHostTimeMs = time->GetHostTimeMs(); + m_previousRewindConnectionId = time->GetRewindingConnectionId(); + time->AlterTime(frameId, timeMs, connectionId); + } + inline ~ScopedAlterTime() + { + INetworkTime* time = GetNetworkTime(); + time->AlterTime(m_previousHostFrameId, m_previousHostTimeMs, m_previousRewindConnectionId); + } + private: + HostFrameId m_previousHostFrameId = InvalidHostFrameId; + AZ::TimeMs m_previousHostTimeMs = AZ::TimeMs{ 0 }; + AzNetworking::ConnectionId m_previousRewindConnectionId = AzNetworking::InvalidConnectionId; + }; + inline const char* GetEnumString(MultiplayerAgentType value) { switch (value) diff --git a/Gems/Multiplayer/Code/Include/INetworkEntityManager.h b/Gems/Multiplayer/Code/Include/INetworkEntityManager.h index d9b611ece0..ebb95e2281 100644 --- a/Gems/Multiplayer/Code/Include/INetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Include/INetworkEntityManager.h @@ -59,9 +59,24 @@ namespace Multiplayer //! Creates new entities of the given archetype //! @param prefabEntryId the name of the spawnable to spawn - virtual EntityList CreateEntitiesImmediate( - const PrefabEntityId& prefabEntryId, NetEntityId netEntityId, NetEntityRole netEntityRole, AutoActivate autoActivate, - const AZ::Transform& transform) = 0; + virtual EntityList CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityRole netEntityRole, + const AZ::Transform& transform + ) = 0; + + //! Creates new entities of the given archetype + //! This interface is internally used to spawn replicated entities + //! @param prefabEntryId the name of the spawnable to spawn + virtual EntityList CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityId netEntityId, + NetEntityRole netEntityRole, + AutoActivate autoActivate, + const AZ::Transform& transform + ) = 0; //! Returns an ConstEntityPtr for the provided entityId. //! @param netEntityId the netEntityId to get an ConstEntityPtr for @@ -134,25 +149,4 @@ namespace Multiplayer //! @param entityRpcMessage the local rpc message to handle virtual void HandleLocalRpcMessage(NetworkEntityRpcMessage& message) = 0; }; - - // Convenience helpers - inline INetworkEntityManager* GetNetworkEntityManager() - { - return AZ::Interface::Get(); - } - - inline NetworkEntityTracker* GetNetworkEntityTracker() - { - return GetNetworkEntityManager()->GetNetworkEntityTracker(); - } - - inline NetworkEntityAuthorityTracker* GetNetworkEntityAuthorityTracker() - { - return GetNetworkEntityManager()->GetNetworkEntityAuthorityTracker(); - } - - inline MultiplayerComponentRegistry* GetMultiplayerComponentRegistry() - { - return GetNetworkEntityManager()->GetMultiplayerComponentRegistry(); - } } diff --git a/Gems/Multiplayer/Code/Include/INetworkTime.h b/Gems/Multiplayer/Code/Include/INetworkTime.h index 5346a0e0d0..1ccf08bbdc 100644 --- a/Gems/Multiplayer/Code/Include/INetworkTime.h +++ b/Gems/Multiplayer/Code/Include/INetworkTime.h @@ -47,9 +47,6 @@ namespace Multiplayer //! @return the hosts current timeMs virtual AZ::TimeMs GetHostTimeMs() const = 0; - //! Synchronizes rewindable entity state for the current application time. - virtual void SyncRewindableEntityState() = 0; - //! Get the controlling connection that may be currently altering global game time. //! Note this abstraction is required at a relatively high level to allow for 'don't rewind the shooter' semantics //! @return the ConnectionId of the connection requesting the rewind operation @@ -67,6 +64,13 @@ namespace Multiplayer //! @param rewindConnectionId the rewinding ConnectionId virtual void AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId rewindConnectionId) = 0; + //! Syncs all entities contained within a volume to the current rewind state. + //! @param rewindVolume the volume to rewind entities within (needed for physics entities) + virtual void SyncEntitiesToRewindState(const AZ::Aabb& rewindVolume) = 0; + + //! Restores all rewound entities to the current application time. + virtual void ClearRewoundEntities() = 0; + AZ_DISABLE_COPY_MOVE(INetworkTime); }; @@ -79,28 +83,4 @@ namespace Multiplayer static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; }; using INetworkTimeRequestBus = AZ::EBus; - - //! @class ScopedAlterTime - //! @brief This is a wrapper that temporarily adjusts global program time for backward reconciliation purposes. - class ScopedAlterTime final - { - public: - inline ScopedAlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId connectionId) - { - INetworkTime* time = AZ::Interface::Get(); - m_previousHostFrameId = time->GetHostFrameId(); - m_previousHostTimeMs = time->GetHostTimeMs(); - m_previousRewindConnectionId = time->GetRewindingConnectionId(); - time->AlterTime(frameId, timeMs, connectionId); - } - inline ~ScopedAlterTime() - { - INetworkTime* time = AZ::Interface::Get(); - time->AlterTime(m_previousHostFrameId, m_previousHostTimeMs, m_previousRewindConnectionId); - } - private: - HostFrameId m_previousHostFrameId = InvalidHostFrameId; - AZ::TimeMs m_previousHostTimeMs = AZ::TimeMs{ 0 }; - AzNetworking::ConnectionId m_previousRewindConnectionId = AzNetworking::InvalidConnectionId; - }; } diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja index 2bae618d94..2acc252729 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja @@ -22,7 +22,7 @@ namespace {{ Namespace }} void RegisterMultiplayerComponents() { Multiplayer::MultiplayerComponentRegistry* multiplayerComponentRegistry = GetMultiplayerComponentRegistry(); - Multiplayer::MultiplayerStats& stats = AZ::Interface::Get()->GetStats(); + Multiplayer::MultiplayerStats& stats = GetMultiplayer()->GetStats(); {% for Component in dataFiles %} {% set ComponentName = Component.attrib['Name'] %} {% set ComponentBaseName = ComponentName %} diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 6e54ec3d58..d719cbe47b 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -476,7 +476,7 @@ bool {{ ClassName }}::Serialize{{ AutoComponentMacros.GetNetPropertiesSetName(Re {%- if networkPropertyCount.update({'value': networkPropertyCount.value + 1}) %}{% endif -%} {% endcall %} {% if networkPropertyCount.value > 0 %} - MultiplayerStats& stats = AZ::Interface::Get()->GetStats(); + MultiplayerStats& stats = GetMultiplayer()->GetStats(); // We modify the record if we are writing an update so that we don't notify for a change that really didn't change the value (just a duplicated send from the server) [[maybe_unused]] bool modifyRecord = serializer.GetSerializerMode() == AzNetworking::SerializerMode::WriteToObject; {% call(Property) AutoComponentMacros.ParseNetworkProperties(Component, ReplicateFrom, ReplicateTo) %} @@ -1141,16 +1141,23 @@ namespace {{ Component.attrib['Namespace'] }} AZ::EditContext* editContext = serializeContext->GetEditContext(); if (editContext) { - editContext->Class<{{ ComponentName }}>("{{ ComponentName }}", "{{ Component.attrib['Description'] }}") + editContext->Class<{{ ComponentBaseName }}>("{{ ComponentBaseName }}", "{{ Component.attrib['Description'] }}") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "Multiplayer") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")) - {{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Authority', ComponentName)|indent(20) -}} -{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Server', ComponentName)|indent(20) -}} -{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Client', ComponentName)|indent(20) -}} -{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Autonomous', ComponentName)|indent(20) -}} -{{ DefineNetworkPropertyEditReflection(Component, 'Autonomous', 'Authority', ComponentName)|indent(20) }} - {{ DefineArchetypePropertyEditReflection(Component, ComponentName)|indent(20) }}; + {{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Authority', ComponentBaseName)|indent(20) -}} +{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Server', ComponentBaseName)|indent(20) -}} +{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Client', ComponentBaseName)|indent(20) -}} +{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Autonomous', ComponentBaseName)|indent(20) -}} +{{ DefineNetworkPropertyEditReflection(Component, 'Autonomous', 'Authority', ComponentBaseName)|indent(20) }} + {{ DefineArchetypePropertyEditReflection(Component, ComponentBaseName)|indent(20) }}; +{% if ComponentDerived %} + + editContext->Class<{{ ComponentName }}>("{{ ComponentName }}", "{{ Component.attrib['Description'] }}") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::Category, "Multiplayer") + ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")); +{% endif %} } } } diff --git a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp index 90b590d99d..b57c465df2 100644 --- a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp @@ -94,7 +94,7 @@ namespace Multiplayer if (entityIsMigrating == EntityIsMigrating::True) { m_allowMigrateClientInput = true; - m_serverMigrateFrameId = AZ::Interface::Get()->GetHostFrameId(); + m_serverMigrateFrameId = GetNetworkTime()->GetHostFrameId(); } } @@ -492,8 +492,8 @@ namespace Multiplayer const uint32_t maxClientInputs = inputRate > 0.0 ? static_cast(maxRewindHistory / inputRate) : 0; - INetworkTime* networkTime = AZ::Interface::Get(); - IMultiplayer* multiplayer = AZ::Interface::Get(); + IMultiplayer* multiplayer = GetMultiplayer(); + INetworkTime* networkTime = GetNetworkTime(); while (m_moveAccumulator >= inputRate) { m_moveAccumulator -= inputRate; diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index e6fb77eca7..590faa6bad 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -23,6 +23,9 @@ #include #include #include +#include +#include +#include namespace AZ::ConsoleTypeHelpers { @@ -69,6 +72,7 @@ namespace Multiplayer AZ_CVAR(ProtocolType, sv_protocol, ProtocolType::Udp, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "This flag controls whether we use TCP or UDP for game networking"); AZ_CVAR(bool, sv_isDedicated, true, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Whether the host command creates an independent or client hosted server"); AZ_CVAR(AZ::TimeMs, cl_defaultNetworkEntityActivationTimeSliceMs, AZ::TimeMs{ 0 }, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Max Ms to use to activate entities coming from the network, 0 means instantiate everything"); + AZ_CVAR(AZ::CVarFixedString, sv_defaultPlayerSpawnAsset, "prefabs/player.network.spawnable", nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "The default spawnable to use when a new player connects"); void MultiplayerSystemComponent::Reflect(AZ::ReflectContext* context) { @@ -411,6 +415,11 @@ namespace Multiplayer void MultiplayerSystemComponent::OnConnect(AzNetworking::IConnection* connection) { + MultiplayerAgentDatum datum; + datum.m_id = connection->GetConnectionId(); + datum.m_isInvited = false; + datum.m_agentType = MultiplayerAgentType::Client; + if (connection->GetConnectionRole() == ConnectionRole::Connector) { AZLOG_INFO("New outgoing connection to remote address: %s", connection->GetRemoteAddress().GetString().c_str()); @@ -419,36 +428,45 @@ namespace Multiplayer else { AZLOG_INFO("New incoming connection from remote address: %s", connection->GetRemoteAddress().GetString().c_str()); - MultiplayerAgentDatum datum; - datum.m_id = connection->GetConnectionId(); - datum.m_isInvited = false; - datum.m_agentType = MultiplayerAgentType::Client; m_connAcquiredEvent.Signal(datum); } - if (GetAgentType() == MultiplayerAgentType::ClientServer - || GetAgentType() == MultiplayerAgentType::DedicatedServer) + if (m_onConnectFunctor) { - // TODO: This needs to be set to the players autonomous proxy ------------v - NetworkEntityHandle controlledEntity = GetNetworkEntityTracker()->Get(NetEntityId{ 0 }); - - if (connection->GetUserData() == nullptr) // Only add user data if the connect event handler has not already done so - { - connection->SetUserData(new ServerToClientConnectionData(connection, *this, controlledEntity)); - } - AZStd::unique_ptr window = AZStd::make_unique(controlledEntity, connection); - reinterpret_cast(connection->GetUserData())->GetReplicationManager().SetReplicationWindow(AZStd::move(window)); } else { - if (connection->GetUserData() == nullptr) // Only add user data if the connect event handler has not already done so + if (GetAgentType() == MultiplayerAgentType::ClientServer + || GetAgentType() == MultiplayerAgentType::DedicatedServer) { - connection->SetUserData(new ClientToServerConnectionData(connection, *this)); + PrefabEntityId playerPrefabEntityId(AZ::Name(static_cast(sv_defaultPlayerSpawnAsset).c_str()), 1); + INetworkEntityManager::EntityList entityList = m_networkEntityManager.CreateEntitiesImmediate(playerPrefabEntityId, NetEntityRole::Authority, AZ::Transform::CreateIdentity()); + + NetworkEntityHandle controlledEntity; + if (entityList.size() > 0) + { + controlledEntity = entityList[0]; + } + + if (connection->GetUserData() == nullptr) // Only add user data if the connect event handler has not already done so + { + connection->SetUserData(new ServerToClientConnectionData(connection, *this, controlledEntity)); + } + + AZStd::unique_ptr window = AZStd::make_unique(controlledEntity, connection); + reinterpret_cast(connection->GetUserData())->GetReplicationManager().SetReplicationWindow(AZStd::move(window)); } + else + { + if (connection->GetUserData() == nullptr) // Only add user data if the connect event handler has not already done so + { + connection->SetUserData(new ClientToServerConnectionData(connection, *this)); + } - AZStd::unique_ptr window = AZStd::make_unique(); - reinterpret_cast(connection->GetUserData())->GetReplicationManager().SetEntityActivationTimeSliceMs(cl_defaultNetworkEntityActivationTimeSliceMs); + AZStd::unique_ptr window = AZStd::make_unique(); + reinterpret_cast(connection->GetUserData())->GetReplicationManager().SetEntityActivationTimeSliceMs(cl_defaultNetworkEntityActivationTimeSliceMs); + } } } @@ -521,6 +539,11 @@ namespace Multiplayer handler.Connect(m_shutdownEvent); } + void MultiplayerSystemComponent::SetOnConnectFunctor(const OnConnectFunctor& functor) + { + m_onConnectFunctor = functor; + } + void MultiplayerSystemComponent::SendReadyForEntityUpdates(bool readyForEntityUpdates) { IConnectionSet& connectionSet = m_networkInterface->GetConnectionSet(); @@ -542,6 +565,16 @@ namespace Multiplayer } } + INetworkTime* MultiplayerSystemComponent::GetNetworkTime() + { + return &m_networkTime; + } + + INetworkEntityManager* MultiplayerSystemComponent::GetNetworkEntityManager() + { + return &m_networkEntityManager; + } + const char* MultiplayerSystemComponent::GetComponentGemName(NetComponentId netComponentId) const { return GetMultiplayerComponentRegistry()->GetComponentGemName(netComponentId); diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h index 477745e6b5..1de8fccb50 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h @@ -89,8 +89,11 @@ namespace Multiplayer void AddConnectionAcquiredHandler(ConnectionAcquiredEvent::Handler& handler) override; void AddSessionInitHandler(SessionInitEvent::Handler& handler) override; void AddSessionShutdownHandler(SessionShutdownEvent::Handler& handler) override; + void SetOnConnectFunctor(const OnConnectFunctor& functor) override; void SendReadyForEntityUpdates(bool readyForEntityUpdates) override; AZ::TimeMs GetCurrentHostTimeMs() const override; + INetworkTime* GetNetworkTime() override; + INetworkEntityManager* GetNetworkEntityManager() override; const char* GetComponentGemName(NetComponentId netComponentId) const override; const char* GetComponentName(NetComponentId netComponentId) const override; const char* GetComponentPropertyName(NetComponentId netComponentId, PropertyIndex propertyIndex) const override; @@ -121,6 +124,8 @@ namespace Multiplayer SessionShutdownEvent m_shutdownEvent; ConnectionAcquiredEvent m_connAcquiredEvent; + OnConnectFunctor m_onConnectFunctor = nullptr; + AZ::TimeMs m_lastReplicatedHostTimeMs = AZ::TimeMs{ 0 }; HostFrameId m_lastReplicatedHostFrameId = InvalidHostFrameId; }; diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp index 1e7649f561..65df4f1464 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp @@ -824,7 +824,7 @@ namespace Multiplayer { if (entityReplicator == nullptr) { - IMultiplayer* multiplayer = AZ::Interface::Get(); + IMultiplayer* multiplayer = GetMultiplayer(); AZLOG_INFO ( "EntityReplicationManager: Dropping remote RPC message for component %s of rpc index %s, entityId %u has already been deleted", diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp index 7431b95a22..197d83a48c 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp @@ -448,7 +448,7 @@ namespace Multiplayer void EntityReplicator::DeferRpcMessage(NetworkEntityRpcMessage& entityRpcMessage) { // Received rpc metrics, log rpc sent, number of bytes, and the componentId/rpcId for bandwidth metrics - MultiplayerStats& stats = AZ::Interface::Get()->GetStats(); + MultiplayerStats& stats = GetMultiplayer()->GetStats(); stats.RecordRpcSent(entityRpcMessage.GetComponentId(), entityRpcMessage.GetRpcIndex(), entityRpcMessage.GetEstimatedSerializeSize()); m_replicationManager.AddDeferredRpcMessage(entityRpcMessage); @@ -631,7 +631,7 @@ namespace Multiplayer bool EntityReplicator::HandleRpcMessage(AzNetworking::IConnection* invokingConnection, NetworkEntityRpcMessage& entityRpcMessage) { // Received rpc metrics, log rpc received, time spent, number of bytes, and the componentId/rpcId for bandwidth metrics - MultiplayerStats& stats = AZ::Interface::Get()->GetStats(); + MultiplayerStats& stats = GetMultiplayer()->GetStats(); stats.RecordRpcReceived(entityRpcMessage.GetComponentId(), entityRpcMessage.GetRpcIndex(), entityRpcMessage.GetEstimatedSerializeSize()); if (!m_netBindComponent) diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index 1c7fb5f7af..7ee4d45e93 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -38,7 +38,6 @@ namespace Multiplayer , 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); @@ -48,7 +47,6 @@ namespace Multiplayer NetworkEntityManager::~NetworkEntityManager() { AzFramework::RootSpawnableNotificationBus::Handler::BusDisconnect(); - AZ::Interface::Unregister(this); } void NetworkEntityManager::Initialize(HostId hostId, AZStd::unique_ptr entityDomain) @@ -365,9 +363,24 @@ namespace Multiplayer return returnList; } - INetworkEntityManager::EntityList NetworkEntityManager::CreateEntitiesImmediate( - const PrefabEntityId& prefabEntryId, NetEntityId netEntityId, NetEntityRole netEntityRole, - AutoActivate autoActivate, const AZ::Transform& transform) + INetworkEntityManager::EntityList NetworkEntityManager::CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityRole netEntityRole, + const AZ::Transform& transform + ) + { + return CreateEntitiesImmediate(prefabEntryId, NextId(), netEntityRole, AutoActivate::Activate, transform); + } + + INetworkEntityManager::EntityList NetworkEntityManager::CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityId netEntityId, + NetEntityRole netEntityRole, + AutoActivate autoActivate, + const AZ::Transform& transform + ) { INetworkEntityManager::EntityList returnList; @@ -436,7 +449,7 @@ namespace Multiplayer void NetworkEntityManager::OnRootSpawnableAssigned( [[maybe_unused]] AZ::Data::Asset rootSpawnable, [[maybe_unused]] uint32_t generation) { - auto* multiplayer = AZ::Interface::Get(); + auto* multiplayer = GetMultiplayer(); const auto agentType = multiplayer->GetAgentType(); if (agentType == MultiplayerAgentType::Client) @@ -448,7 +461,7 @@ namespace Multiplayer void NetworkEntityManager::OnRootSpawnableReleased([[maybe_unused]] uint32_t generation) { // TODO: Do we need to clear all entities here? - auto* multiplayer = AZ::Interface::Get(); + auto* multiplayer = GetMultiplayer(); const auto agentType = multiplayer->GetAgentType(); if (agentType == MultiplayerAgentType::Client) @@ -494,7 +507,7 @@ namespace Multiplayer return; } - auto* multiplayer = AZ::Interface::Get(); + auto* multiplayer = GetMultiplayer(); const auto agentType = multiplayer->GetAgentType(); const bool spawnImmediately = diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h index ae2cb0dd9e..ba71eaf780 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h @@ -47,10 +47,20 @@ namespace Multiplayer ConstNetworkEntityHandle GetEntity(NetEntityId netEntityId) const override; EntityList CreateEntitiesImmediate(const AzFramework::Spawnable& spawnable, NetEntityRole netEntityRole); - - EntityList CreateEntitiesImmediate( - const PrefabEntityId& prefabEntryId, NetEntityId netEntityId, NetEntityRole netEntityRole, - AutoActivate autoActivate, const AZ::Transform& transform) override; + EntityList CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityRole netEntityRole, + const AZ::Transform& transform + ) override; + EntityList CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityId netEntityId, + NetEntityRole netEntityRole, + AutoActivate autoActivate, + const AZ::Transform& transform + ) override; uint32_t GetEntityCount() const override; NetworkEntityHandle AddEntityToEntityMap(NetEntityId netEntityId, AZ::Entity* entity) override; @@ -81,7 +91,6 @@ namespace Multiplayer private: void RemoveEntities(); - NetEntityId NextId(); void OnSpawned(AZ::Data::Asset spawnable); diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp index 8f70f7e1fa..114c3e3b43 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp index dee72156ed..c6eed626a9 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp index 9a0e784d36..c0200c9e6d 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp @@ -11,19 +11,12 @@ */ #include +#include +#include +#include namespace Multiplayer { - NetworkTime::NetworkTime() - { - AZ::Interface::Register(this); - } - - NetworkTime::~NetworkTime() - { - AZ::Interface::Unregister(this); - } - bool NetworkTime::IsTimeRewound() const { return m_rewindingConnectionId != AzNetworking::InvalidConnectionId; @@ -51,11 +44,6 @@ namespace Multiplayer return m_hostTimeMs; } - void NetworkTime::SyncRewindableEntityState() - { - - } - AzNetworking::ConnectionId NetworkTime::GetRewindingConnectionId() const { return m_rewindingConnectionId; @@ -72,4 +60,38 @@ namespace Multiplayer m_hostTimeMs = timeMs; m_rewindingConnectionId = rewindConnectionId; } + + void NetworkTime::SyncEntitiesToRewindState(const AZ::Aabb& rewindVolume) + { + // TODO: extrude rewind volume for initial gather + AZStd::vector gatheredEntries; + AZ::Interface::Get()->GetDefaultVisibilityScene()->Enumerate(rewindVolume, [&gatheredEntries](const AzFramework::IVisibilityScene::NodeData& nodeData) + { + gatheredEntries.reserve(gatheredEntries.size() + nodeData.m_entries.size()); + for (AzFramework::VisibilityEntry* visEntry : nodeData.m_entries) + { + if (visEntry->m_typeFlags & AzFramework::VisibilityEntry::TypeFlags::TYPE_Entity) + { + // TODO: offset aabb for exact rewound position and check against the non-extruded rewind volume + gatheredEntries.push_back(visEntry); + } + } + }); + + for (AzFramework::VisibilityEntry* visEntry : gatheredEntries) + { + AZ::Entity* entity = static_cast(visEntry->m_userData); + [[maybe_unused]] NetBindComponent* entryNetBindComponent = entity->template FindComponent(); + if (entryNetBindComponent != nullptr) + { + // TODO: invoke the sync to rewind event on the netBindComponent and add the entity to the rewound entity set + } + } + } + + void NetworkTime::ClearRewoundEntities() + { + AZ_Assert(!IsTimeRewound(), "Cannot clear rewound entity state while still within scoped rewind"); + // TODO: iterate all rewound entities, signal them to sync rewind state, and clear the rewound entity set + } } diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h index 06e758b349..47f557a11f 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h @@ -23,8 +23,8 @@ namespace Multiplayer : public INetworkTime { public: - NetworkTime(); - virtual ~NetworkTime(); + NetworkTime() = default; + virtual ~NetworkTime() = default; //! INetworkTime overrides. //! @{ @@ -33,10 +33,11 @@ namespace Multiplayer HostFrameId GetUnalteredHostFrameId() const override; void IncrementHostFrameId() override; AZ::TimeMs GetHostTimeMs() const override; - void SyncRewindableEntityState() override; AzNetworking::ConnectionId GetRewindingConnectionId() const override; HostFrameId GetHostFrameIdForRewindingConnection(AzNetworking::ConnectionId rewindConnectionId) const override; void AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId rewindConnectionId) override; + void SyncEntitiesToRewindState(const AZ::Aabb& rewindVolume) override; + void ClearRewoundEntities() override; //! @} private: diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl b/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl index 0835421ebd..2e67d42ede 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl +++ b/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl @@ -47,7 +47,7 @@ namespace Multiplayer template inline RewindableObject &RewindableObject::operator =(const RewindableObject& rhs) { - INetworkTime* networkTime = AZ::Interface::Get(); + INetworkTime* networkTime = GetNetworkTime(); SetValueForTime(rhs.GetValueForTime(networkTime->GetHostFrameId()), GetCurrentTimeForProperty()); return *this; } @@ -115,7 +115,7 @@ namespace Multiplayer template inline HostFrameId RewindableObject::GetCurrentTimeForProperty() const { - INetworkTime* networkTime = AZ::Interface::Get(); + INetworkTime* networkTime = GetNetworkTime(); return networkTime->GetHostFrameIdForRewindingConnection(m_owningConnectionId); } diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp index c54a610de2..a51bdc4acc 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp @@ -65,7 +65,7 @@ namespace Multiplayer { AZ::Entity* entity = m_controlledEntity.GetEntity(); AZ_Assert(entity, "Invalid controlled entity provided to replication window"); - m_controlledEntityTransform = entity->GetTransform(); + m_controlledEntityTransform = entity ? entity->GetTransform() : nullptr; AZ_Assert(m_controlledEntityTransform, "Controlled player entity must have a transform"); //// this one is optional diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h index 55a6a4b56e..b4e4427945 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include #include #include From 293e0057f4c0a74642e331dd052b3ae0d0468264 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 13:58:53 -0700 Subject: [PATCH 083/100] Actually invoke the override OnConnect handler --- Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 590faa6bad..15b6b48631 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -433,7 +433,8 @@ namespace Multiplayer if (m_onConnectFunctor) { - + // Default OnConnect behaviour has been overridden, + m_onConnectFunctor(connection, datum); } else { From 655d71e0ddfd69834537da5e2febd1f8a40fc59f Mon Sep 17 00:00:00 2001 From: greerdv Date: Wed, 12 May 2021 22:16:14 +0100 Subject: [PATCH 084/100] update compatibility of atom components with NonUniformScaleService --- .../Atom/Component/DebugCamera/CameraControllerComponent.h | 3 ++- .../Component/DebugCamera/Code/Source/CameraComponent.cpp | 1 + .../DebugCamera/Code/Source/CameraControllerComponent.cpp | 7 ++++++- .../AtomBridge/Code/Source/FlyCameraInputComponent.cpp | 6 ++++++ .../AtomBridge/Code/Source/FlyCameraInputComponent.h | 1 + .../Code/Source/Animation/AttachmentComponent.h | 1 + .../CoreLights/DirectionalLightComponentController.cpp | 1 + .../DiffuseProbeGridComponentController.cpp | 1 + .../ReflectionProbe/ReflectionProbeComponentController.cpp | 1 + .../Code/Source/SkyBox/HDRiSkyboxComponentController.cpp | 1 + .../Code/Source/SkyBox/PhysicalSkyComponentController.cpp | 1 + 11 files changed, 22 insertions(+), 2 deletions(-) diff --git a/Gems/Atom/Component/DebugCamera/Code/Include/Atom/Component/DebugCamera/CameraControllerComponent.h b/Gems/Atom/Component/DebugCamera/Code/Include/Atom/Component/DebugCamera/CameraControllerComponent.h index 4b2b19cff0..225952302a 100644 --- a/Gems/Atom/Component/DebugCamera/Code/Include/Atom/Component/DebugCamera/CameraControllerComponent.h +++ b/Gems/Atom/Component/DebugCamera/Code/Include/Atom/Component/DebugCamera/CameraControllerComponent.h @@ -41,7 +41,8 @@ namespace AZ static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); - + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + // CameraControllerRequestBus::Handler overrides void Enable(TypeId typeId) override final; void Reset() override final; diff --git a/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp b/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp index fbda0924e6..cbaa70929c 100644 --- a/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp +++ b/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp @@ -69,6 +69,7 @@ namespace AZ void CameraComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("CameraService", 0x1dd1caa4)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void CameraComponent::Activate() diff --git a/Gems/Atom/Component/DebugCamera/Code/Source/CameraControllerComponent.cpp b/Gems/Atom/Component/DebugCamera/Code/Source/CameraControllerComponent.cpp index 69e8469a56..e5a88dd409 100644 --- a/Gems/Atom/Component/DebugCamera/Code/Source/CameraControllerComponent.cpp +++ b/Gems/Atom/Component/DebugCamera/Code/Source/CameraControllerComponent.cpp @@ -32,12 +32,17 @@ namespace AZ required.push_back(AZ_CRC("TransformService", 0x8ee22c50)); required.push_back(AZ_CRC("CameraService", 0x1dd1caa4)); } - + void CameraControllerComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) { provided.push_back(AZ_CRC("CameraControllerService", 0xc35788f9)); } + void CameraControllerComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void CameraControllerComponent::Enable(TypeId typeId) { // Enable this controller if type id matches, otherwise disable this controller diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.cpp index 54e3a6ce59..3ad8bbae99 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.cpp @@ -78,6 +78,12 @@ void FlyCameraInputComponent::GetProvidedServices(AZ::ComponentDescriptor::Depen provided.push_back(AZ_CRC("InputService", 0xd41af40c)); } +////////////////////////////////////////////////////////////////////////////// +void FlyCameraInputComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) +{ + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); +} + ////////////////////////////////////////////////////////////////////////////// void FlyCameraInputComponent::Reflect(AZ::ReflectContext* reflection) { diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.h index 03fb3c421e..6c0232f358 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.h +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.h @@ -30,6 +30,7 @@ namespace AZ public: static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); static void Reflect(AZ::ReflectContext* reflection); AZ_COMPONENT(FlyCameraInputComponent, "{7AE0D6AD-691C-41B6-9DD5-F23F78B1A02E}"); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.h index ac03663f22..855c5494b3 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.h @@ -163,6 +163,7 @@ namespace AZ static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("AttachmentService", 0x5aaa7b63)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp index 310e6e6eca..6bff558268 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp @@ -121,6 +121,7 @@ namespace AZ void DirectionalLightComponentController::GetIncompatibleServices(ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("DirectionalLightService", 0x5270619f)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleComponent")); } void DirectionalLightComponentController::GetProvidedServices(ComponentDescriptor::DependencyArrayType& provided) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp index 8a0bd86965..0ddace1f87 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp @@ -73,6 +73,7 @@ namespace AZ void DiffuseProbeGridComponentController::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("DiffuseProbeGridService", 0x63d32042)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void DiffuseProbeGridComponentController::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp index 91040885f1..9b0ff29bb8 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp @@ -80,6 +80,7 @@ namespace AZ void ReflectionProbeComponentController::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("ReflectionProbeService", 0xa5b919ce)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void ReflectionProbeComponentController::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/HDRiSkyboxComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/HDRiSkyboxComponentController.cpp index f343a68f79..2c44124564 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/HDRiSkyboxComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/HDRiSkyboxComponentController.cpp @@ -51,6 +51,7 @@ namespace AZ void HDRiSkyboxComponentController::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("SkyBoxService", 0x8169a709)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void HDRiSkyboxComponentController::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/PhysicalSkyComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/PhysicalSkyComponentController.cpp index 867a81eefe..4a6b1608a4 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/PhysicalSkyComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/PhysicalSkyComponentController.cpp @@ -58,6 +58,7 @@ namespace AZ void PhysicalSkyComponentController::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("SkyBoxService", 0x8169a709)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void PhysicalSkyComponentController::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) From 50abafbab1bc0033395654c7491bfd3c2720d441 Mon Sep 17 00:00:00 2001 From: Steve Pham <82231385+spham-amzn@users.noreply.github.com> Date: Wed, 12 May 2021 14:31:39 -0700 Subject: [PATCH 085/100] Add orchestrating script to install ubuntu packages for O3DE on Linux (#721) SPEC-3510: Linux environment setup scripts * Add orchestrating script to install ubuntu packages for O3DE on Linux * Fix issue parsing package content file for build-tools --- .../Platform/Linux/install-ubuntu-awscli.sh | 2 +- .../Linux/install-ubuntu-build-tools.sh | 21 ++++---- .../Platform/Linux/install-ubuntu-git.sh | 8 ++-- .../Platform/Linux/install-ubuntu.sh | 48 +++++++++++++++++++ 4 files changed, 64 insertions(+), 15 deletions(-) create mode 100755 scripts/build/build_node/Platform/Linux/install-ubuntu.sh diff --git a/scripts/build/build_node/Platform/Linux/install-ubuntu-awscli.sh b/scripts/build/build_node/Platform/Linux/install-ubuntu-awscli.sh index 4c2f350859..8649f61fd1 100755 --- a/scripts/build/build_node/Platform/Linux/install-ubuntu-awscli.sh +++ b/scripts/build/build_node/Platform/Linux/install-ubuntu-awscli.sh @@ -38,7 +38,7 @@ then ./aws/install rm -rf ./aws else - AWS_CLI_VERSION=`aws --version | awk '{print $1}' | awk -F/ '{print $2}'` + AWS_CLI_VERSION=$(aws --version | awk '{print $1}' | awk -F/ '{print $2}') echo AWS CLI \(version $AWS_CLI_VERSION\) already installed fi diff --git a/scripts/build/build_node/Platform/Linux/install-ubuntu-build-tools.sh b/scripts/build/build_node/Platform/Linux/install-ubuntu-build-tools.sh index fd7b59592a..6fea3b03fa 100755 --- a/scripts/build/build_node/Platform/Linux/install-ubuntu-build-tools.sh +++ b/scripts/build/build_node/Platform/Linux/install-ubuntu-build-tools.sh @@ -26,7 +26,7 @@ then exit 1 fi -UBUNTU_DISTRO="`lsb_release -c | awk '{print $2}'`" +UBUNTU_DISTRO="$(lsb_release -c | awk '{print $2}')" if [ "$UBUNTU_DISTRO" == "bionic" ] then echo "Setup for Ubuntu 18.04 LTS ($UBUNTU_DISTRO)" @@ -53,7 +53,7 @@ fi # will install it from the bionic distro manually into focal. This is needed since Ubuntu 20.04 supports # python 3.8 out of the box, but we are using 3.7 # -LIBFFI6_COUNT=`apt list --installed 2>/dev/null | grep libffi6 | wc -l` +LIBFFI6_COUNT=$(apt list --installed 2>/dev/null | grep libffi6 | wc -l) if [ "$UBUNTU_DISTRO" == "focal" ] && [ $LIBFFI6_COUNT -eq 0 ] then echo "Installing libffi for Ubuntu 20.04" @@ -90,7 +90,7 @@ fi # Add the kitware repository for cmake if necessary # -KITWARE_REPO_COUNT=`cat /etc/apt/sources.list | grep ^deb | grep https://apt.kitware.com/ubuntu/ | wc -l` +KITWARE_REPO_COUNT=$(cat /etc/apt/sources.list | grep ^deb | grep https://apt.kitware.com/ubuntu/ | wc -l) if [ $KITWARE_REPO_COUNT -eq 0 ] then @@ -121,33 +121,34 @@ PACKAGE_FILE_LIST=package-list.ubuntu-$UBUNTU_DISTRO.txt echo Reading package list $PACKAGE_FILE_LIST # Read each line (strip out comment tags) -for LINE in `cat $PACKAGE_FILE_LIST | sed 's/#.*$//g'` +for PREPROC_LINE in $(cat $PACKAGE_FILE_LIST | sed 's/#.*$//g') do - PACKAGE=`echo $LINE | awk -F / '{print $1}'` + LINE=$(echo $PREPROC_LINE | tr -d '\r\n') + PACKAGE=$(echo $LINE | awk -F / '{$1=$1;print $1}') if [ "$PACKAGE" != "" ] # Skip blank lines then - PACKAGE_VER=`echo $LINE | awk -F / '{print $2}'` + PACKAGE_VER=$(echo $LINE | awk -F / '{$2=$2;print $2}') if [ "$PACKAGE_VER" == "" ] then # Process non-versioned packages - INSTALLED_COUNT=`apt list --installed 2>/dev/null | grep ^$PACKAGE/ | wc -l` + INSTALLED_COUNT=$(apt list --installed 2>/dev/null | grep ^$PACKAGE/ | wc -l) if [ $INSTALLED_COUNT -eq 0 ] then echo Installing $PACKAGE apt-get install $PACKAGE -y else - INSTALLED_VERSION=`apt list --installed 2>/dev/null | grep ^$PACKAGE/ | awk '{print $2}'` + INSTALLED_VERSION=$(apt list --installed 2>/dev/null | grep ^$PACKAGE/ | awk '{print $2}') echo $PACKAGE already installed \(version $INSTALLED_VERSION\) fi else # Process versioned packages - INSTALLED_COUNT=`apt list --installed 2>/dev/null | grep ^$PACKAGE/ | wc -l` + INSTALLED_COUNT=$(apt list --installed 2>/dev/null | grep ^$PACKAGE/ | wc -l) if [ $INSTALLED_COUNT -eq 0 ] then echo Installing $PACKAGE \( $PACKAGE_VER \) apt-get install $PACKAGE=$PACKAGE_VER -y else - INSTALLED_VERSION=`apt list --installed 2>/dev/null | grep ^$PACKAGE/ | awk '{print $2}'` + INSTALLED_VERSION=$(apt list --installed 2>/dev/null | grep ^$PACKAGE/ | awk '{print $2}') if [ "$INSTALLED_VERSION" != "$PACKAGE_VER" ] then echo $PACKAGE already installed but with the wrong version. Purging the package diff --git a/scripts/build/build_node/Platform/Linux/install-ubuntu-git.sh b/scripts/build/build_node/Platform/Linux/install-ubuntu-git.sh index 53554f4175..028b0082d7 100755 --- a/scripts/build/build_node/Platform/Linux/install-ubuntu-git.sh +++ b/scripts/build/build_node/Platform/Linux/install-ubuntu-git.sh @@ -26,7 +26,7 @@ then exit 1 fi -UBUNTU_DISTRO="`lsb_release -c | awk '{print $2}'`" +UBUNTU_DISTRO="$(lsb_release -c | awk '{print $2}')" if [ "$UBUNTU_DISTRO" == "bionic" ] then echo "Setup for Ubuntu 18.04 LTS ($UBUNTU_DISTRO)" @@ -49,14 +49,14 @@ then apt-get update apt-get install git -y else - GIT_VERSION=`git --version | awk '{print $3}'` + GIT_VERSION=$(git --version | awk '{print $3}') echo Git $GIT_VERSION already Installed. Skipping Git installation fi # # Setup Git-LFS if needed # -GIT_LFS_PACKAGE_COUNT=`apt list --installed 2>/dev/null | grep git-lfs/ | wc -l` +GIT_LFS_PACKAGE_COUNT=$(apt list --installed 2>/dev/null | grep git-lfs/ | wc -l) if [ $GIT_LFS_PACKAGE_COUNT -eq 0 ] then echo Setting up Git-LFS @@ -87,7 +87,7 @@ then dpkg -i $GCM_PACKAGE_NAME popd else - GCM_VERSION=`git-credential-manager-core --version` + GCM_VERSION=$(git-credential-manager-core --version) echo Git Credential Manager \(GCM\) version $GCM_VERSION already installed. Skipping GCM installation fi diff --git a/scripts/build/build_node/Platform/Linux/install-ubuntu.sh b/scripts/build/build_node/Platform/Linux/install-ubuntu.sh new file mode 100755 index 0000000000..9cdc94fa9e --- /dev/null +++ b/scripts/build/build_node/Platform/Linux/install-ubuntu.sh @@ -0,0 +1,48 @@ +#!/bin/bash + +# 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 script must be run as root +if [[ $EUID -ne 0 ]] +then + echo "This script must be run as root (sudo)" + exit 1 +fi + +echo Installing packages and tools for O3DE development + +# Install awscli +./install-ubuntu-awscli.sh +if [ $? -ne 0 ] +then + echo Error installing AWSCLI + exit 1 +fi + + +# Install git +./install-ubuntu-git.sh +if [ $? -ne 0 ] +then + echo Error installing Git + exit 1 +fi + +# Install the necessary build tools +./install-ubuntu-build-tools.sh +if [ $? -ne 0 ] +then + echo Error installing ubuntu tools + exit 1 +fi + + +echo Packages and tools for O3DE setup complete +exit 0 From 9b1f4c04e65e8ae29053d1070eacc67a18be7768 Mon Sep 17 00:00:00 2001 From: mriegger Date: Wed, 12 May 2021 14:54:33 -0700 Subject: [PATCH 086/100] Removing the old hack code --- .../Code/Source/Decals/AsyncLoadTracker.h | 18 ++++++++++-------- .../DecalTextureArrayFeatureProcessor.cpp | 18 +++++------------- .../Decals/DecalTextureArrayFeatureProcessor.h | 3 --- 3 files changed, 15 insertions(+), 24 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/AsyncLoadTracker.h b/Gems/Atom/Feature/Common/Code/Source/Decals/AsyncLoadTracker.h index ec35c4b51f..a3fff7b91e 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/AsyncLoadTracker.h +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/AsyncLoadTracker.h @@ -23,7 +23,9 @@ namespace AZ { public: - void TrackAssetLoad(const FeatureProcessorHandle handle, const AZ::Data::AssetId asset) + using MaterialAssetPtr = AZ::Data::Asset; + + void TrackAssetLoad(const FeatureProcessorHandle handle, const MaterialAssetPtr asset) { if (IsAssetLoading(handle)) { @@ -77,12 +79,12 @@ namespace AZ { const auto asset = EraseFromInFlightHandles(handle); - AZ_Assert(m_inFlightHandlesByAsset.count(asset) > 0, "AsyncLoadTracker in a bad state"); - auto& handleList = m_inFlightHandlesByAsset[asset]; + AZ_Assert(m_inFlightHandlesByAsset.count(asset.GetId()) > 0, "AsyncLoadTracker in a bad state"); + auto& handleList = m_inFlightHandlesByAsset[asset.GetId()]; EraseFromVector(handleList, handle); if (handleList.empty()) { - m_inFlightHandlesByAsset.erase(asset); + m_inFlightHandlesByAsset.erase(asset.GetId()); } } @@ -104,14 +106,14 @@ namespace AZ vec.pop_back(); } - void Add(const FeatureProcessorHandle handle, const AZ::Data::AssetId asset) + void Add(const FeatureProcessorHandle handle, const MaterialAssetPtr asset) { AZ_Assert(m_inFlightHandles.count(handle) == 0, "AsyncLoadTracker::Add() - told to add a handle that was already being tracked."); - m_inFlightHandlesByAsset[asset].push_back(handle); + m_inFlightHandlesByAsset[asset.GetId()].push_back(handle); m_inFlightHandles[handle] = asset; } - AZ::Data::AssetId EraseFromInFlightHandles(const FeatureProcessorHandle handle) + MaterialAssetPtr EraseFromInFlightHandles(const FeatureProcessorHandle handle) { const auto iter = m_inFlightHandles.find(handle); AZ_Assert(iter != m_inFlightHandles.end(), "Told to remove handle that was not present"); @@ -125,7 +127,7 @@ namespace AZ // Hash table that tracks the reverse of the m_inFlightHandlesByAsset hash table. // i.e. for each object, it stores what asset that it needs. - AZStd::unordered_map m_inFlightHandles; + AZStd::unordered_map m_inFlightHandles; }; } } diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp index 4000df646d..24857f8d65 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp @@ -85,7 +85,6 @@ namespace AZ m_decalData.Clear(); m_decalBufferHandler.Release(); - m_materialAssets.clear(); } DecalTextureArrayFeatureProcessor::DecalHandle DecalTextureArrayFeatureProcessor::AcquireDecal() @@ -410,7 +409,7 @@ namespace AZ int iter = m_textureArrayList.begin(); while (iter != -1) { - const auto packedTexture = m_textureArrayList[iter].second.GetPackedTexture(); + const auto& packedTexture = m_textureArrayList[iter].second.GetPackedTexture(); view->GetShaderResourceGroup()->SetImage(m_decalTextureArrayIndices[iter], packedTexture); iter = m_textureArrayList.next(iter); } @@ -482,22 +481,15 @@ namespace AZ return material; } - void DecalTextureArrayFeatureProcessor::QueueMaterialLoadForDecal(const AZ::Data::AssetId material, const DecalHandle handle) + void DecalTextureArrayFeatureProcessor::QueueMaterialLoadForDecal(const AZ::Data::AssetId materialId, const DecalHandle handle) { - // Note that another decal might have already queued this material for loading - if (m_materialLoadTracker.IsAssetLoading(material)) - { - m_materialLoadTracker.TrackAssetLoad(handle, material); - return; - } + const auto materialAsset = QueueMaterialAssetLoad(materialId); - const auto materialAsset = QueueMaterialAssetLoad(material); - m_materialAssets.emplace(material, materialAsset); - m_materialLoadTracker.TrackAssetLoad(handle, material); + m_materialLoadTracker.TrackAssetLoad(handle, materialAsset); if (materialAsset.IsLoading()) { - AZ::Data::AssetBus::MultiHandler::BusConnect(material); + AZ::Data::AssetBus::MultiHandler::BusConnect(materialId); } else if (materialAsset.IsReady()) { diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h index 825e461fc2..5301fcc61b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h @@ -136,11 +136,8 @@ namespace AZ GpuBufferHandler m_decalBufferHandler; AsyncLoadTracker m_materialLoadTracker; - AZStd::unordered_map< AZ::Data::AssetId, DecalLocationAndUseCount> m_materialToTextureArrayLookupTable; - AZStd::unordered_map> m_materialAssets; - bool m_deviceBufferNeedsUpdate = false; }; } // namespace Render From 254ad165c15b3d433b852cb05a06f563ccb4fff4 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 16:01:59 -0700 Subject: [PATCH 087/100] A bunch of work to get external multiplayer components to actually work --- .../{ => Multiplayer}/IConnectionData.h | 2 +- .../Include/{ => Multiplayer}/IEntityDomain.h | 2 +- .../Include/{ => Multiplayer}/IMultiplayer.h | 6 +-- .../IMultiplayerComponentInput.h | 2 +- .../{ => Multiplayer}/INetworkEntityManager.h | 4 +- .../Multiplayer/INetworkPlayerSpawner.h | 0 .../Include/{ => Multiplayer}/INetworkTime.h | 2 +- .../{ => Multiplayer}/IReplicationWindow.h | 4 +- .../Multiplayer}/MultiplayerComponent.h | 6 +-- .../MultiplayerComponentRegistry.h | 2 +- .../Multiplayer}/MultiplayerController.h | 8 +--- .../{ => Multiplayer}/MultiplayerStats.cpp | 2 +- .../{ => Multiplayer}/MultiplayerStats.h | 2 +- .../{ => Multiplayer}/MultiplayerTypes.h | 0 .../Multiplayer}/NetBindComponent.h | 11 ++--- .../{ => Multiplayer}/NetworkEntityHandle.h | 4 +- .../{ => Multiplayer}/NetworkEntityHandle.inl | 0 .../Multiplayer}/NetworkEntityRpcMessage.h | 2 +- .../Multiplayer}/NetworkEntityUpdateMessage.h | 2 +- .../Multiplayer}/NetworkInput.h | 6 +-- .../Multiplayer}/ReplicationRecord.h | 2 +- .../Multiplayer}/RewindableObject.h | 4 +- .../Multiplayer}/RewindableObject.inl | 0 .../AutoGen/AutoComponentTypes_Header.jinja | 2 +- .../AutoGen/AutoComponentTypes_Source.jinja | 8 ++-- .../Source/AutoGen/AutoComponent_Header.jinja | 26 +++++------ .../Source/AutoGen/AutoComponent_Source.jinja | 10 ++-- ...tionPlayerInputComponent.AutoComponent.xml | 4 +- .../AutoGen/Multiplayer.AutoPackets.xml | 8 ++-- ...etworkTransformComponent.AutoComponent.xml | 2 +- .../LocalPredictionPlayerInputComponent.h | 2 +- .../Components/MultiplayerComponent.cpp | 4 +- .../MultiplayerComponentRegistry.cpp | 2 +- .../Components/MultiplayerController.cpp | 6 +-- .../Source/Components/NetBindComponent.cpp | 29 +++--------- .../ClientToServerConnectionData.h | 2 +- .../ServerToClientConnectionData.h | 2 +- .../EntityDomains/FullOwnershipEntityDomain.h | 2 +- .../Code/Source/MultiplayerGem.cpp | 2 +- .../Source/MultiplayerSystemComponent.cpp | 2 +- .../Code/Source/MultiplayerSystemComponent.h | 2 +- .../EntityReplicationManager.cpp | 14 +++--- .../EntityReplicationManager.h | 10 ++-- .../EntityReplication/EntityReplicator.cpp | 6 +-- .../EntityReplication/EntityReplicator.h | 4 +- .../EntityReplication/PropertyPublisher.h | 2 +- .../EntityReplication/PropertySubscriber.cpp | 2 +- .../EntityReplication/ReplicationRecord.cpp | 2 +- .../NetworkEntityAuthorityTracker.cpp | 4 +- .../NetworkEntity/NetworkEntityHandle.cpp | 8 ++-- .../NetworkEntity/NetworkEntityManager.cpp | 5 +- .../NetworkEntity/NetworkEntityManager.h | 8 ++-- .../NetworkEntity/NetworkEntityRpcMessage.cpp | 2 +- .../NetworkEntity/NetworkEntityTracker.cpp | 2 +- .../NetworkEntity/NetworkEntityTracker.h | 4 +- .../NetworkEntityUpdateMessage.cpp | 2 +- .../Code/Source/NetworkInput/NetworkInput.cpp | 4 +- .../Source/NetworkInput/NetworkInputArray.cpp | 2 +- .../Source/NetworkInput/NetworkInputArray.h | 4 +- .../Source/NetworkInput/NetworkInputChild.cpp | 2 +- .../Source/NetworkInput/NetworkInputChild.h | 2 +- .../Source/NetworkInput/NetworkInputHistory.h | 2 +- .../NetworkInputMigrationVector.cpp | 2 +- .../NetworkInputMigrationVector.h | 4 +- .../Code/Source/NetworkTime/NetworkTime.cpp | 4 +- .../Code/Source/NetworkTime/NetworkTime.h | 2 +- .../NullReplicationWindow.h | 2 +- .../ServerToClientReplicationWindow.cpp | 2 +- .../ServerToClientReplicationWindow.h | 6 +-- Gems/Multiplayer/Code/multiplayer_files.cmake | 46 +++++++++---------- 70 files changed, 162 insertions(+), 185 deletions(-) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/IConnectionData.h (97%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/IEntityDomain.h (97%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/IMultiplayer.h (98%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/IMultiplayerComponentInput.h (96%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/INetworkEntityManager.h (98%) create mode 100644 Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/INetworkTime.h (98%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/IReplicationWindow.h (94%) rename Gems/Multiplayer/Code/{Source/Components => Include/Multiplayer}/MultiplayerComponent.h (97%) rename Gems/Multiplayer/Code/{Source/Components => Include/Multiplayer}/MultiplayerComponentRegistry.h (98%) rename Gems/Multiplayer/Code/{Source/Components => Include/Multiplayer}/MultiplayerController.h (90%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/MultiplayerStats.cpp (99%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/MultiplayerStats.h (98%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/MultiplayerTypes.h (100%) rename Gems/Multiplayer/Code/{Source/Components => Include/Multiplayer}/NetBindComponent.h (95%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/NetworkEntityHandle.h (98%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/NetworkEntityHandle.inl (100%) rename Gems/Multiplayer/Code/{Source/NetworkEntity => Include/Multiplayer}/NetworkEntityRpcMessage.h (99%) rename Gems/Multiplayer/Code/{Source/NetworkEntity => Include/Multiplayer}/NetworkEntityUpdateMessage.h (99%) rename Gems/Multiplayer/Code/{Source/NetworkInput => Include/Multiplayer}/NetworkInput.h (95%) rename Gems/Multiplayer/Code/{Source/NetworkEntity/EntityReplication => Include/Multiplayer}/ReplicationRecord.h (98%) rename Gems/Multiplayer/Code/{Source/NetworkTime => Include/Multiplayer}/RewindableObject.h (98%) rename Gems/Multiplayer/Code/{Source/NetworkTime => Include/Multiplayer}/RewindableObject.inl (100%) diff --git a/Gems/Multiplayer/Code/Include/IConnectionData.h b/Gems/Multiplayer/Code/Include/Multiplayer/IConnectionData.h similarity index 97% rename from Gems/Multiplayer/Code/Include/IConnectionData.h rename to Gems/Multiplayer/Code/Include/Multiplayer/IConnectionData.h index dcc2c940ef..39fdb61435 100644 --- a/Gems/Multiplayer/Code/Include/IConnectionData.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IConnectionData.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Include/IEntityDomain.h b/Gems/Multiplayer/Code/Include/Multiplayer/IEntityDomain.h similarity index 97% rename from Gems/Multiplayer/Code/Include/IEntityDomain.h rename to Gems/Multiplayer/Code/Include/Multiplayer/IEntityDomain.h index 6571797d05..70215612b0 100644 --- a/Gems/Multiplayer/Code/Include/IEntityDomain.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IEntityDomain.h @@ -12,7 +12,7 @@ #pragma once -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Include/IMultiplayer.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h similarity index 98% rename from Gems/Multiplayer/Code/Include/IMultiplayer.h rename to Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h index 80bdaa68eb..665661b55b 100644 --- a/Gems/Multiplayer/Code/Include/IMultiplayer.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h @@ -15,9 +15,9 @@ #include #include #include -#include -#include -#include +#include +#include +#include namespace AzNetworking { diff --git a/Gems/Multiplayer/Code/Include/IMultiplayerComponentInput.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerComponentInput.h similarity index 96% rename from Gems/Multiplayer/Code/Include/IMultiplayerComponentInput.h rename to Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerComponentInput.h index b5df01a1a8..b26feadc4f 100644 --- a/Gems/Multiplayer/Code/Include/IMultiplayerComponentInput.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerComponentInput.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Include/INetworkEntityManager.h b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkEntityManager.h similarity index 98% rename from Gems/Multiplayer/Code/Include/INetworkEntityManager.h rename to Gems/Multiplayer/Code/Include/Multiplayer/INetworkEntityManager.h index ebb95e2281..17224e64cb 100644 --- a/Gems/Multiplayer/Code/Include/INetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkEntityManager.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Gems/Multiplayer/Code/Include/INetworkTime.h b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h similarity index 98% rename from Gems/Multiplayer/Code/Include/INetworkTime.h rename to Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h index 1ccf08bbdc..c228e135ee 100644 --- a/Gems/Multiplayer/Code/Include/INetworkTime.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h @@ -14,7 +14,7 @@ #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Include/IReplicationWindow.h b/Gems/Multiplayer/Code/Include/Multiplayer/IReplicationWindow.h similarity index 94% rename from Gems/Multiplayer/Code/Include/IReplicationWindow.h rename to Gems/Multiplayer/Code/Include/Multiplayer/IReplicationWindow.h index eb34a2f87d..d0192e8aa4 100644 --- a/Gems/Multiplayer/Code/Include/IReplicationWindow.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IReplicationWindow.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponent.h similarity index 97% rename from Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.h rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponent.h index 0f64221dde..29348a698a 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponent.h @@ -15,9 +15,9 @@ #include #include #include -#include -#include -#include +#include +#include +#include //! Macro to declare bindings for a multiplayer component inheriting from MultiplayerComponent #define AZ_MULTIPLAYER_COMPONENT(ComponentClass, Guid, Base) \ diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponentRegistry.h similarity index 98% rename from Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.h rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponentRegistry.h index e16f942100..d06362ed4b 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponentRegistry.h @@ -14,7 +14,7 @@ #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerController.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerController.h similarity index 90% rename from Gems/Multiplayer/Code/Source/Components/MultiplayerController.h rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerController.h index de07e39e66..89c47c40d4 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerController.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerController.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace Multiplayer @@ -84,12 +84,6 @@ namespace Multiplayer //! Returns the input priority ordering for determining the order of ProcessInput or CreateInput functions. virtual InputPriorityOrder GetInputOrder() const = 0; - //! Queries the rewind system to determine what volume is relevent for a given input, this is very important for performance at scale. - //! @param networkInput input structure to process - //! @param deltaTime amount of time the provided input would be integrated over - //! @return a world-space aabb representing the volume relevent to the provided input - virtual AZ::Aabb GetRewindBoundsForInput(const NetworkInput& networkInput, float deltaTime) const = 0; - //! Base execution for ProcessInput packet, do not call directly. //! @param networkInput input structure to process //! @param deltaTime amount of time to integrate the provided inputs over diff --git a/Gems/Multiplayer/Code/Include/MultiplayerStats.cpp b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.cpp similarity index 99% rename from Gems/Multiplayer/Code/Include/MultiplayerStats.cpp rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.cpp index 7672997ad5..1f063b749d 100644 --- a/Gems/Multiplayer/Code/Include/MultiplayerStats.cpp +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.cpp @@ -10,7 +10,7 @@ * */ -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Include/MultiplayerStats.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h similarity index 98% rename from Gems/Multiplayer/Code/Include/MultiplayerStats.h rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h index dc266a14bf..5d00c4d205 100644 --- a/Gems/Multiplayer/Code/Include/MultiplayerStats.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h @@ -15,7 +15,7 @@ #include #include #include -#include +#include namespace AzNetworking { diff --git a/Gems/Multiplayer/Code/Include/MultiplayerTypes.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerTypes.h similarity index 100% rename from Gems/Multiplayer/Code/Include/MultiplayerTypes.h rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerTypes.h diff --git a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetBindComponent.h similarity index 95% rename from Gems/Multiplayer/Code/Source/Components/NetBindComponent.h rename to Gems/Multiplayer/Code/Include/Multiplayer/NetBindComponent.h index 0885e44aa4..464333e3b2 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetBindComponent.h @@ -20,11 +20,11 @@ #include #include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include namespace Multiplayer @@ -73,7 +73,6 @@ namespace Multiplayer bool IsProcessingInput() const; void CreateInput(NetworkInput& networkInput, float deltaTime); void ProcessInput(NetworkInput& networkInput, float deltaTime); - AZ::Aabb GetRewindBoundsForInput(const NetworkInput& networkInput, float deltaTime) const; bool HandleRpcMessage(AzNetworking::IConnection* invokingConnection, NetEntityRole remoteRole, NetworkEntityRpcMessage& message); bool HandlePropertyChangeMessage(AzNetworking::ISerializer& serializer, bool notifyChanges = true); diff --git a/Gems/Multiplayer/Code/Include/NetworkEntityHandle.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityHandle.h similarity index 98% rename from Gems/Multiplayer/Code/Include/NetworkEntityHandle.h rename to Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityHandle.h index 9b8546ef2c..813589fac6 100644 --- a/Gems/Multiplayer/Code/Include/NetworkEntityHandle.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityHandle.h @@ -13,7 +13,7 @@ #pragma once #include -#include +#include namespace Multiplayer { @@ -138,4 +138,4 @@ namespace Multiplayer }; } -#include +#include diff --git a/Gems/Multiplayer/Code/Include/NetworkEntityHandle.inl b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityHandle.inl similarity index 100% rename from Gems/Multiplayer/Code/Include/NetworkEntityHandle.inl rename to Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityHandle.inl diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityRpcMessage.h similarity index 99% rename from Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.h rename to Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityRpcMessage.h index 08b1960172..f6a7ff2c65 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityRpcMessage.h @@ -14,7 +14,7 @@ #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityUpdateMessage.h similarity index 99% rename from Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.h rename to Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityUpdateMessage.h index 9ca539d75d..e96191262a 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityUpdateMessage.h @@ -15,7 +15,7 @@ #include #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput.h similarity index 95% rename from Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.h rename to Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput.h index b2b0fa12c6..9c6d2ce66a 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput.h @@ -12,9 +12,9 @@ #pragma once -#include -#include -#include +#include +#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.h b/Gems/Multiplayer/Code/Include/Multiplayer/ReplicationRecord.h similarity index 98% rename from Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.h rename to Gems/Multiplayer/Code/Include/Multiplayer/ReplicationRecord.h index 83721a5539..f6eb93c4ba 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/ReplicationRecord.h @@ -15,7 +15,7 @@ #include #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.h b/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.h similarity index 98% rename from Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.h rename to Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.h index 4e830d4480..9e1655aec7 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include #include #include @@ -115,4 +115,4 @@ namespace AZ AZ_TYPE_INFO_TEMPLATE(Multiplayer::RewindableObject, "{B2937B44-FEE1-4277-B1E0-863DE76D363F}", AZ_TYPE_INFO_TYPENAME, AZ_TYPE_INFO_AUTO); } -#include +#include diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl b/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl similarity index 100% rename from Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl rename to Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Header.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Header.jinja index fc2860ebe7..849b4245e2 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Header.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Header.jinja @@ -1,7 +1,7 @@ #pragma once #include -#include +#include namespace AZ { diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja index 2acc252729..453d74c907 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja @@ -1,6 +1,6 @@ #include -#include -#include +#include +#include {% for Component in dataFiles %} {% set ComponentDerived = Component.attrib['OverrideComponent']|booleanTrue %} {% set ControllerDerived = Component.attrib['OverrideController']|booleanTrue %} @@ -21,8 +21,8 @@ namespace {{ Namespace }} { void RegisterMultiplayerComponents() { - Multiplayer::MultiplayerComponentRegistry* multiplayerComponentRegistry = GetMultiplayerComponentRegistry(); - Multiplayer::MultiplayerStats& stats = GetMultiplayer()->GetStats(); + Multiplayer::MultiplayerComponentRegistry* multiplayerComponentRegistry = Multiplayer::GetMultiplayerComponentRegistry(); + Multiplayer::MultiplayerStats& stats = Multiplayer::GetMultiplayer()->GetStats(); {% for Component in dataFiles %} {% set ComponentName = Component.attrib['Name'] %} {% set ComponentBaseName = ComponentName %} diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja index faaa009e34..c22945c983 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja @@ -221,13 +221,14 @@ AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] } #include #include #include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include {% call(Include) AutoComponentMacros.ParseIncludes(Component) %} #include <{{ Include.attrib['File'] }}> {% endcall %} @@ -359,7 +360,6 @@ namespace {{ Component.attrib['Namespace'] }} //! MultiplayerController interface //! @{ Multiplayer::MultiplayerController::InputPriorityOrder GetInputOrder() const override { return Multiplayer::MultiplayerController::InputPriorityOrder::Default; } - AZ::Aabb GetRewindBoundsForInput([[maybe_unused]] const NetworkInput& networkInput, [[maybe_unused]] float deltaTime) const override { return AZ::Aabb::CreateNull(); } void CreateInput([[maybe_unused]] Multiplayer::NetworkInput& input, [[maybe_unused]] float deltaTime) override {} void ProcessInput([[maybe_unused]] Multiplayer::NetworkInput& input, [[maybe_unused]] float deltaTime) override {} //! @} @@ -434,12 +434,12 @@ namespace {{ Component.attrib['Namespace'] }} //! MultiplayerComponent interface //! @{ - NetComponentId GetNetComponentId() const override; + Multiplayer::NetComponentId GetNetComponentId() const override; bool HandleRpcMessage(AzNetworking::IConnection* invokingConnection, Multiplayer::NetEntityRole remoteRole, Multiplayer::NetworkEntityRpcMessage& rpcMessage) override; bool SerializeStateDeltaMessage(Multiplayer::ReplicationRecord& replicationRecord, AzNetworking::ISerializer& serializer) override; void NotifyStateDeltaChanges(Multiplayer::ReplicationRecord& replicationRecord) override; bool HasController() const override; - MultiplayerController* GetController() override; + Multiplayer::MultiplayerController* GetController() override; protected: void ConstructController() override; @@ -484,8 +484,8 @@ namespace {{ Component.attrib['Namespace'] }} void NotifyChangesAutonomousToAuthorityProperties(const {{ RecordName }}& replicationRecord) const; //! Debug name helpers - static const char* GetNetworkPropertyName(PropertyIndex propertyIndex); - static const char* GetRpcName(RpcIndex rpcIndex); + static const char* GetNetworkPropertyName(Multiplayer::PropertyIndex propertyIndex); + static const char* GetRpcName(Multiplayer::RpcIndex rpcIndex); AZStd::unique_ptr<{{ RecordName }}> m_currentRecord; AZStd::unique_ptr<{{ ControllerName }}> m_controller; @@ -517,7 +517,7 @@ namespace {{ Component.attrib['Namespace'] }} {{ Type }}* {{ Name }} = nullptr; {% endcall %} - static NetComponentId s_netComponentId; + static Multiplayer::NetComponentId s_netComponentId; friend void RegisterMultiplayerComponents(); }; } diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index d719cbe47b..1bc6dc3994 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -902,8 +902,8 @@ m_{{ LowerFirst(Property.attrib['Name']) }} = m_{{ LowerFirst(Property.attrib['N #include #include #include -#include -#include +#include +#include {% if ComponentDerived or ControllerDerived %} #include <{{ Component.attrib['OverrideInclude'] }}> {% endif %} @@ -915,7 +915,7 @@ m_{{ LowerFirst(Property.attrib['Name']) }} = m_{{ LowerFirst(Property.attrib['N namespace {{ Component.attrib['Namespace'] }} { - NetComponentId {{ UpperFirst(ComponentBaseName) }}::s_netComponentId = InvalidNetComponentId; + Multiplayer::NetComponentId {{ UpperFirst(ComponentBaseName) }}::s_netComponentId = Multiplayer::InvalidNetComponentId; namespace {{ UpperFirst(Component.attrib['Name']) }}Internal { @@ -1408,7 +1408,7 @@ namespace {{ Component.attrib['Namespace'] }} } {% endif %} - const char* {{ ComponentBaseName }}::GetNetworkPropertyName([[maybe_unused]] PropertyIndex propertyIndex) + const char* {{ ComponentBaseName }}::GetNetworkPropertyName([[maybe_unused]] Multiplayer::PropertyIndex propertyIndex) { {% if NetworkPropertyCount > 0 %} const {{ UpperFirst(Component.attrib['Name']) }}Internal::NetworkProperties propertyId = static_cast<{{ UpperFirst(Component.attrib['Name']) }}Internal::NetworkProperties>(propertyIndex); @@ -1423,7 +1423,7 @@ namespace {{ Component.attrib['Namespace'] }} return "Unknown network property"; } - const char* {{ ComponentBaseName }}::GetRpcName([[maybe_unused]] RpcIndex rpcIndex) + const char* {{ ComponentBaseName }}::GetRpcName([[maybe_unused]] Multiplayer::RpcIndex rpcIndex) { {% if RpcCount > 0 %} const {{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure rpcId = static_cast<{{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure>(rpcIndex); diff --git a/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml b/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml index 44edcaf505..a5a7e8decd 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml @@ -10,8 +10,8 @@ - - + + diff --git a/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml b/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml index daf55c3d92..1260075cba 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml @@ -2,10 +2,10 @@ - - - - + + + + diff --git a/Gems/Multiplayer/Code/Source/AutoGen/NetworkTransformComponent.AutoComponent.xml b/Gems/Multiplayer/Code/Source/AutoGen/NetworkTransformComponent.AutoComponent.xml index 46065b386f..e76ac75edc 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/NetworkTransformComponent.AutoComponent.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/NetworkTransformComponent.AutoComponent.xml @@ -10,7 +10,7 @@ - + diff --git a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.h b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.h index 15a4f3a048..924fd78391 100644 --- a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.h +++ b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.h @@ -13,7 +13,7 @@ #pragma once #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.cpp b/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.cpp index fcdad87416..ae6fc50f5a 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.cpp @@ -10,8 +10,8 @@ * */ -#include -#include +#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.cpp b/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.cpp index de1782cc59..648b28633e 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.cpp +++ b/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.cpp @@ -10,7 +10,7 @@ * */ -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerController.cpp b/Gems/Multiplayer/Code/Source/Components/MultiplayerController.cpp index 737ecc10cc..9b8f41d5bc 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerController.cpp +++ b/Gems/Multiplayer/Code/Source/Components/MultiplayerController.cpp @@ -10,9 +10,9 @@ * */ -#include -#include -#include +#include +#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp index eba09734a9..6dc661415e 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp @@ -10,13 +10,13 @@ * */ -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include #include #include #include @@ -177,21 +177,6 @@ namespace Multiplayer } } - AZ::Aabb NetBindComponent::GetRewindBoundsForInput(const NetworkInput& networkInput, float deltaTime) const - { - AZ_Assert(m_netEntityRole == NetEntityRole::Authority, "Incorrect network role for computing rewind bounds"); - AZ::Aabb bounds = AZ::Aabb::CreateNull(); - for (MultiplayerComponent* multiplayerComponent : m_multiplayerInputComponentVector) - { - const AZ::Aabb componentBounds = multiplayerComponent->GetController()->GetRewindBoundsForInput(networkInput, deltaTime); - if (componentBounds.IsValid()) - { - bounds.AddAabb(componentBounds); - } - } - return bounds; - } - bool NetBindComponent::HandleRpcMessage(AzNetworking::IConnection* invokingConnection, NetEntityRole remoteRole, NetworkEntityRpcMessage& message) { auto findIt = m_multiplayerComponentMap.find(message.GetComponentId()); diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h index b72a6aad2b..449ffafe45 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h +++ b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h b/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h index b02e6de9aa..6274a6ba31 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h +++ b/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/EntityDomains/FullOwnershipEntityDomain.h b/Gems/Multiplayer/Code/Source/EntityDomains/FullOwnershipEntityDomain.h index c1abbe74cd..3bf6eb554f 100644 --- a/Gems/Multiplayer/Code/Source/EntityDomains/FullOwnershipEntityDomain.h +++ b/Gems/Multiplayer/Code/Source/EntityDomains/FullOwnershipEntityDomain.h @@ -12,7 +12,7 @@ #pragma once -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/MultiplayerGem.cpp b/Gems/Multiplayer/Code/Source/MultiplayerGem.cpp index cafdbf2a09..aef3e546ad 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerGem.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerGem.cpp @@ -13,10 +13,10 @@ #include #include #include -#include #include #include #include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 15b6b48631..715d9a8527 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -11,13 +11,13 @@ */ #include -#include #include #include #include #include #include #include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h index 1de8fccb50..ba59a82eae 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp index 65df4f1464..6eefeaf5fe 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp @@ -14,14 +14,14 @@ #include #include #include -#include -#include -#include #include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.h b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.h index 4fc14e210f..50a4ad43d4 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.h @@ -13,11 +13,11 @@ #pragma once #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp index 197d83a48c..15293d518d 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp @@ -16,11 +16,11 @@ #include #include #include -#include -#include #include #include -#include +#include +#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.h b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.h index 93494ab07c..3587c28975 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.h @@ -18,8 +18,8 @@ #include #include #include -#include -#include +#include +#include namespace AzNetworking { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertyPublisher.h b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertyPublisher.h index 238e665a00..be8ac1b65b 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertyPublisher.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertyPublisher.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace AzNetworking diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp index 7b8c3e6094..4994884364 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp @@ -12,7 +12,7 @@ #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp index 5f8dae8ff4..6aa6c10b11 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp @@ -10,7 +10,7 @@ * */ -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp index 797d67e3ef..ecfd416380 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp @@ -11,8 +11,8 @@ */ #include -#include -#include +#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.cpp index ca0275d20b..0dd7292d25 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.cpp @@ -10,11 +10,11 @@ * */ -#include +#include +#include +#include +#include #include -#include -#include -#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index 7ee4d45e93..28b72abf25 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -11,7 +11,6 @@ */ #include - #include #include #include @@ -22,9 +21,9 @@ #include #include #include -#include +#include +#include #include -#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h index ba71eaf780..e763e7ebca 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h @@ -17,11 +17,11 @@ #include #include #include -#include -#include -#include #include -#include +#include +#include +#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.cpp index 4bfc753f75..d58c192162 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.cpp @@ -10,7 +10,7 @@ * */ -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp index 69f715317a..42104e79fd 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h index 4cfb242154..34f5d03f2f 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.cpp index 27c39ea135..5ece0c7157 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.cpp @@ -10,7 +10,7 @@ * */ -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp index 0ab1d5ffcc..eafd4375e7 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp @@ -10,8 +10,8 @@ * */ -#include -#include +#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.cpp index 0f5a0d7c0c..82e5cea0c4 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.h b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.h index 504992fecb..d5cbcbbed3 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.h +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp index 114c3e3b43..c6b8e8d7ef 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.h b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.h index 18b518f19f..fa4ab1e4e9 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.h +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.h @@ -12,7 +12,7 @@ #pragma once -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputHistory.h b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputHistory.h index ad406ffd8b..c5f0a70fd3 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputHistory.h +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputHistory.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp index c6eed626a9..4395ff5b7d 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.h b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.h index c6ea425fec..454cef4e0a 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.h +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp index c0200c9e6d..ab5988444b 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp @@ -11,8 +11,8 @@ */ #include -#include -#include +#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h index 47f557a11f..18adc00140 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.h b/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.h index 1922e65941..5cb9c0de70 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.h +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.h @@ -12,7 +12,7 @@ #pragma once -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp index a51bdc4acc..bf370c1952 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h index b4e4427945..25fbfd481d 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h @@ -12,9 +12,9 @@ #pragma once -#include -#include -#include +#include +#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/multiplayer_files.cmake b/Gems/Multiplayer/Code/multiplayer_files.cmake index 1f4e57ae43..bea88af10c 100644 --- a/Gems/Multiplayer/Code/multiplayer_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_files.cmake @@ -10,18 +10,28 @@ # set(FILES - Include/IConnectionData.h - Include/IEntityDomain.h - Include/IMultiplayer.h - Include/IMultiplayerComponentInput.h - Include/INetworkEntityManager.h - Include/INetworkTime.h - Include/IReplicationWindow.h - Include/MultiplayerStats.cpp - Include/MultiplayerStats.h - Include/MultiplayerTypes.h - Include/NetworkEntityHandle.h - Include/NetworkEntityHandle.inl + Include/Multiplayer/IConnectionData.h + Include/Multiplayer/IEntityDomain.h + Include/Multiplayer/IMultiplayer.h + Include/Multiplayer/IMultiplayerComponentInput.h + Include/Multiplayer/INetworkEntityManager.h + Include/Multiplayer/INetworkTime.h + Include/Multiplayer/IReplicationWindow.h + Include/Multiplayer/MultiplayerComponent.h + Include/Multiplayer/MultiplayerController.h + Include/Multiplayer/MultiplayerComponentRegistry.h + Include/Multiplayer/MultiplayerStats.cpp + Include/Multiplayer/MultiplayerStats.h + Include/Multiplayer/MultiplayerTypes.h + Include/Multiplayer/NetBindComponent.h + Include/Multiplayer/NetworkEntityRpcMessage.h + Include/Multiplayer/NetworkEntityUpdateMessage.h + Include/Multiplayer/NetworkEntityHandle.h + Include/Multiplayer/NetworkEntityHandle.inl + Include/Multiplayer/NetworkInput.h + Include/Multiplayer/ReplicationRecord.h + Include/Multiplayer/RewindableObject.h + Include/Multiplayer/RewindableObject.inl Source/Multiplayer_precompiled.cpp Source/Multiplayer_precompiled.h Source/MultiplayerSystemComponent.cpp @@ -36,14 +46,10 @@ set(FILES Source/AutoGen/NetworkTransformComponent.AutoComponent.xml Source/Components/LocalPredictionPlayerInputComponent.cpp Source/Components/LocalPredictionPlayerInputComponent.h - Source/Components/MultiplayerComponentRegistry.cpp - Source/Components/MultiplayerComponentRegistry.h Source/Components/MultiplayerComponent.cpp - Source/Components/MultiplayerComponent.h Source/Components/MultiplayerController.cpp - Source/Components/MultiplayerController.h + Source/Components/MultiplayerComponentRegistry.cpp Source/Components/NetBindComponent.cpp - Source/Components/NetBindComponent.h Source/Components/NetworkTransformComponent.cpp Source/Components/NetworkTransformComponent.h Source/ConnectionData/ClientToServerConnectionData.cpp @@ -64,7 +70,6 @@ set(FILES Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp Source/NetworkEntity/EntityReplication/PropertySubscriber.h Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp - Source/NetworkEntity/EntityReplication/ReplicationRecord.h Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp Source/NetworkEntity/NetworkEntityAuthorityTracker.h Source/NetworkEntity/NetworkEntityHandle.cpp @@ -73,14 +78,11 @@ set(FILES Source/NetworkEntity/NetworkSpawnableLibrary.cpp Source/NetworkEntity/NetworkSpawnableLibrary.h Source/NetworkEntity/NetworkEntityRpcMessage.cpp - Source/NetworkEntity/NetworkEntityRpcMessage.h Source/NetworkEntity/NetworkEntityTracker.cpp Source/NetworkEntity/NetworkEntityTracker.h Source/NetworkEntity/NetworkEntityTracker.inl Source/NetworkEntity/NetworkEntityUpdateMessage.cpp - Source/NetworkEntity/NetworkEntityUpdateMessage.h Source/NetworkInput/NetworkInput.cpp - Source/NetworkInput/NetworkInput.h Source/NetworkInput/NetworkInputArray.cpp Source/NetworkInput/NetworkInputArray.h Source/NetworkInput/NetworkInputChild.cpp @@ -91,8 +93,6 @@ set(FILES Source/NetworkInput/NetworkInputMigrationVector.h Source/NetworkTime/NetworkTime.cpp Source/NetworkTime/NetworkTime.h - Source/NetworkTime/RewindableObject.h - Source/NetworkTime/RewindableObject.inl Source/Pipeline/NetBindMarkerComponent.cpp Source/Pipeline/NetBindMarkerComponent.h Source/Pipeline/NetworkSpawnableHolderComponent.cpp From 8bb425709b38d2f574de0eafe842f3a0cffea8dc Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 16:04:44 -0700 Subject: [PATCH 088/100] unit test fix --- Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp index 367b7ee0de..9f1b879856 100644 --- a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp +++ b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp @@ -10,7 +10,8 @@ * */ -#include +#include +#include #include #include #include From 67c3801d73fbcf67e93f9d42c3548923a580bf5d Mon Sep 17 00:00:00 2001 From: SSpalding <57235700+AMZN-scspaldi@users.noreply.github.com> Date: Wed, 12 May 2021 16:15:18 -0700 Subject: [PATCH 089/100] Log monitor encoding fix (#729) Fixed log monitor encoding bug. --- Tools/LyTestTools/ly_test_tools/log/log_monitor.py | 4 ++-- Tools/LyTestTools/tests/unit/test_log_monitor.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/Tools/LyTestTools/ly_test_tools/log/log_monitor.py b/Tools/LyTestTools/ly_test_tools/log/log_monitor.py index ca3cd24303..ea3991342a 100755 --- a/Tools/LyTestTools/ly_test_tools/log/log_monitor.py +++ b/Tools/LyTestTools/ly_test_tools/log/log_monitor.py @@ -44,7 +44,7 @@ def check_exact_match(line, expected_line): # Look for either start of line or whitespace, then the expected_line, then either end of the line or whitespace. # This way we don't partial match inside of a string. So for example, 'foo' matches 'foo bar' but not 'foobar' - regex_pattern = re.compile("(^|\\s){}($|\\s)".format(re.escape(expected_line))) + regex_pattern = re.compile("(^|\\s){}($|\\s)".format(re.escape(expected_line)), re.UNICODE) if regex_pattern.search(line) is not None: return expected_line @@ -125,7 +125,7 @@ class LogMonitor(object): self.py_log = "" try: logger.debug("Monitoring log file in '{}' ".format(self.log_file_path)) - with open(self.log_file_path, mode='r') as log: + with open(self.log_file_path, mode='r', encoding='utf-8') as log: logger.info( "Monitoring log file '{}' for '{}' seconds".format(self.log_file_path, timeout)) diff --git a/Tools/LyTestTools/tests/unit/test_log_monitor.py b/Tools/LyTestTools/tests/unit/test_log_monitor.py index 5be2b48d8b..2dd588f9ff 100755 --- a/Tools/LyTestTools/tests/unit/test_log_monitor.py +++ b/Tools/LyTestTools/tests/unit/test_log_monitor.py @@ -98,6 +98,16 @@ class TestLogMonitor(object): under_test = ly_test_tools.log.log_monitor.check_exact_match(line, expected_line) assert under_test == expected_line + @mock.patch('os.path.exists', mock.MagicMock(return_value=True)) + def test_Monitor_UTF8StringsPresentAndExpected_Success(self): + mock_file = io.StringIO('gr\xc3\xb6\xc3\x9feren pr\xc3\xbcfung \xd1\x82\xd0\xb5\xd1\x81\xd1\x82\xd1\x83\xd0\xb2\xd0\xb0\xd0\xbd\xd0\xbd\xd1\x8f\n\xc3\x80\xc3\x88\xc3\x8c\xc3\x92\xc3\x99\n\xc3\x85lpha\xc3\x9fravo\xc3\xa7harlie\n') + mock_launcher.is_alive.side_effect = [True, True, True, False] + + with mock.patch('ly_test_tools.log.log_monitor.open', return_value=mock_file, create=True): + mock_log_monitor().monitor_log_for_lines(['gr\xc3\xb6\xc3\x9feren pr\xc3\xbcfung \xd1\x82\xd0\xb5\xd1\x81\xd1\x82\xd1\x83\xd0\xb2\xd0\xb0\xd0\xbd\xd0\xbd\xd1\x8f', + '\xc3\x80\xc3\x88\xc3\x8c\xc3\x92\xc3\x99', + '\xc3\x85lpha\xc3\x9fravo\xc3\xa7harlie']) + @mock.patch('os.path.exists', mock.MagicMock(return_value=True)) def test_Monitor_AllLinesFound_Success(self): mock_file = io.StringIO(u'a\nb\nc\n') From 7633ec9a83035d9bc543070f055840a086180d02 Mon Sep 17 00:00:00 2001 From: catdo Date: Wed, 12 May 2021 16:27:51 -0700 Subject: [PATCH 090/100] removed spacings in CMakeList and removed the tags.txt file in the prefab level --- .../Gem/PythonTests/CMakeLists.txt | 26 +++++++++---------- .../tags.txt | 12 --------- 2 files changed, 13 insertions(+), 25 deletions(-) delete mode 100644 AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/tags.txt diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 86bcb967ab..3f0827f995 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -124,19 +124,19 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) endif() ## Prefab ## - if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) - ly_add_pytest( - NAME AutomatedTesting::PrefabTests - TEST_SUITE main - TEST_SERIAL - PATH ${CMAKE_CURRENT_LIST_DIR}/prefab/TestSuite_Main.py - TIMEOUT 1500 - RUNTIME_DEPENDENCIES - Legacy::Editor - AZ::AssetProcessor - AutomatedTesting.Assets - ) - endif() +if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) + ly_add_pytest( + NAME AutomatedTesting::PrefabTests + TEST_SUITE main + TEST_SERIAL + PATH ${CMAKE_CURRENT_LIST_DIR}/prefab/TestSuite_Main.py + TIMEOUT 1500 + RUNTIME_DEPENDENCIES + Legacy::Editor + AZ::AssetProcessor + AutomatedTesting.Assets + ) +endif() ## Editor Python Bindings ## if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) diff --git a/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/tags.txt b/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/tags.txt deleted file mode 100644 index 0d6c1880e7..0000000000 --- a/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/tags.txt +++ /dev/null @@ -1,12 +0,0 @@ -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 From e7722658718b4c705b688ca88c54cb17c603b417 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 20:09:27 -0700 Subject: [PATCH 091/100] Build fixes for gem reorganization --- .../Code/Source/Debug/MultiplayerDebugSystemComponent.cpp | 2 +- .../Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp index aec8d8520e..1ae4bffd07 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp @@ -13,7 +13,7 @@ #include #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp index 4962d16fb4..805a982506 100644 --- a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp +++ b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp @@ -18,7 +18,7 @@ #include #include #include -#include +#include #include #include From eea0660d2140c1e84f63b484f2e89e87a9ec4930 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 20:26:08 -0700 Subject: [PATCH 092/100] A couple more fixes --- .../Code/Include/Multiplayer/RewindableObject.inl | 4 ++-- .../Code/Source/AutoGen/AutoComponent_Source.jinja | 4 ++-- Gems/Multiplayer/Code/multiplayer_files.cmake | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl b/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl index 2e67d42ede..20f52ffcb0 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl +++ b/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl @@ -47,7 +47,7 @@ namespace Multiplayer template inline RewindableObject &RewindableObject::operator =(const RewindableObject& rhs) { - INetworkTime* networkTime = GetNetworkTime(); + INetworkTime* networkTime = Multiplayer::GetNetworkTime(); SetValueForTime(rhs.GetValueForTime(networkTime->GetHostFrameId()), GetCurrentTimeForProperty()); return *this; } @@ -115,7 +115,7 @@ namespace Multiplayer template inline HostFrameId RewindableObject::GetCurrentTimeForProperty() const { - INetworkTime* networkTime = GetNetworkTime(); + INetworkTime* networkTime = Multiplayer::GetNetworkTime(); return networkTime->GetHostFrameIdForRewindingConnection(m_owningConnectionId); } diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 1bc6dc3994..200d38910b 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -1143,7 +1143,7 @@ namespace {{ Component.attrib['Namespace'] }} { editContext->Class<{{ ComponentBaseName }}>("{{ ComponentBaseName }}", "{{ Component.attrib['Description'] }}") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Multiplayer") + ->Attribute(AZ::Edit::Attributes::Category, "{{ Component.attrib['Namespace'] }}") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")) {{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Authority', ComponentBaseName)|indent(20) -}} {{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Server', ComponentBaseName)|indent(20) -}} @@ -1155,7 +1155,7 @@ namespace {{ Component.attrib['Namespace'] }} editContext->Class<{{ ComponentName }}>("{{ ComponentName }}", "{{ Component.attrib['Description'] }}") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Multiplayer") + ->Attribute(AZ::Edit::Attributes::Category, "{{ Component.attrib['Namespace'] }}") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")); {% endif %} } diff --git a/Gems/Multiplayer/Code/multiplayer_files.cmake b/Gems/Multiplayer/Code/multiplayer_files.cmake index bea88af10c..5eba7dd144 100644 --- a/Gems/Multiplayer/Code/multiplayer_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_files.cmake @@ -24,12 +24,12 @@ set(FILES Include/Multiplayer/MultiplayerStats.h Include/Multiplayer/MultiplayerTypes.h Include/Multiplayer/NetBindComponent.h - Include/Multiplayer/NetworkEntityRpcMessage.h + Include/Multiplayer/NetworkEntityRpcMessage.h Include/Multiplayer/NetworkEntityUpdateMessage.h Include/Multiplayer/NetworkEntityHandle.h Include/Multiplayer/NetworkEntityHandle.inl Include/Multiplayer/NetworkInput.h - Include/Multiplayer/ReplicationRecord.h + Include/Multiplayer/ReplicationRecord.h Include/Multiplayer/RewindableObject.h Include/Multiplayer/RewindableObject.inl Source/Multiplayer_precompiled.cpp @@ -48,7 +48,7 @@ set(FILES Source/Components/LocalPredictionPlayerInputComponent.h Source/Components/MultiplayerComponent.cpp Source/Components/MultiplayerController.cpp - Source/Components/MultiplayerComponentRegistry.cpp + Source/Components/MultiplayerComponentRegistry.cpp Source/Components/NetBindComponent.cpp Source/Components/NetworkTransformComponent.cpp Source/Components/NetworkTransformComponent.h From 601dd30452f9f052bf93fc48413e831259e2297d Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 20:41:53 -0700 Subject: [PATCH 093/100] Various build and test fixes --- .../Code/Include/Multiplayer/IMultiplayer.h | 14 +++++++++----- .../EntityReplication/EntityReplicationManager.cpp | 6 +++++- .../Code/Source/NetworkTime/NetworkTime.cpp | 10 ++++++++++ .../Code/Source/NetworkTime/NetworkTime.h | 4 ++-- .../Code/Tests/RewindableObjectTests.cpp | 6 +++--- 5 files changed, 29 insertions(+), 11 deletions(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h index 665661b55b..eda5b71b52 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h @@ -139,27 +139,31 @@ namespace Multiplayer inline INetworkTime* GetNetworkTime() { - return GetMultiplayer()->GetNetworkTime(); + return AZ::Interface::Get(); } inline INetworkEntityManager* GetNetworkEntityManager() { - return GetMultiplayer()->GetNetworkEntityManager(); + IMultiplayer* multiplayer = GetMultiplayer(); + return (multiplayer != nullptr) ? multiplayer->GetNetworkEntityManager() : nullptr; } inline NetworkEntityTracker* GetNetworkEntityTracker() { - return GetNetworkEntityManager()->GetNetworkEntityTracker(); + INetworkEntityManager* networkEntityManager = GetNetworkEntityManager(); + return (networkEntityManager != nullptr) ? networkEntityManager->GetNetworkEntityTracker() : nullptr; } inline NetworkEntityAuthorityTracker* GetNetworkEntityAuthorityTracker() { - return GetNetworkEntityManager()->GetNetworkEntityAuthorityTracker(); + INetworkEntityManager* networkEntityManager = GetNetworkEntityManager(); + return (networkEntityManager != nullptr) ? networkEntityManager->GetNetworkEntityAuthorityTracker() : nullptr; } inline MultiplayerComponentRegistry* GetMultiplayerComponentRegistry() { - return GetNetworkEntityManager()->GetMultiplayerComponentRegistry(); + INetworkEntityManager* networkEntityManager = GetNetworkEntityManager(); + return (networkEntityManager != nullptr) ? networkEntityManager->GetMultiplayerComponentRegistry() : nullptr; } //! @class ScopedAlterTime diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp index 6eefeaf5fe..286090ca74 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp @@ -60,7 +60,11 @@ namespace Multiplayer // Start window update events m_updateWindow.Enqueue(AZ::TimeMs{ 0 }, true); - GetNetworkEntityManager()->AddEntityExitDomainHandler(m_entityExitDomainEventHandler); + INetworkEntityManager* networkEntityManager = GetNetworkEntityManager(); + if (networkEntityManager != nullptr) + { + networkEntityManager->AddEntityExitDomainHandler(m_entityExitDomainEventHandler); + } } void EntityReplicationManager::SetRemoteHostId(HostId hostId) diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp index ab5988444b..d991e59d05 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp @@ -17,6 +17,16 @@ namespace Multiplayer { + NetworkTime::NetworkTime() + { + AZ::Interface::Register(this); + } + + NetworkTime::~NetworkTime() + { + AZ::Interface::Unregister(this); + } + bool NetworkTime::IsTimeRewound() const { return m_rewindingConnectionId != AzNetworking::InvalidConnectionId; diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h index 18adc00140..ff2da0f759 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h @@ -23,8 +23,8 @@ namespace Multiplayer : public INetworkTime { public: - NetworkTime() = default; - virtual ~NetworkTime() = default; + NetworkTime(); + virtual ~NetworkTime(); //! INetworkTime overrides. //! @{ diff --git a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp index 9f1b879856..f614dc2690 100644 --- a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp +++ b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp @@ -38,7 +38,7 @@ namespace UnitTest { test = i; EXPECT_EQ(i, test); - AZ::Interface::Get()->IncrementHostFrameId(); + Multiplayer::GetNetworkTime()->IncrementHostFrameId(); } for (uint32_t i = 0; i < 16; ++i) @@ -51,7 +51,7 @@ namespace UnitTest { test = i; EXPECT_EQ(i, test); - AZ::Interface::Get()->IncrementHostFrameId(); + Multiplayer::GetNetworkTime()->IncrementHostFrameId(); } for (uint32_t i = 16; i < 48; ++i) @@ -69,7 +69,7 @@ namespace UnitTest { test = i; EXPECT_EQ(i, test); - AZ::Interface::Get()->IncrementHostFrameId(); + Multiplayer::GetNetworkTime()->IncrementHostFrameId(); } { From cb8016bde5f7c63c3054b4992705b9011fce502e Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 20:52:02 -0700 Subject: [PATCH 094/100] Fix for validator failing on empty files --- .../Multiplayer/INetworkPlayerSpawner.h | 18 ++++++++++++++++++ .../Code/Source/MultiplayerSystemComponent.cpp | 2 +- Gems/Multiplayer/Code/multiplayer_files.cmake | 1 + 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h index e69de29bb2..f50d60e82d 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h @@ -0,0 +1,18 @@ +/* +* 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 + +namespace Multiplayer +{ + +} diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 715d9a8527..80a09d7d48 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -433,7 +433,7 @@ namespace Multiplayer if (m_onConnectFunctor) { - // Default OnConnect behaviour has been overridden, + // Default OnConnect behaviour has been overridden m_onConnectFunctor(connection, datum); } else diff --git a/Gems/Multiplayer/Code/multiplayer_files.cmake b/Gems/Multiplayer/Code/multiplayer_files.cmake index 5eba7dd144..26909cbfd3 100644 --- a/Gems/Multiplayer/Code/multiplayer_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_files.cmake @@ -15,6 +15,7 @@ set(FILES Include/Multiplayer/IMultiplayer.h Include/Multiplayer/IMultiplayerComponentInput.h Include/Multiplayer/INetworkEntityManager.h + Include/Multiplayer/INetworkPlayerSpawner.h Include/Multiplayer/INetworkTime.h Include/Multiplayer/IReplicationWindow.h Include/Multiplayer/MultiplayerComponent.h From c0d9a3c423b61747656842a931f9c127dceba8d7 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 20:55:03 -0700 Subject: [PATCH 095/100] Fix for clang not being lazy about template expansion --- Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h | 5 ----- Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h | 6 ++++++ 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h index eda5b71b52..4931fb167f 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h @@ -137,11 +137,6 @@ namespace Multiplayer return AZ::Interface::Get(); } - inline INetworkTime* GetNetworkTime() - { - return AZ::Interface::Get(); - } - inline INetworkEntityManager* GetNetworkEntityManager() { IMultiplayer* multiplayer = GetMultiplayer(); diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h index c228e135ee..240eed270a 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h @@ -83,4 +83,10 @@ namespace Multiplayer static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; }; using INetworkTimeRequestBus = AZ::EBus; + + // Convenience helpers + inline INetworkTime* GetNetworkTime() + { + return AZ::Interface::Get(); + } } From d690c3fee4810a49da588a71da4a95ab603918c9 Mon Sep 17 00:00:00 2001 From: amzn-sean <75276488+amzn-sean@users.noreply.github.com> Date: Thu, 13 May 2021 11:59:22 +0100 Subject: [PATCH 096/100] static rigid body and rigid body component use Handles instead of pointers (#662) --- .../Configuration/RigidBodyConfiguration.cpp | 8 +- .../Configuration/RigidBodyConfiguration.h | 1 - .../Physics/SimulatedBodies/RigidBody.h | 2 +- .../Code/Source/Family/BlastFamilyImpl.cpp | 2 +- Gems/Blast/Code/Tests/Mocks/BlastMocks.h | 2 +- .../Code/Source/EditorRigidBodyComponent.cpp | 98 +++--- .../Code/Source/EditorRigidBodyComponent.h | 7 +- Gems/PhysX/Code/Source/RigidBody.cpp | 8 +- Gems/PhysX/Code/Source/RigidBody.h | 2 +- Gems/PhysX/Code/Source/RigidBodyComponent.cpp | 278 ++++++++++++++---- Gems/PhysX/Code/Source/RigidBodyComponent.h | 3 +- Gems/PhysX/Code/Source/Scene/PhysXScene.cpp | 18 +- .../Code/Source/StaticRigidBodyComponent.cpp | 42 ++- .../Code/Source/StaticRigidBodyComponent.h | 1 - Gems/PhysX/Code/Source/System/PhysXSystem.cpp | 3 + Gems/PhysX/Code/Tests/PhysXTestCommon.cpp | 12 + 16 files changed, 358 insertions(+), 129 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.cpp b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.cpp index 80434e5dee..0d5d5ca841 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.cpp +++ b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.cpp @@ -99,6 +99,11 @@ namespace AzPhysics classElement.RemoveElementByName(AZ_CRC_CE("Property Visibility Flags")); } + if (classElement.GetVersion() <= 4) + { + classElement.RemoveElementByName(AZ_CRC_CE("Simulated")); + } + return true; } } @@ -110,7 +115,7 @@ namespace AzPhysics if (auto serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(4, &Internal::RigidBodyVersionConverter) + ->Version(5, &Internal::RigidBodyVersionConverter) ->Field("Initial linear velocity", &RigidBodyConfiguration::m_initialLinearVelocity) ->Field("Initial angular velocity", &RigidBodyConfiguration::m_initialAngularVelocity) ->Field("Linear damping", &RigidBodyConfiguration::m_linearDamping) @@ -119,7 +124,6 @@ namespace AzPhysics ->Field("Start Asleep", &RigidBodyConfiguration::m_startAsleep) ->Field("Interpolate Motion", &RigidBodyConfiguration::m_interpolateMotion) ->Field("Gravity Enabled", &RigidBodyConfiguration::m_gravityEnabled) - ->Field("Simulated", &RigidBodyConfiguration::m_simulated) ->Field("Kinematic", &RigidBodyConfiguration::m_kinematic) ->Field("CCD Enabled", &RigidBodyConfiguration::m_ccdEnabled) ->Field("Compute Mass", &RigidBodyConfiguration::m_computeMass) diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.h b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.h index 5c43118f3d..ecf7e023c5 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.h @@ -57,7 +57,6 @@ namespace AzPhysics bool m_startAsleep = false; bool m_interpolateMotion = false; bool m_gravityEnabled = true; - bool m_simulated = true; bool m_kinematic = false; bool m_ccdEnabled = false; //!< Whether continuous collision detection is enabled. float m_ccdMinAdvanceCoefficient = 0.15f; //!< Coefficient affecting how granularly time is subdivided in CCD. diff --git a/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/RigidBody.h b/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/RigidBody.h index 5b18887d43..0f43aaaf4a 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/RigidBody.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/RigidBody.h @@ -62,7 +62,7 @@ namespace AzPhysics virtual void SetLinearVelocity(const AZ::Vector3& velocity) = 0; virtual AZ::Vector3 GetAngularVelocity() const = 0; virtual void SetAngularVelocity(const AZ::Vector3& angularVelocity) = 0; - virtual AZ::Vector3 GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) = 0; + virtual AZ::Vector3 GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) const = 0; virtual void ApplyLinearImpulse(const AZ::Vector3& impulse) = 0; virtual void ApplyLinearImpulseAtWorldPoint(const AZ::Vector3& impulse, const AZ::Vector3& worldPoint) = 0; virtual void ApplyAngularImpulse(const AZ::Vector3& angularImpulse) = 0; diff --git a/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp b/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp index d276486548..87865d0e08 100644 --- a/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp +++ b/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp @@ -241,7 +241,7 @@ namespace Blast configuration.m_orientation = transform.GetRotation(); configuration.m_scale = transform.GetScale(); configuration.m_ccdEnabled = m_actorConfiguration.m_isCcdEnabled; - configuration.m_simulated = m_actorConfiguration.m_isSimulated; + configuration.m_startSimulationEnabled = m_actorConfiguration.m_isSimulated; configuration.m_initialAngularVelocity = AZ::Vector3::CreateZero(); BlastActorDesc actorDesc; diff --git a/Gems/Blast/Code/Tests/Mocks/BlastMocks.h b/Gems/Blast/Code/Tests/Mocks/BlastMocks.h index a1e57a6917..1ae87e2282 100644 --- a/Gems/Blast/Code/Tests/Mocks/BlastMocks.h +++ b/Gems/Blast/Code/Tests/Mocks/BlastMocks.h @@ -424,7 +424,7 @@ namespace Blast void SetAngularVelocity([[maybe_unused]] const AZ::Vector3& angularVelocity) override {} - AZ::Vector3 GetLinearVelocityAtWorldPoint([[maybe_unused]] const AZ::Vector3& worldPoint) override + AZ::Vector3 GetLinearVelocityAtWorldPoint([[maybe_unused]] const AZ::Vector3& worldPoint) const override { return {}; } diff --git a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp index b6517b0499..f97e7c6cbd 100644 --- a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp @@ -282,9 +282,8 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { - sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_rigidBodyHandle); - m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - m_editorBody = nullptr; + sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorRigidBodyHandle); + m_editorRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } @@ -342,12 +341,15 @@ namespace PhysX [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - if (m_editorBody && m_config.m_centerOfMassDebugDraw) + if (m_config.m_centerOfMassDebugDraw) { - debugDisplay.DepthTestOff(); - debugDisplay.SetColor(m_centerOfMassDebugColor); - debugDisplay.DrawBall(m_editorBody->GetCenterOfMassWorld(), m_centerOfMassDebugSize); - debugDisplay.DepthTestOn(); + if (const AzPhysics::RigidBody* body = GetRigidBody()) + { + debugDisplay.DepthTestOff(); + debugDisplay.SetColor(m_centerOfMassDebugColor); + debugDisplay.DrawBall(body->GetCenterOfMassWorld(), m_centerOfMassDebugSize); + debugDisplay.DepthTestOn(); + } } } @@ -366,29 +368,30 @@ namespace PhysX AZ::Transform colliderTransform = GetWorldTM(); colliderTransform.ExtractScale(); - AzPhysics::RigidBodyConfiguration configuration; + AzPhysics::RigidBodyConfiguration configuration = m_config; configuration.m_orientation = colliderTransform.GetRotation(); configuration.m_position = colliderTransform.GetTranslation(); configuration.m_entityId = GetEntityId(); configuration.m_debugName = GetEntity()->GetName(); - configuration.m_centerOfMassOffset = m_config.m_centerOfMassOffset; - configuration.m_computeCenterOfMass = m_config.m_computeCenterOfMass; - configuration.m_computeInertiaTensor = m_config.m_computeInertiaTensor; - configuration.m_inertiaTensor = m_config.m_inertiaTensor; - configuration.m_simulated = false; - configuration.m_kinematic = m_config.m_kinematic; + configuration.m_startSimulationEnabled = false; configuration.m_colliderAndShapeData = Internal::GetCollisionShapes(GetEntity()); + if (auto* sceneInterface = AZ::Interface::Get()) { - m_rigidBodyHandle = sceneInterface->AddSimulatedBody(m_editorSceneHandle, &configuration); - m_editorBody = azdynamic_cast(sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_rigidBodyHandle)); + m_editorRigidBodyHandle = sceneInterface->AddSimulatedBody(m_editorSceneHandle, &configuration); + if (auto* body = azdynamic_cast( + sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorRigidBodyHandle) + )) + { + // AddSimulatedBody may update mass / CoM / Inertia tensor based on the config, so grab the updated values. + m_config.m_mass = body->GetMass(); + m_config.m_centerOfMassOffset = body->GetCenterOfMassLocal(); + m_config.m_inertiaTensor = body->GetInverseInertiaLocal(); + } } - - m_editorBody->UpdateMassProperties(m_config.GetMassComputeFlags(), &m_config.m_centerOfMassOffset, &m_config.m_inertiaTensor, &m_config.m_mass); - m_config.m_mass = m_editorBody->GetMass(); - m_config.m_centerOfMassOffset = m_editorBody->GetCenterOfMassLocal(); - m_config.m_inertiaTensor = m_editorBody->GetInverseInertiaLocal(); + AZ_Error("EditorRigidBodyComponent", + m_editorRigidBodyHandle != AzPhysics::InvalidSimulatedBodyHandle, "Failed to create editor rigid body"); } void EditorRigidBodyComponent::OnColliderChanged() @@ -424,9 +427,8 @@ namespace PhysX { if (auto* sceneInterface = AZ::Interface::Get()) { - sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_rigidBodyHandle); - m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - m_editorBody = nullptr; + sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorRigidBodyHandle); + m_editorRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; CreateEditorWorldRigidBody(); } @@ -436,46 +438,65 @@ namespace PhysX void EditorRigidBodyComponent::EnablePhysics() { - if (!IsPhysicsEnabled()) + if (auto* sceneInterface = AZ::Interface::Get()) { - m_editorBody->SetSimulationEnabled(true); + sceneInterface->EnableSimulationOfBody(m_editorSceneHandle, m_editorRigidBodyHandle); } } void EditorRigidBodyComponent::DisablePhysics() { - m_editorBody->SetSimulationEnabled(false); + if (auto* sceneInterface = AZ::Interface::Get()) + { + sceneInterface->DisableSimulationOfBody(m_editorSceneHandle, m_editorRigidBodyHandle); + } } bool EditorRigidBodyComponent::IsPhysicsEnabled() const { - return m_editorBody && m_editorBody->m_simulating; + if (auto* sceneInterface = AZ::Interface::Get()) + { + if (AzPhysics::SimulatedBody* body = + sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorRigidBodyHandle)) + { + return body->m_simulating; + } + } + return false; } AZ::Aabb EditorRigidBodyComponent::GetAabb() const { - if (m_editorBody) + if (auto* sceneInterface = AZ::Interface::Get()) { - return m_editorBody->GetAabb(); + if (AzPhysics::SimulatedBody* body = + sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorRigidBodyHandle)) + { + return body->GetAabb(); + } } return AZ::Aabb::CreateNull(); } AzPhysics::SimulatedBody* EditorRigidBodyComponent::GetSimulatedBody() { - return m_editorBody; + if (auto* sceneInterface = AZ::Interface::Get()) + { + return sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorRigidBodyHandle); + } + return nullptr; } AzPhysics::SimulatedBodyHandle EditorRigidBodyComponent::GetSimulatedBodyHandle() const { - return m_rigidBodyHandle; + return m_editorRigidBodyHandle; } AzPhysics::SceneQueryHit EditorRigidBodyComponent::RayCast(const AzPhysics::RayCastRequest& request) { - if (m_editorBody) + if (AzPhysics::SimulatedBody* body = GetSimulatedBody()) { - return m_editorBody->RayCast(request); + return body->RayCast(request); } return AzPhysics::SceneQueryHit(); } @@ -488,7 +509,12 @@ namespace PhysX const AzPhysics::RigidBody* EditorRigidBodyComponent::GetRigidBody() const { - return m_editorBody; + if (auto* sceneInterface = AZ::Interface::Get()) + { + return azdynamic_cast( + sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorRigidBodyHandle)); + } + return nullptr; } void EditorRigidBodyComponent::SetShouldBeRecreated() diff --git a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.h b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.h index b2b199e6be..72d34bb0d0 100644 --- a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.h +++ b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.h @@ -33,8 +33,8 @@ namespace PhysX struct EditorRigidBodyConfiguration : public AzPhysics::RigidBodyConfiguration { - AZ_CLASS_ALLOCATOR(EditorRigidBodyConfiguration, AZ::SystemAllocator, 0); - AZ_RTTI(EditorRigidBodyConfiguration, "{27297024-5A99-4C58-8614-4EF18137CE69}", AzPhysics::RigidBodyConfiguration); + AZ_CLASS_ALLOCATOR(PhysX::EditorRigidBodyConfiguration, AZ::SystemAllocator, 0); + AZ_RTTI(PhysX::EditorRigidBodyConfiguration, "{27297024-5A99-4C58-8614-4EF18137CE69}", AzPhysics::RigidBodyConfiguration); static void Reflect(AZ::ReflectContext* context); @@ -127,8 +127,7 @@ namespace PhysX Debug::DebugDisplayDataChangedEvent::Handler m_debugDisplayDataChangeHandler; EditorRigidBodyConfiguration m_config; - AzPhysics::SimulatedBodyHandle m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - AzPhysics::RigidBody* m_editorBody = nullptr; + AzPhysics::SimulatedBodyHandle m_editorRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; AzPhysics::SceneHandle m_editorSceneHandle = AzPhysics::InvalidSceneHandle; AZ::Color m_centerOfMassDebugColor = AZ::Colors::White; diff --git a/Gems/PhysX/Code/Source/RigidBody.cpp b/Gems/PhysX/Code/Source/RigidBody.cpp index 6d1ece6a82..7fda0a1912 100644 --- a/Gems/PhysX/Code/Source/RigidBody.cpp +++ b/Gems/PhysX/Code/Source/RigidBody.cpp @@ -82,12 +82,8 @@ namespace PhysX SetName(configuration.m_debugName); SetGravityEnabled(configuration.m_gravityEnabled); - SetSimulationEnabled(configuration.m_simulated); SetCCDEnabled(configuration.m_ccdEnabled); - - AzPhysics::MassComputeFlags flags = configuration.GetMassComputeFlags(); - UpdateMassProperties(flags, &configuration.m_centerOfMassOffset, &configuration.m_inertiaTensor, - &configuration.m_mass); + SetKinematic(configuration.m_kinematic); if (configuration.m_customUserData) { @@ -459,7 +455,7 @@ namespace PhysX } } - AZ::Vector3 RigidBody::GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) + AZ::Vector3 RigidBody::GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) const { return m_pxRigidActor ? GetLinearVelocity() + GetAngularVelocity().Cross(worldPoint - GetCenterOfMassWorld()) : diff --git a/Gems/PhysX/Code/Source/RigidBody.h b/Gems/PhysX/Code/Source/RigidBody.h index c9f171b261..07df60d649 100644 --- a/Gems/PhysX/Code/Source/RigidBody.h +++ b/Gems/PhysX/Code/Source/RigidBody.h @@ -63,7 +63,7 @@ namespace PhysX void SetLinearVelocity(const AZ::Vector3& velocity) override; AZ::Vector3 GetAngularVelocity() const override; void SetAngularVelocity(const AZ::Vector3& angularVelocity) override; - AZ::Vector3 GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) override; + AZ::Vector3 GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) const override; void ApplyLinearImpulse(const AZ::Vector3& impulse) override; void ApplyLinearImpulseAtWorldPoint(const AZ::Vector3& impulse, const AZ::Vector3& worldPoint) override; void ApplyAngularImpulse(const AZ::Vector3& angularImpulse) override; diff --git a/Gems/PhysX/Code/Source/RigidBodyComponent.cpp b/Gems/PhysX/Code/Source/RigidBodyComponent.cpp index cf2e306cc7..58b0749d0f 100644 --- a/Gems/PhysX/Code/Source/RigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/RigidBodyComponent.cpp @@ -185,7 +185,6 @@ namespace PhysX { sceneInterface->RemoveSimulatedBody(m_attachedSceneHandle, m_rigidBodyHandle); m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - m_rigidBody = nullptr; } Physics::RigidBodyRequestBus::Handler::BusDisconnect(); @@ -232,20 +231,33 @@ namespace PhysX // User sets kinematic Target ---> Update transform // User sets transform ---> Update kinematic target - if (!IsPhysicsEnabled() || (m_rigidBody->IsKinematic() && !m_isLastMovementFromKinematicSource)) + if (!IsPhysicsEnabled() || (IsKinematic() && !m_isLastMovementFromKinematicSource)) { return; } + auto* sceneInterface = AZ::Interface::Get(); + if (sceneInterface == nullptr) + { + AZ_Error("RigidBodyComponent", false, "PostPhysicsTick, SceneInterface is null"); + return; + } + + AzPhysics::SimulatedBody* rigidBody = + sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_rigidBodyHandle); + if (rigidBody == nullptr) + { + AZ_Error("RigidBodyComponent", false, "Unable to retrieve simulated rigid body"); + return; + } + + AZ::Transform transform = rigidBody->GetTransform(); if (m_configuration.m_interpolateMotion) { - AZ::Transform transform = m_rigidBody->GetTransform(); - m_interpolator->SetTarget(transform.GetTranslation(), m_rigidBody->GetOrientation(), fixedDeltaTime); + m_interpolator->SetTarget(transform.GetTranslation(), rigidBody->GetOrientation(), fixedDeltaTime); } else { - AZ::Transform transform = m_rigidBody->GetTransform(); - // Maintain scale (this must be precise). AZ::Transform entityTransform = AZ::Transform::Identity(); AZ::TransformBus::EventResult(entityTransform, GetEntityId(), &AZ::TransformInterface::GetWorldTM); @@ -261,13 +273,17 @@ namespace PhysX // Note: OnTransformChanged is not safe at the moment due to TransformComponent design flaw. // It is called when the parent entity is activated after the children causing rigid body // to move through the level instantly. - if (IsPhysicsEnabled() && (m_rigidBody->IsKinematic() && !m_isLastMovementFromKinematicSource)) + if (AzPhysics::RigidBody* body = GetRigidBody()) { - m_rigidBody->SetKinematicTarget(world); - } - else if (!IsPhysicsEnabled()) - { - m_rigidBodyTransformNeedsUpdateOnPhysReEnable = true; + if (body->m_simulating && + (body->IsKinematic() && !m_isLastMovementFromKinematicSource)) + { + body->SetKinematicTarget(world); + } + else if (!body->m_simulating) + { + m_rigidBodyTransformNeedsUpdateOnPhysReEnable = true; + } } } @@ -290,16 +306,9 @@ namespace PhysX auto* sceneInterface = AZ::Interface::Get(); if (sceneInterface != nullptr) { + m_configuration.m_startSimulationEnabled = false; //enable physics will enable this when called. m_rigidBodyHandle = sceneInterface->AddSimulatedBody(m_attachedSceneHandle, &m_configuration); - m_rigidBody = azdynamic_cast(sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_rigidBodyHandle)); - //disable simulating the body until EnablePhysics is called. - sceneInterface->DisableSimulationOfBody(m_attachedSceneHandle, m_rigidBodyHandle); } - m_rigidBody->SetKinematic(m_configuration.m_kinematic); - - AzPhysics::MassComputeFlags flags = m_configuration.GetMassComputeFlags(); - m_rigidBody->UpdateMassProperties(flags, &m_configuration.m_centerOfMassOffset, &m_configuration.m_inertiaTensor, - &m_configuration.m_mass); // Listen to the PhysX system for events concerning this entity. if (sceneInterface != nullptr) @@ -319,16 +328,23 @@ namespace PhysX return; } - if (auto* sceneInterface = AZ::Interface::Get()) + auto* sceneInterface = AZ::Interface::Get(); + if (sceneInterface == nullptr) { - sceneInterface->EnableSimulationOfBody(m_attachedSceneHandle, m_rigidBodyHandle); + AZ_Error("RigidBodyComponent", false, "Unable to enable physics, SceneInterface is null"); + return; } + SetSimulationEnabled(true); AZ::Transform transform = AZ::Transform::CreateIdentity(); AZ::TransformBus::EventResult(transform, GetEntityId(), &AZ::TransformInterface::GetWorldTM); if (m_rigidBodyTransformNeedsUpdateOnPhysReEnable) { - m_rigidBody->SetTransform(transform); + if (AzPhysics::SimulatedBody* body = + sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_rigidBodyHandle)) + { + body->SetTransform(transform); + } m_rigidBodyTransformNeedsUpdateOnPhysReEnable = false; } @@ -345,188 +361,322 @@ namespace PhysX void RigidBodyComponent::DisablePhysics() { - if (auto* sceneInterface = AZ::Interface::Get()) - { - sceneInterface->DisableSimulationOfBody(m_attachedSceneHandle, m_rigidBodyHandle); - } + SetSimulationEnabled(false); Physics::RigidBodyNotificationBus::Event(GetEntityId(), &Physics::RigidBodyNotificationBus::Events::OnPhysicsDisabled); } bool RigidBodyComponent::IsPhysicsEnabled() const { - return m_rigidBody != nullptr && m_rigidBody->m_simulating; + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->m_simulating; + } + return false; } void RigidBodyComponent::ApplyLinearImpulse(const AZ::Vector3& impulse) { - m_rigidBody->ApplyLinearImpulse(impulse); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->ApplyLinearImpulse(impulse); + } } void RigidBodyComponent::ApplyLinearImpulseAtWorldPoint(const AZ::Vector3& impulse, const AZ::Vector3& worldSpacePoint) { - m_rigidBody->ApplyLinearImpulseAtWorldPoint(impulse, worldSpacePoint); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->ApplyLinearImpulseAtWorldPoint(impulse, worldSpacePoint); + } } void RigidBodyComponent::ApplyAngularImpulse(const AZ::Vector3& impulse) { - m_rigidBody->ApplyAngularImpulse(impulse); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->ApplyAngularImpulse(impulse); + } } AZ::Vector3 RigidBodyComponent::GetLinearVelocity() const { - return m_rigidBody->GetLinearVelocity(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetLinearVelocity(); + } + return AZ::Vector3::CreateZero(); } void RigidBodyComponent::SetLinearVelocity(const AZ::Vector3& velocity) { - m_rigidBody->SetLinearVelocity(velocity); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetLinearVelocity(velocity); + } } AZ::Vector3 RigidBodyComponent::GetAngularVelocity() const { - return m_rigidBody->GetAngularVelocity(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetAngularVelocity(); + } + return AZ::Vector3::CreateZero(); } void RigidBodyComponent::SetAngularVelocity(const AZ::Vector3& angularVelocity) { - m_rigidBody->SetAngularVelocity(angularVelocity); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetAngularVelocity(angularVelocity); + } } AZ::Vector3 RigidBodyComponent::GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) const { - return m_rigidBody->GetLinearVelocityAtWorldPoint(worldPoint); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetLinearVelocityAtWorldPoint(worldPoint); + } + return AZ::Vector3::CreateZero(); } AZ::Vector3 RigidBodyComponent::GetCenterOfMassWorld() const { - return m_rigidBody->GetCenterOfMassWorld(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetCenterOfMassWorld(); + } + return AZ::Vector3::CreateZero(); } AZ::Vector3 RigidBodyComponent::GetCenterOfMassLocal() const { - return m_rigidBody->GetCenterOfMassLocal(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetCenterOfMassLocal(); + } + return AZ::Vector3::CreateZero(); } AZ::Matrix3x3 RigidBodyComponent::GetInverseInertiaWorld() const { - return m_rigidBody->GetInverseInertiaWorld(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetInverseInertiaWorld(); + } + return AZ::Matrix3x3::CreateZero(); } AZ::Matrix3x3 RigidBodyComponent::GetInverseInertiaLocal() const { - return m_rigidBody->GetInverseInertiaLocal(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetInverseInertiaLocal(); + } + return AZ::Matrix3x3::CreateZero(); } float RigidBodyComponent::GetMass() const { - return m_rigidBody->GetMass(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetMass(); + } + return 0.0f; } float RigidBodyComponent::GetInverseMass() const { - return m_rigidBody->GetInverseMass(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetInverseMass(); + } + return 0.0f; } void RigidBodyComponent::SetMass(float mass) { - m_rigidBody->SetMass(mass); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetMass(mass); + } } void RigidBodyComponent::SetCenterOfMassOffset(const AZ::Vector3& comOffset) { - m_rigidBody->SetCenterOfMassOffset(comOffset); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetCenterOfMassOffset(comOffset); + } } float RigidBodyComponent::GetLinearDamping() const { - return m_rigidBody->GetLinearDamping(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetLinearDamping(); + } + return 0.0f; } void RigidBodyComponent::SetLinearDamping(float damping) { - m_rigidBody->SetLinearDamping(damping); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetLinearDamping(damping); + } } float RigidBodyComponent::GetAngularDamping() const { - return m_rigidBody->GetAngularDamping(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetAngularDamping(); + } + return 0.0f; } void RigidBodyComponent::SetAngularDamping(float damping) { - m_rigidBody->SetAngularDamping(damping); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetAngularDamping(damping); + } } bool RigidBodyComponent::IsAwake() const { - return m_rigidBody->IsAwake(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->IsAwake(); + } + return false; } void RigidBodyComponent::ForceAsleep() { - m_rigidBody->ForceAsleep(); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->ForceAsleep(); + } } void RigidBodyComponent::ForceAwake() { - m_rigidBody->ForceAwake(); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->ForceAwake(); + } } bool RigidBodyComponent::IsKinematic() const { - return m_rigidBody->IsKinematic(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->IsKinematic(); + } + return false; } void RigidBodyComponent::SetKinematic(bool kinematic) { - m_rigidBody->SetKinematic(kinematic); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetKinematic(kinematic); + } } void RigidBodyComponent::SetKinematicTarget(const AZ::Transform& targetPosition) { m_isLastMovementFromKinematicSource = true; - m_rigidBody->SetKinematicTarget(targetPosition); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetKinematicTarget(targetPosition); + } } bool RigidBodyComponent::IsGravityEnabled() const { - return m_rigidBody->IsGravityEnabled(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->IsGravityEnabled(); + } + return false; } void RigidBodyComponent::SetGravityEnabled(bool enabled) { - m_rigidBody->SetGravityEnabled(enabled); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetGravityEnabled(enabled); + } } void RigidBodyComponent::SetSimulationEnabled(bool enabled) { - m_rigidBody->SetSimulationEnabled(enabled); + if (auto* sceneInterface = AZ::Interface::Get()) + { + if (enabled) + { + sceneInterface->EnableSimulationOfBody(m_attachedSceneHandle, m_rigidBodyHandle); + } + else + { + sceneInterface->DisableSimulationOfBody(m_attachedSceneHandle, m_rigidBodyHandle); + } + } } float RigidBodyComponent::GetSleepThreshold() const { - return m_rigidBody->GetSleepThreshold(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetSleepThreshold(); + } + return 0.0f; } void RigidBodyComponent::SetSleepThreshold(float threshold) { - m_rigidBody->SetSleepThreshold(threshold); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetSleepThreshold(threshold); + } } AZ::Aabb RigidBodyComponent::GetAabb() const { - return m_rigidBody->GetAabb(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetAabb(); + } + return AZ::Aabb::CreateNull(); } AzPhysics::RigidBody* RigidBodyComponent::GetRigidBody() { - return m_rigidBody; + return azdynamic_cast(GetSimulatedBody()); } AzPhysics::SimulatedBody* RigidBodyComponent::GetSimulatedBody() { - return m_rigidBody; + if (auto* sceneInterface = AZ::Interface::Get()) + { + return sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_rigidBodyHandle); + } + return nullptr; + } + + const AzPhysics::RigidBody* RigidBodyComponent::GetRigidBodyConst() const + { + if (auto* sceneInterface = AZ::Interface::Get()) + { + return azdynamic_cast( + sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_rigidBodyHandle)); + } + return nullptr; } AzPhysics::SimulatedBodyHandle RigidBodyComponent::GetSimulatedBodyHandle() const @@ -536,9 +686,9 @@ namespace PhysX AzPhysics::SceneQueryHit RigidBodyComponent::RayCast(const AzPhysics::RayCastRequest& request) { - if (m_rigidBody) + if (AzPhysics::RigidBody* body = GetRigidBody()) { - return m_rigidBody->RayCast(request); + return body->RayCast(request); } return AzPhysics::SceneQueryHit(); } diff --git a/Gems/PhysX/Code/Source/RigidBodyComponent.h b/Gems/PhysX/Code/Source/RigidBodyComponent.h index 12c4d3f5ff..7b2a34cf37 100644 --- a/Gems/PhysX/Code/Source/RigidBodyComponent.h +++ b/Gems/PhysX/Code/Source/RigidBodyComponent.h @@ -153,11 +153,12 @@ namespace PhysX void InitPhysicsTickHandler(); void PostPhysicsTick(float fixedDeltaTime); + const AzPhysics::RigidBody* GetRigidBodyConst() const; + std::unique_ptr m_interpolator; AzPhysics::RigidBodyConfiguration m_configuration; AzPhysics::SimulatedBodyHandle m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - AzPhysics::RigidBody* m_rigidBody = nullptr; AzPhysics::SceneHandle m_attachedSceneHandle = AzPhysics::InvalidSceneHandle; AZ::Vector3 m_initialScale = AZ::Vector3::CreateOne(); diff --git a/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp b/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp index 03bbac9fd4..96e2d8a9bb 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp +++ b/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp @@ -189,6 +189,22 @@ namespace PhysX return newBody; } + AzPhysics::SimulatedBody* CreateRigidBody(const AzPhysics::RigidBodyConfiguration* configuration, AZ::Crc32& crc) + { + RigidBody* newBody = aznew RigidBody(*configuration); + if (!AZStd::holds_alternative(configuration->m_colliderAndShapeData)) + { + const bool shapeAdded = AddShape(newBody, configuration->m_colliderAndShapeData); + AZ_Warning("PhysXScene", shapeAdded, "No Collider or Shape information found when creating Rigid body [%s]", configuration->m_debugName.c_str()); + } + const AzPhysics::MassComputeFlags& flags = configuration->GetMassComputeFlags(); + newBody->UpdateMassProperties(flags, &configuration->m_centerOfMassOffset, + &configuration->m_inertiaTensor, &configuration->m_mass); + + crc = AZ::Crc32(newBody, sizeof(*newBody)); + return newBody; + } + AzPhysics::SimulatedBody* CreateCharacterBody(PhysXScene* scene, const Physics::CharacterConfiguration* characterConfig) { @@ -617,7 +633,7 @@ namespace PhysX AZ::Crc32 newBodyCrc; if (azrtti_istypeof(simulatedBodyConfig)) { - newBody = Internal::CreateSimulatedBody( + newBody = Internal::CreateRigidBody( azdynamic_cast(simulatedBodyConfig), newBodyCrc); } else if (azrtti_istypeof(simulatedBodyConfig)) diff --git a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp index 79e5ea8204..881fb29750 100644 --- a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp @@ -100,7 +100,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { m_staticRigidBodyHandle = sceneInterface->AddSimulatedBody(m_attachedSceneHandle, &configuration); - m_staticRigidBody = azdynamic_cast(sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_staticRigidBodyHandle)); } } @@ -119,16 +118,18 @@ namespace PhysX { sceneInterface->RemoveSimulatedBody(m_attachedSceneHandle, m_staticRigidBodyHandle); m_staticRigidBodyHandle = AzPhysics::InvalidSceneHandle; - m_staticRigidBody = nullptr; } AzPhysics::SimulatedBodyComponentRequestsBus::Handler::BusDisconnect(); AZ::TransformNotificationBus::Handler::BusDisconnect(); } - void StaticRigidBodyComponent::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world) + void StaticRigidBodyComponent::OnTransformChanged([[maybe_unused]] const AZ::Transform& local, const AZ::Transform& world) { - m_staticRigidBody->SetTransform(world); + if (AzPhysics::SimulatedBody* body = GetSimulatedBody()) + { + body->SetTransform(world); + } } void StaticRigidBodyComponent::EnablePhysics() @@ -153,12 +154,31 @@ namespace PhysX bool StaticRigidBodyComponent::IsPhysicsEnabled() const { - return m_staticRigidBody != nullptr && m_staticRigidBody->m_simulating; + if (m_staticRigidBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) + { + if (auto* sceneInterface = AZ::Interface::Get(); + sceneInterface != nullptr && + sceneInterface->IsEnabled(m_attachedSceneHandle))//check if the scene is enabled + { + if (AzPhysics::SimulatedBody* body = sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_staticRigidBodyHandle)) + { + return body->m_simulating; + } + } + } + return false; } AZ::Aabb StaticRigidBodyComponent::GetAabb() const { - return m_staticRigidBody->GetAabb(); + if (auto* sceneInterface = AZ::Interface::Get()) + { + if (AzPhysics::SimulatedBody* body = sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_staticRigidBodyHandle)) + { + return body->GetAabb(); + } + } + return AZ::Aabb::CreateNull(); } AzPhysics::SimulatedBodyHandle StaticRigidBodyComponent::GetSimulatedBodyHandle() const @@ -168,14 +188,18 @@ namespace PhysX AzPhysics::SimulatedBody* StaticRigidBodyComponent::GetSimulatedBody() { - return m_staticRigidBody; + if (auto* sceneInterface = AZ::Interface::Get()) + { + return sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_staticRigidBodyHandle); + } + return nullptr; } AzPhysics::SceneQueryHit StaticRigidBodyComponent::RayCast(const AzPhysics::RayCastRequest& request) { - if (m_staticRigidBody) + if (auto* body = azdynamic_cast(GetSimulatedBody())) { - return m_staticRigidBody->RayCast(request); + return body->RayCast(request); } return AzPhysics::SceneQueryHit(); } diff --git a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.h b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.h index 660521ab7a..0f5bf1a4b2 100644 --- a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.h +++ b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.h @@ -65,7 +65,6 @@ namespace PhysX void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; AzPhysics::SimulatedBodyHandle m_staticRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - PhysX::StaticRigidBody* m_staticRigidBody = nullptr; AzPhysics::SceneHandle m_attachedSceneHandle = AzPhysics::InvalidSceneHandle; }; } // namespace PhysX diff --git a/Gems/PhysX/Code/Source/System/PhysXSystem.cpp b/Gems/PhysX/Code/Source/System/PhysXSystem.cpp index 1d925570c5..1622d04aae 100644 --- a/Gems/PhysX/Code/Source/System/PhysXSystem.cpp +++ b/Gems/PhysX/Code/Source/System/PhysXSystem.cpp @@ -140,6 +140,9 @@ namespace PhysX } }; + AZ_Warning("PhysXSystem", deltaTime <= m_systemConfig.m_maxTimestep, + "Frame delta time of [%.6f seconds] exceeds Physics max frame timestep, physics timestep will be clamped to [%.6f seconds].", + deltaTime, m_systemConfig.m_maxTimestep); deltaTime = AZ::GetClamp(deltaTime, 0.0f, m_systemConfig.m_maxTimestep); AZ_Assert(m_systemConfig.m_fixedTimestep >= 0.0f, "PhysXSystem - fixed timestep is negitive."); diff --git a/Gems/PhysX/Code/Tests/PhysXTestCommon.cpp b/Gems/PhysX/Code/Tests/PhysXTestCommon.cpp index 2404a60e0d..93ad7704c9 100644 --- a/Gems/PhysX/Code/Tests/PhysXTestCommon.cpp +++ b/Gems/PhysX/Code/Tests/PhysXTestCommon.cpp @@ -415,6 +415,10 @@ namespace PhysX Physics::SphereShapeConfiguration shapeConfiguration; shapeConfiguration.m_radius = radius; AzPhysics::RigidBodyConfiguration rigidBodySettings; + rigidBodySettings.m_computeMass = false; + rigidBodySettings.m_computeInertiaTensor = false; + rigidBodySettings.m_computeCenterOfMass = false; + rigidBodySettings.m_mass = 1.0f; rigidBodySettings.m_position = position; rigidBodySettings.m_linearDamping = 0.0f; rigidBodySettings.m_colliderAndShapeData = AZStd::make_pair(&colliderConfig, &shapeConfiguration); @@ -437,6 +441,10 @@ namespace PhysX Physics::CapsuleShapeConfiguration shapeConfig(height, radius); rigidBodySettings.m_colliderAndShapeData = AZStd::make_pair(&colliderConfig, &shapeConfig); rigidBodySettings.m_position = position; + rigidBodySettings.m_computeMass = false; + rigidBodySettings.m_computeInertiaTensor = false; + rigidBodySettings.m_computeCenterOfMass = false; + rigidBodySettings.m_mass = 1.0f; if (auto* sceneInterface = AZ::Interface::Get()) { @@ -455,6 +463,10 @@ namespace PhysX shapeConfiguration.m_dimensions = dimensions; AzPhysics::RigidBodyConfiguration rigidBodySettings; + rigidBodySettings.m_computeMass = false; + rigidBodySettings.m_computeInertiaTensor = false; + rigidBodySettings.m_computeCenterOfMass = false; + rigidBodySettings.m_mass = 1.0f; rigidBodySettings.m_position = position; rigidBodySettings.m_linearDamping = 0.0f; rigidBodySettings.m_colliderAndShapeData = AZStd::make_pair(&colliderConfig, &shapeConfiguration); From a13c9e8d531c25d2c490e127f63d2964b3ba9c08 Mon Sep 17 00:00:00 2001 From: Hasareej <82398396+Hasareej@users.noreply.github.com> Date: Thu, 13 May 2021 14:23:31 +0100 Subject: [PATCH 097/100] Hasareej lyn 2301 cluster space (#717) ViewportUi widget anchoring & alignment update. --- .../EditorTransformComponentSelection.cpp | 2 +- .../ViewportUi/ViewportUiDisplay.cpp | 30 ++++++++++++++++--- .../ViewportUi/ViewportUiDisplay.h | 4 +-- .../ViewportUi/ViewportUiManager.cpp | 8 ++--- .../ViewportUi/ViewportUiManager.h | 4 +-- .../ViewportUi/ViewportUiRequestBus.h | 15 ++++++++-- .../Tests/Viewport/ViewportUiDisplayTests.cpp | 10 +++---- .../Tests/Viewport/ViewportUiManagerTests.cpp | 12 ++++---- .../Code/Editor/ColliderComponentMode.cpp | 2 +- .../Source/EditorWhiteBoxComponentMode.cpp | 2 +- 10 files changed, 61 insertions(+), 28 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index c6450d03c7..1766e65276 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -2526,7 +2526,7 @@ namespace AzToolsFramework // create the cluster for changing transform mode ViewportUi::ViewportUiRequestBus::EventResult( m_transformModeClusterId, ViewportUi::DefaultViewportId, - &ViewportUi::ViewportUiRequestBus::Events::CreateCluster); + &ViewportUi::ViewportUiRequestBus::Events::CreateCluster, ViewportUi::Alignment::TopLeft); // create and register the buttons (strings correspond to icons even if the values appear different) m_translateButtonId = RegisterClusterButton(m_transformModeClusterId, "Move"); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp index e67ac46f62..e9e7dcc1cc 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp @@ -41,6 +41,28 @@ namespace AzToolsFramework::ViewportUi::Internal } } + static Qt::Alignment GetQtAlignment(Alignment align) + { + switch (align) + { + case Alignment::TopRight: + return Qt::AlignTop | Qt::AlignRight; + case Alignment::TopLeft: + return Qt::AlignTop | Qt::AlignLeft; + case Alignment::BottomRight: + return Qt::AlignBottom | Qt::AlignRight; + case Alignment::BottomLeft: + return Qt::AlignBottom | Qt::AlignLeft; + case Alignment::Top: + return Qt::AlignTop; + case Alignment::Bottom: + return Qt::AlignBottom; + } + + AZ_Assert(false, "ViewportUI", "Unhandled ViewportUI Alignment %d", static_cast(align)); + return Qt::AlignTop; + } + ViewportUiDisplay::ViewportUiDisplay(QWidget* parent, QWidget* renderOverlay) : m_renderOverlay(renderOverlay) , m_uiMainWindow(parent) @@ -56,7 +78,7 @@ namespace AzToolsFramework::ViewportUi::Internal UnparentWidgets(m_viewportUiElements); } - void ViewportUiDisplay::AddCluster(AZStd::shared_ptr buttonGroup) + void ViewportUiDisplay::AddCluster(AZStd::shared_ptr buttonGroup, const Alignment align) { if (!buttonGroup.get()) { @@ -66,7 +88,7 @@ namespace AzToolsFramework::ViewportUi::Internal auto viewportUiCluster = AZStd::make_shared(buttonGroup); auto id = AddViewportUiElement(viewportUiCluster); buttonGroup->SetViewportUiElementId(id); - PositionViewportUiElementAnchored(id, Qt::AlignTop | Qt::AlignLeft); + PositionViewportUiElementAnchored(id, GetQtAlignment(align)); } void ViewportUiDisplay::AddClusterButton( @@ -94,7 +116,7 @@ namespace AzToolsFramework::ViewportUi::Internal } } - void ViewportUiDisplay::AddSwitcher(AZStd::shared_ptr buttonGroup) + void ViewportUiDisplay::AddSwitcher(AZStd::shared_ptr buttonGroup, const Alignment align) { if (!buttonGroup.get()) { @@ -104,7 +126,7 @@ namespace AzToolsFramework::ViewportUi::Internal auto viewportUiSwitcher = AZStd::make_shared(buttonGroup); auto id = AddViewportUiElement(viewportUiSwitcher); buttonGroup->SetViewportUiElementId(id); - PositionViewportUiElementAnchored(id, Qt::AlignTop | Qt::AlignLeft); + PositionViewportUiElementAnchored(id, GetQtAlignment(align)); } void ViewportUiDisplay::AddSwitcherButton(const ViewportUiElementId clusterId, Button* button) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h index 7ef81986c0..d46e01c978 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h @@ -56,12 +56,12 @@ namespace AzToolsFramework::ViewportUi::Internal ViewportUiDisplay(QWidget* parent, QWidget* renderOverlay); ~ViewportUiDisplay(); - void AddCluster(AZStd::shared_ptr buttonGroup); + void AddCluster(AZStd::shared_ptr buttonGroup, Alignment align); void AddClusterButton(ViewportUiElementId clusterId, Button* button); void RemoveClusterButton(ViewportUiElementId clusterId, ButtonId buttonId); void UpdateCluster(const ViewportUiElementId clusterId); - void AddSwitcher(AZStd::shared_ptr buttonGroup); + void AddSwitcher(AZStd::shared_ptr buttonGroup, Alignment align); void AddSwitcherButton(ViewportUiElementId switcherId, Button* button); void RemoveSwitcherButton(ViewportUiElementId switcherId, ButtonId buttonId); void UpdateSwitcher(ViewportUiElementId switcherId); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp index 6eb97adb93..12c3b5c9bb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp @@ -30,18 +30,18 @@ namespace AzToolsFramework::ViewportUi ViewportUiRequestBus::Handler::BusDisconnect(); } - const ClusterId ViewportUiManager::CreateCluster() + const ClusterId ViewportUiManager::CreateCluster(const Alignment align) { auto buttonGroup = AZStd::make_shared(); - m_viewportUi->AddCluster(buttonGroup); + m_viewportUi->AddCluster(buttonGroup, align); return RegisterNewCluster(buttonGroup); } - const SwitcherId ViewportUiManager::CreateSwitcher() + const SwitcherId ViewportUiManager::CreateSwitcher(const Alignment align) { auto buttonGroup = AZStd::make_shared(); - m_viewportUi->AddSwitcher(buttonGroup); + m_viewportUi->AddSwitcher(buttonGroup, align); return RegisterNewSwitcher(buttonGroup); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h index 1b350bbd64..04a58cef65 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h @@ -31,8 +31,8 @@ namespace AzToolsFramework::ViewportUi ~ViewportUiManager() = default; // ViewportUiRequestBus ... - const ClusterId CreateCluster() override; - const SwitcherId CreateSwitcher() override; + const ClusterId CreateCluster(Alignment align) override; + const SwitcherId CreateSwitcher(Alignment align) override; void SetClusterActiveButton(ClusterId clusterId, ButtonId buttonId) override; void SetSwitcherActiveButton(SwitcherId switcherId, ButtonId buttonId) override; const ButtonId CreateClusterButton(ClusterId clusterId, const AZStd::string& icon) override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h index 5041f28656..3879817ccb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h @@ -41,15 +41,26 @@ namespace AzToolsFramework::ViewportUi String }; + //! Used to anchor widgets to a specific side of the viewport. + enum class Alignment + { + TopRight, + TopLeft, + BottomRight, + BottomLeft, + Top, + Bottom + }; + //! Viewport requests to interact with the Viewport UI. Viewport UI refers to the entire UI overlay (one per viewport). //! Each widget on the Viewport UI is referred to as an element. class ViewportUiRequests { public: //! Creates and registers a cluster with the Viewport UI system. - virtual const ClusterId CreateCluster() = 0; + virtual const ClusterId CreateCluster(Alignment align) = 0; //! Creates and registers a switcher with the Viewport UI system. - virtual const SwitcherId CreateSwitcher() = 0; + virtual const SwitcherId CreateSwitcher(Alignment align) = 0; //! Sets the active button of the cluster. This is the button which will display as highlighted. virtual void SetClusterActiveButton(ClusterId clusterId, ButtonId buttonId) = 0; //! Sets the active button of the switcher. This is the button which has a text label. diff --git a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiDisplayTests.cpp b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiDisplayTests.cpp index a1ce868569..5fd102b450 100644 --- a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiDisplayTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiDisplayTests.cpp @@ -72,7 +72,7 @@ namespace UnitTest TEST_F(ViewportUiDisplayTestFixture, RemoveViewportUiElementRemovesElementFromViewportUi) { ViewportUiDisplay viewportUi(m_parentWidget, m_mockRenderOverlay); - viewportUi.AddCluster(m_buttonGroup); + viewportUi.AddCluster(m_buttonGroup, AzToolsFramework::ViewportUi::Alignment::TopLeft); auto widget = viewportUi.GetViewportUiElement(m_buttonGroup->GetViewportUiElementId()); EXPECT_TRUE(widget.get() != nullptr); @@ -89,7 +89,7 @@ namespace UnitTest ViewportUiDisplay viewportUi(m_parentWidget, m_mockRenderOverlay); viewportUi.InitializeUiOverlay(); - viewportUi.AddCluster(m_buttonGroup); + viewportUi.AddCluster(m_buttonGroup, AzToolsFramework::ViewportUi::Alignment::TopLeft); viewportUi.Update(); viewportUi.ShowViewportUiElement(m_buttonGroup->GetViewportUiElementId()); @@ -102,7 +102,7 @@ namespace UnitTest ViewportUiDisplay viewportUi(m_parentWidget, m_mockRenderOverlay); viewportUi.InitializeUiOverlay(); - viewportUi.AddCluster(m_buttonGroup); + viewportUi.AddCluster(m_buttonGroup, AzToolsFramework::ViewportUi::Alignment::TopLeft); viewportUi.HideViewportUiElement(m_buttonGroup->GetViewportUiElementId()); EXPECT_FALSE(viewportUi.IsViewportUiElementVisible(m_buttonGroup->GetViewportUiElementId())); @@ -112,7 +112,7 @@ namespace UnitTest { ViewportUiDisplay viewportUi(m_parentWidget, m_mockRenderOverlay); viewportUi.InitializeUiOverlay(); - viewportUi.AddCluster(m_buttonGroup); + viewportUi.AddCluster(m_buttonGroup, AzToolsFramework::ViewportUi::Alignment::TopLeft); viewportUi.Update(); auto widget = viewportUi.GetViewportUiElement(m_buttonGroup->GetViewportUiElementId()); @@ -129,7 +129,7 @@ namespace UnitTest auto buttonGroup = AZStd::make_shared(); buttonGroup->AddButton(""); - viewportUi.AddCluster(buttonGroup); + viewportUi.AddCluster(buttonGroup, AzToolsFramework::ViewportUi::Alignment::TopLeft); viewportUi.Update(); EXPECT_TRUE(viewportUi.GetUiMainWindow()->isVisible()); diff --git a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiManagerTests.cpp b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiManagerTests.cpp index 396bde3fdd..9babd0fe6d 100644 --- a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiManagerTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiManagerTests.cpp @@ -101,7 +101,7 @@ namespace UnitTest TEST_F(ViewportUiManagerTestFixture, CreateClusterAddsNewClusterAndReturnsId) { - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); auto clusterEntry = m_viewportManagerWrapper.GetViewportManager()->GetClusterMap().find(clusterId); EXPECT_TRUE(clusterEntry != m_viewportManagerWrapper.GetViewportManager()->GetClusterMap().end()); @@ -110,7 +110,7 @@ namespace UnitTest TEST_F(ViewportUiManagerTestFixture, CreateClusterButtonAddsNewButtonAndReturnsId) { - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); auto buttonId = m_viewportManagerWrapper.GetViewportManager()->CreateClusterButton(clusterId, ""); auto clusterEntry = m_viewportManagerWrapper.GetViewportManager()->GetClusterMap().find(clusterId); @@ -120,7 +120,7 @@ namespace UnitTest TEST_F(ViewportUiManagerTestFixture, SetClusterActiveButtonSetsButtonStateToActive) { - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); auto buttonId = m_viewportManagerWrapper.GetViewportManager()->CreateClusterButton(clusterId, ""); auto clusterEntry = m_viewportManagerWrapper.GetViewportManager()->GetClusterMap().find(clusterId); @@ -133,7 +133,7 @@ namespace UnitTest TEST_F(ViewportUiManagerTestFixture, RegisterClusterEventHandlerConnectsHandlerToClusterEvent) { - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); auto buttonId = m_viewportManagerWrapper.GetViewportManager()->CreateClusterButton(clusterId, ""); // create a handler which will be triggered by the cluster @@ -159,7 +159,7 @@ namespace UnitTest TEST_F(ViewportUiManagerTestFixture, RemoveClusterRemovesClusterFromViewportUi) { - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); m_viewportManagerWrapper.GetViewportManager()->RemoveCluster(clusterId); auto clusterEntry = m_viewportManagerWrapper.GetViewportManager()->GetClusterMap().find(clusterId); @@ -171,7 +171,7 @@ namespace UnitTest { m_viewportManagerWrapper.GetMockRenderOverlay()->setVisible(true); - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); auto buttonId = m_viewportManagerWrapper.GetViewportManager()->CreateClusterButton(clusterId, ""); m_viewportManagerWrapper.GetViewportManager()->Update(); diff --git a/Gems/PhysX/Code/Editor/ColliderComponentMode.cpp b/Gems/PhysX/Code/Editor/ColliderComponentMode.cpp index 9aece90d90..7caa497344 100644 --- a/Gems/PhysX/Code/Editor/ColliderComponentMode.cpp +++ b/Gems/PhysX/Code/Editor/ColliderComponentMode.cpp @@ -240,7 +240,7 @@ namespace PhysX // create the cluster for changing transform mode AzToolsFramework::ViewportUi::ViewportUiRequestBus::EventResult( m_modeSelectionClusterId, AzToolsFramework::ViewportUi::DefaultViewportId, - &AzToolsFramework::ViewportUi::ViewportUiRequestBus::Events::CreateCluster); + &AzToolsFramework::ViewportUi::ViewportUiRequestBus::Events::CreateCluster, AzToolsFramework::ViewportUi::Alignment::TopLeft); // create and register the buttons m_dimensionsModeButtonId = RegisterClusterButton(m_modeSelectionClusterId, "Scale"); diff --git a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentMode.cpp b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentMode.cpp index 7677ee69f4..0772851cba 100644 --- a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentMode.cpp +++ b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentMode.cpp @@ -482,7 +482,7 @@ namespace WhiteBox // create the cluster for changing transform mode AzToolsFramework::ViewportUi::ViewportUiRequestBus::EventResult( m_modeSelectionClusterId, AzToolsFramework::ViewportUi::DefaultViewportId, - &AzToolsFramework::ViewportUi::ViewportUiRequestBus::Events::CreateCluster); + &AzToolsFramework::ViewportUi::ViewportUiRequestBus::Events::CreateCluster, AzToolsFramework::ViewportUi::Alignment::TopLeft); // create and register the buttons m_defaultModeButtonId = RegisterClusterButton(m_modeSelectionClusterId, "SketchMode"); From 7f79cc879698118c05dba138270e5e36955c94c2 Mon Sep 17 00:00:00 2001 From: amzn-sean <75276488+amzn-sean@users.noreply.github.com> Date: Thu, 13 May 2021 15:04:00 +0100 Subject: [PATCH 098/100] RemoveSimulatedBody automatically updates the requested handle to be invalid once removed. (#740) --- .../AzFramework/Physics/PhysicsScene.h | 16 ++++++++-------- Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h | 4 ++-- .../Code/Source/EditorColliderComponent.cpp | 4 ---- .../Code/Source/EditorRigidBodyComponent.cpp | 2 -- .../Code/Source/EditorShapeColliderComponent.cpp | 2 -- .../PhysXCharacters/API/CharacterController.cpp | 1 - .../Source/PhysXCharacters/API/RagdollNode.cpp | 1 - Gems/PhysX/Code/Source/RigidBodyComponent.cpp | 1 - Gems/PhysX/Code/Source/Scene/PhysXScene.cpp | 6 ++++-- Gems/PhysX/Code/Source/Scene/PhysXScene.h | 4 ++-- .../Code/Source/Scene/PhysXSceneInterface.cpp | 4 ++-- .../Code/Source/Scene/PhysXSceneInterface.h | 4 ++-- .../Code/Source/StaticRigidBodyComponent.cpp | 1 - .../Benchmarks/PhysXBenchmarkWashingMachine.cpp | 2 -- .../Tests/Benchmarks/PhysXJointBenchmarks.cpp | 5 +---- .../Benchmarks/PhysXRigidBodyBenchmarks.cpp | 15 +++------------ Gems/PhysX/Code/Tests/PhysXSceneTests.cpp | 9 +++++++-- Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp | 1 - .../Code/Tests/ScriptCanvasPhysicsTest.cpp | 4 ++-- .../EditorWhiteBoxColliderComponent.cpp | 1 - .../Components/WhiteBoxColliderComponent.cpp | 1 - 21 files changed, 33 insertions(+), 55 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Physics/PhysicsScene.h b/Code/Framework/AzFramework/AzFramework/Physics/PhysicsScene.h index db3ec15c83..58e53b0b0d 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/PhysicsScene.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/PhysicsScene.h @@ -88,13 +88,13 @@ namespace AzPhysics //! Remove a simulated body from the Scene.z //! @param sceneHandle A handle to the scene to remove the requested simulated body. - //! @param bodyHandle A handle to the simulated body being removed. - virtual void RemoveSimulatedBody(SceneHandle sceneHandle, SimulatedBodyHandle bodyHandle) = 0; + //! @param bodyHandle A handle to the simulated body being removed. This will be set to AzPhysics::InvalidSimulatedBodyHandle as they're no longer valid. + virtual void RemoveSimulatedBody(SceneHandle sceneHandle, SimulatedBodyHandle& bodyHandle) = 0; //! Remove a list of simulated bodies from the Scene. //! @param sceneHandle A handle to the scene to remove the simulated bodies from. - //! @param bodyHandles A list of simulated body handles to be removed. - virtual void RemoveSimulatedBodies(SceneHandle sceneHandle, const SimulatedBodyHandleList& bodyHandles) = 0; + //! @param bodyHandles A list of simulated body handles to be removed. All handles will be set to AzPhysics::InvalidSimulatedBodyHandle as they're no longer valid. + virtual void RemoveSimulatedBodies(SceneHandle sceneHandle, SimulatedBodyHandleList& bodyHandles) = 0; //! Enable / Disable simulation of the requested body. By default all bodies added are enabled. //! Disabling simulation the body will no longer be affected by any forces, collisions, or found with scene queries. @@ -286,12 +286,12 @@ namespace AzPhysics virtual SimulatedBodyList GetSimulatedBodiesFromHandle(const SimulatedBodyHandleList& bodyHandles) = 0; //! Remove a simulated body from the Scene. - //! @param bodyHandle A handle to the simulated body being removed. - virtual void RemoveSimulatedBody(SimulatedBodyHandle bodyHandle) = 0; + //! @param bodyHandle A handle to the simulated body being removed. This will be set to AzPhysics::InvalidSimulatedBodyHandle as they're no longer valid. + virtual void RemoveSimulatedBody(SimulatedBodyHandle& bodyHandle) = 0; //! Remove a list of simulated bodies from the Scene. - //! @param bodyHandles A list of simulated body handles to be removed. - virtual void RemoveSimulatedBodies(const SimulatedBodyHandleList& bodyHandles) = 0; + //! @param bodyHandles A list of simulated body handles to be removed. All handles will be set to AzPhysics::InvalidSimulatedBodyHandle as they're no longer valid. + virtual void RemoveSimulatedBodies(SimulatedBodyHandleList& bodyHandles) = 0; //! Enable / Disable simulation of the requested body. By default all bodies added are enabled. //! Disabling simulation the body will no longer be affected by any forces, collisions, or found with scene queries. diff --git a/Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h b/Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h index 1219e34448..22102fd38a 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h @@ -92,10 +92,10 @@ namespace Physics [[maybe_unused]] bool enable) override {} void RemoveSimulatedBody( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, - [[maybe_unused]] AzPhysics::SimulatedBodyHandle bodyHandle) override {} + [[maybe_unused]] AzPhysics::SimulatedBodyHandle& bodyHandle) override {} void RemoveSimulatedBodies( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, - [[maybe_unused]] const AzPhysics::SimulatedBodyHandleList& bodyHandles) override {} + [[maybe_unused]] AzPhysics::SimulatedBodyHandleList& bodyHandles) override {} void EnableSimulationOfBody( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, [[maybe_unused]] AzPhysics::SimulatedBodyHandle bodyHandle) override {} diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp index 2cf5835a1f..18bb06ba74 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp @@ -405,7 +405,6 @@ namespace PhysX if (m_sceneInterface) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } @@ -579,7 +578,6 @@ namespace PhysX if (m_sceneInterface && m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } return; } @@ -634,7 +632,6 @@ namespace PhysX if (m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } m_editorBodyHandle = m_sceneInterface->AddSimulatedBody(m_editorSceneHandle, &configuration); @@ -1051,7 +1048,6 @@ namespace PhysX if (m_sceneInterface && m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } diff --git a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp index f97e7c6cbd..efd65181da 100644 --- a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp @@ -283,7 +283,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorRigidBodyHandle); - m_editorRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } @@ -428,7 +427,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorRigidBodyHandle); - m_editorRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; CreateEditorWorldRigidBody(); } diff --git a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp index b71bd47288..58b8995281 100644 --- a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp @@ -271,7 +271,6 @@ namespace PhysX if (m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } m_editorBodyHandle = m_sceneInterface->AddSimulatedBody(m_editorSceneHandle, &configuration); @@ -681,7 +680,6 @@ namespace PhysX if (m_sceneInterface && m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterController.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterController.cpp index 9e5f92aa72..08df8c0601 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterController.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterController.cpp @@ -343,7 +343,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_sceneOwner, m_shadowBodyHandle); - m_shadowBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; m_shadowBody = nullptr; } } diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/API/RagdollNode.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/API/RagdollNode.cpp index 6e3b97212b..0f9c7644cd 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/API/RagdollNode.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/API/RagdollNode.cpp @@ -163,7 +163,6 @@ namespace PhysX sceneInterface->RemoveSimulatedBody(m_sceneOwner, m_rigidBodyHandle); } m_rigidBody = nullptr; - m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; m_sceneOwner = AzPhysics::InvalidSceneHandle; } } diff --git a/Gems/PhysX/Code/Source/RigidBodyComponent.cpp b/Gems/PhysX/Code/Source/RigidBodyComponent.cpp index 58b0749d0f..f770f8408c 100644 --- a/Gems/PhysX/Code/Source/RigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/RigidBodyComponent.cpp @@ -184,7 +184,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_attachedSceneHandle, m_rigidBodyHandle); - m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } Physics::RigidBodyRequestBus::Handler::BusDisconnect(); diff --git a/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp b/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp index 96e2d8a9bb..79aa767959 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp +++ b/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp @@ -729,7 +729,7 @@ namespace PhysX return results; } - void PhysXScene::RemoveSimulatedBody(AzPhysics::SimulatedBodyHandle bodyHandle) + void PhysXScene::RemoveSimulatedBody(AzPhysics::SimulatedBodyHandle& bodyHandle) { if (bodyHandle == AzPhysics::InvalidSimulatedBodyHandle) { @@ -751,10 +751,12 @@ namespace PhysX m_deferredDeletions.push_back(m_simulatedBodies[index].second); m_simulatedBodies[index] = AZStd::make_pair(AZ::Crc32(), nullptr); m_freeSceneSlots.push(index); + + bodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } - void PhysXScene::RemoveSimulatedBodies(const AzPhysics::SimulatedBodyHandleList& bodyHandles) + void PhysXScene::RemoveSimulatedBodies(AzPhysics::SimulatedBodyHandleList& bodyHandles) { for (auto& handle: bodyHandles) { diff --git a/Gems/PhysX/Code/Source/Scene/PhysXScene.h b/Gems/PhysX/Code/Source/Scene/PhysXScene.h index 8bf20fca55..2e257283f0 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXScene.h +++ b/Gems/PhysX/Code/Source/Scene/PhysXScene.h @@ -48,8 +48,8 @@ namespace PhysX AzPhysics::SimulatedBodyHandleList AddSimulatedBodies(const AzPhysics::SimulatedBodyConfigurationList& simulatedBodyConfigs) override; AzPhysics::SimulatedBody* GetSimulatedBodyFromHandle(AzPhysics::SimulatedBodyHandle bodyHandle) override; AzPhysics::SimulatedBodyList GetSimulatedBodiesFromHandle(const AzPhysics::SimulatedBodyHandleList& bodyHandles) override; - void RemoveSimulatedBody(AzPhysics::SimulatedBodyHandle bodyHandle) override; - void RemoveSimulatedBodies(const AzPhysics::SimulatedBodyHandleList& bodyHandles) override; + void RemoveSimulatedBody(AzPhysics::SimulatedBodyHandle& bodyHandle) override; + void RemoveSimulatedBodies(AzPhysics::SimulatedBodyHandleList& bodyHandles) override; void EnableSimulationOfBody(AzPhysics::SimulatedBodyHandle bodyHandle) override; void DisableSimulationOfBody(AzPhysics::SimulatedBodyHandle bodyHandle) override; AzPhysics::SceneQueryHits QueryScene(const AzPhysics::SceneQueryRequest* request) override; diff --git a/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.cpp b/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.cpp index 948529a5c8..3b3ab2f0f8 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.cpp +++ b/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.cpp @@ -112,7 +112,7 @@ namespace PhysX return {}; //return an empty list } - void PhysXSceneInterface::RemoveSimulatedBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle) + void PhysXSceneInterface::RemoveSimulatedBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle& bodyHandle) { if (AzPhysics::Scene* scene = m_physxSystem->GetScene(sceneHandle)) { @@ -120,7 +120,7 @@ namespace PhysX } } - void PhysXSceneInterface::RemoveSimulatedBodies(AzPhysics::SceneHandle sceneHandle, const AzPhysics::SimulatedBodyHandleList& bodyHandles) + void PhysXSceneInterface::RemoveSimulatedBodies(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandleList& bodyHandles) { if (AzPhysics::Scene* scene = m_physxSystem->GetScene(sceneHandle)) { diff --git a/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.h b/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.h index 3bc08d641c..2edfbd8457 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.h +++ b/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.h @@ -40,8 +40,8 @@ namespace PhysX AzPhysics::SimulatedBodyHandleList AddSimulatedBodies(AzPhysics::SceneHandle sceneHandle, const AzPhysics::SimulatedBodyConfigurationList& simulatedBodyConfigs) override; AzPhysics::SimulatedBody* GetSimulatedBodyFromHandle(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle) override; AzPhysics::SimulatedBodyList GetSimulatedBodiesFromHandle(AzPhysics::SceneHandle sceneHandle, const AzPhysics::SimulatedBodyHandleList& bodyHandles) override; - void RemoveSimulatedBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle) override; - void RemoveSimulatedBodies(AzPhysics::SceneHandle sceneHandle, const AzPhysics::SimulatedBodyHandleList& bodyHandles) override; + void RemoveSimulatedBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle& bodyHandle) override; + void RemoveSimulatedBodies(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandleList& bodyHandles) override; void EnableSimulationOfBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle) override; void DisableSimulationOfBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle) override; AzPhysics::SceneQueryHits QueryScene(AzPhysics::SceneHandle sceneHandle, const AzPhysics::SceneQueryRequest* request) override; diff --git a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp index 881fb29750..bb1dfc4293 100644 --- a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp @@ -117,7 +117,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_attachedSceneHandle, m_staticRigidBodyHandle); - m_staticRigidBodyHandle = AzPhysics::InvalidSceneHandle; } AzPhysics::SimulatedBodyComponentRequestsBus::Handler::BusDisconnect(); diff --git a/Gems/PhysX/Code/Tests/Benchmarks/PhysXBenchmarkWashingMachine.cpp b/Gems/PhysX/Code/Tests/Benchmarks/PhysXBenchmarkWashingMachine.cpp index 463aea2f71..adc910e8c8 100644 --- a/Gems/PhysX/Code/Tests/Benchmarks/PhysXBenchmarkWashingMachine.cpp +++ b/Gems/PhysX/Code/Tests/Benchmarks/PhysXBenchmarkWashingMachine.cpp @@ -129,10 +129,8 @@ namespace PhysX::Benchmarks for (int i = 0; i < NumCylinderSide; i++) { sceneInterface->RemoveSimulatedBody(m_sceneHandle, m_cylinder[i]); - m_cylinder[i] = AzPhysics::InvalidSimulatedBodyHandle; } sceneInterface->RemoveSimulatedBody(m_sceneHandle, m_blade); - m_blade = AzPhysics::InvalidSimulatedBodyHandle; } m_sceneHandle = AzPhysics::InvalidSceneHandle; } diff --git a/Gems/PhysX/Code/Tests/Benchmarks/PhysXJointBenchmarks.cpp b/Gems/PhysX/Code/Tests/Benchmarks/PhysXJointBenchmarks.cpp index 7143f08626..7d650d6bef 100644 --- a/Gems/PhysX/Code/Tests/Benchmarks/PhysXJointBenchmarks.cpp +++ b/Gems/PhysX/Code/Tests/Benchmarks/PhysXJointBenchmarks.cpp @@ -404,10 +404,7 @@ namespace PhysX::Benchmarks } subTickTracker.Stop(); - for (auto handle : snakeRigidBodyHandles) - { - m_defaultScene->RemoveSimulatedBody(handle); - } + m_defaultScene->RemoveSimulatedBodies(snakeRigidBodyHandles); snakeRigidBodyHandles.clear(); //sort the frame times and get the P50, P90, P99 percentiles diff --git a/Gems/PhysX/Code/Tests/Benchmarks/PhysXRigidBodyBenchmarks.cpp b/Gems/PhysX/Code/Tests/Benchmarks/PhysXRigidBodyBenchmarks.cpp index 54f7d2219c..e295916554 100644 --- a/Gems/PhysX/Code/Tests/Benchmarks/PhysXRigidBodyBenchmarks.cpp +++ b/Gems/PhysX/Code/Tests/Benchmarks/PhysXRigidBodyBenchmarks.cpp @@ -233,10 +233,7 @@ namespace PhysX::Benchmarks subTickTracker.Stop(); //object clean up - for (auto handle : rigidBodies) - { - m_defaultScene->RemoveSimulatedBody(handle); - } + m_defaultScene->RemoveSimulatedBodies(rigidBodies); rigidBodies.clear(); //sort the frame times and get the P50, P90, P99 percentiles @@ -310,10 +307,7 @@ namespace PhysX::Benchmarks //object clean up washingMachine.TearDownWashingMachine(); - for (auto handle : rigidBodies) - { - m_defaultScene->RemoveSimulatedBody(handle); - } + m_defaultScene->RemoveSimulatedBodies(rigidBodies); rigidBodies.clear(); //sort the frame times and get the P50, P90, P99 percentiles @@ -465,10 +459,7 @@ namespace PhysX::Benchmarks //object clean up collisionHandlers.clear(); washingMachine.TearDownWashingMachine(); - for (auto handle : rigidBodies) - { - m_defaultScene->RemoveSimulatedBody(handle); - } + m_defaultScene->RemoveSimulatedBodies(rigidBodies); rigidBodies.clear(); //sort the frame times and get the P50, P90, P99 percentiles diff --git a/Gems/PhysX/Code/Tests/PhysXSceneTests.cpp b/Gems/PhysX/Code/Tests/PhysXSceneTests.cpp index 2a30fad32d..2a38e1b867 100644 --- a/Gems/PhysX/Code/Tests/PhysXSceneTests.cpp +++ b/Gems/PhysX/Code/Tests/PhysXSceneTests.cpp @@ -237,13 +237,17 @@ namespace PhysX //select 1 to remove AzPhysics::SimulatedBodyHandle removedSelection = simBodyHandles[simBodyHandles.size() / 2]; + const AzPhysics::SimulatedBodyIndex removedIndex = AZStd::get(removedSelection); sceneInterface->RemoveSimulatedBody(m_testSceneHandle, removedSelection); + // The removedSelection handle should be set to invalid in RemoveSimulatedBody + EXPECT_EQ(removedSelection, AzPhysics::InvalidSimulatedBodyHandle); + //add a new one. AzPhysics::SimulatedBodyHandle newSimBodyHandle = sceneInterface->AddSimulatedBody(m_testSceneHandle, &config); //The old and new handle should share an index as the freed slot will be used - EXPECT_EQ(AZStd::get(removedSelection), + EXPECT_EQ(removedIndex, AZStd::get(newSimBodyHandle)); } @@ -287,9 +291,10 @@ namespace PhysX EXPECT_EQ(simBodyHandle, addEventSimBodyHandle); //remove the body + const AzPhysics::SimulatedBodyHandle removedHandle = simBodyHandle; //copy the handle as RemoveSimulatedBody will mark it invalid. sceneInterface->RemoveSimulatedBody(m_testSceneHandle, simBodyHandle); EXPECT_TRUE(removedTriggered); - EXPECT_EQ(simBodyHandle, removeEventSimBodyHandle); + EXPECT_EQ(removedHandle, removeEventSimBodyHandle); } TEST_F(PhysXSceneFixture, StartFinishSimulationEvents_triggerAsExpected) diff --git a/Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp b/Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp index 8e4da0fe4b..74c88d0b46 100644 --- a/Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp +++ b/Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp @@ -882,7 +882,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_testSceneHandle, rigidBodyHandle); - rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } rigidBody = nullptr; } diff --git a/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp b/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp index c74030d6df..4b04434e13 100644 --- a/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp +++ b/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp @@ -90,10 +90,10 @@ namespace ScriptCanvasPhysicsTests [[maybe_unused]] bool enable) override {} void RemoveSimulatedBody( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, - [[maybe_unused]] AzPhysics::SimulatedBodyHandle bodyHandle) override {} + [[maybe_unused]] AzPhysics::SimulatedBodyHandle& bodyHandle) override {} void RemoveSimulatedBodies( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, - [[maybe_unused]] const AzPhysics::SimulatedBodyHandleList& bodyHandles) override {} + [[maybe_unused]] AzPhysics::SimulatedBodyHandleList& bodyHandles) override {} void EnableSimulationOfBody( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, [[maybe_unused]] AzPhysics::SimulatedBodyHandle bodyHandle) override {} diff --git a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp index 97bce7631d..c8b189942e 100644 --- a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp +++ b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp @@ -163,7 +163,6 @@ namespace WhiteBox if (m_sceneInterface) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_rigidBodyHandle); - m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } diff --git a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp index 117b175cda..41d0a4c5e3 100644 --- a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp +++ b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp @@ -132,7 +132,6 @@ namespace WhiteBox sceneInterface->RemoveSimulatedBody(defaultScene, m_simulatedBodyHandle); } } - m_simulatedBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } void WhiteBoxColliderComponent::OnTransformChanged( From 4aff32e719c604b59ccdef7e21ce3dcd9923a8dc Mon Sep 17 00:00:00 2001 From: bosnichd Date: Thu, 13 May 2021 08:55:36 -0600 Subject: [PATCH 099/100] More red code (#732) Remove: - Code/CryEngine/CryCommon/Platform - Some unused Code/CryEngine/CryCommon/Mock files - Code/Tools/CryXML and almost all of Code/Tools/CryCommonTools - Code/Tools/TestBed/ResourceCompilerImage - Tools/DeepBandwidthToExcel - Various .p4ignore files --- Code/.p4ignore | 6 - Code/CryEngine/CryCommon/CMakeLists.txt | 8 - .../CryCommon/Mocks/IMemoryManagerMock.h | 43 - Code/CryEngine/CryCommon/Mocks/INetworkMock.h | 47 - .../CryCommon/Mocks/MockCGFContent.h | 29 - .../Platform/Android/crycommon_android.cmake | 11 - .../Android/crycommon_android_files.cmake | 14 - ...ycommon_enginesettings_android_files.cmake | 13 - .../Platform/AppleTV/crycommon_appletv.cmake | 11 - ...crycommon_enginesettings_linux_files.cmake | 13 - .../Platform/Linux/crycommon_linux.cmake | 11 - .../Linux/crycommon_linux_files.cmake | 14 - .../Platform/Mac/crycommon_mac.cmake | 11 - .../Platform/Mac/crycommon_mac_files.cmake | 14 - .../Platform/Windows/crycommon_windows.cmake | 11 - .../Windows/crycommon_windows_files.cmake | 13 - .../crycommon_enginesettings_ios_files.cmake | 13 - .../Platform/iOS/crycommon_ios.cmake | 11 - .../Platform/iOS/crycommon_ios_files.cmake | 14 - .../CryCommon/Terrain/Bus/HeightmapDataBus.h | 102 - .../CryCommon/Terrain/Bus/TerrainBus.h | 56 - .../Terrain/Bus/TerrainProviderBus.h | 82 - .../Terrain/Bus/TerrainRendererBus.h | 37 - .../Terrain/Bus/WorldMaterialRequestsBus.h | 122 - Code/CryEngine/CryCommon/WinBase.cpp | 3 + .../CryEngine/CryCommon/crycommon_files.cmake | 7 +- .../CryCommon/crycommon_linux_files.cmake | 13 - .../CryCommon/crycommon_testing_files.cmake | 2 - .../CryEngine/CryCommon/stl/STLAlignedAlloc.h | 115 - .../CrySystem/Tests/Test_CryPrimitives.cpp | 16 - Code/Framework/AtomCore/.p4ignore | 1 - Code/Framework/AzCore/.p4ignore | 1 - Code/Sandbox/.p4ignore | 5 - Code/Tools/CMakeLists.txt | 1 - Code/Tools/CryCommonTools/CMakeLists.txt | 26 - Code/Tools/CryCommonTools/ColladaShared.h | 18 - Code/Tools/CryCommonTools/Decompose.cpp | 514 ---- Code/Tools/CryCommonTools/Decompose.h | 30 - Code/Tools/CryCommonTools/Exceptions.h | 43 - Code/Tools/CryCommonTools/FileUtil.cpp | 175 -- Code/Tools/CryCommonTools/FileUtil.h | 311 --- .../CryCommonTools/FileXmlBufferSource.h | 48 - Code/Tools/CryCommonTools/ILogger.h | 53 - Code/Tools/CryCommonTools/IPakSystem.h | 49 - Code/Tools/CryCommonTools/ISettings.h | 57 - Code/Tools/CryCommonTools/LocaleChanger.cpp | 27 - Code/Tools/CryCommonTools/LocaleChanger.h | 30 - Code/Tools/CryCommonTools/LogFile.cpp | 79 - Code/Tools/CryCommonTools/LogFile.h | 40 - Code/Tools/CryCommonTools/MathHelpers.h | 72 - Code/Tools/CryCommonTools/ModuleHelpers.cpp | 44 - Code/Tools/CryCommonTools/ModuleHelpers.h | 31 - Code/Tools/CryCommonTools/PakSystem.cpp | 380 --- Code/Tools/CryCommonTools/PakSystem.h | 69 - .../CryCommonTools/PakXmlFileBufferSource.h | 74 - Code/Tools/CryCommonTools/PathHelpers.cpp | 621 ----- Code/Tools/CryCommonTools/PathHelpers.h | 110 - .../UnixLike/ZipDir/ZipDir_Traits_UnixLike.h | 15 - .../Linux/ZipDir/ZipDir_Traits_Linux.h | 16 - .../Linux/ZipDir/ZipDir_Traits_Platform.h | 15 - .../Platform/Linux/platform_linux_files.cmake | 16 - .../Platform/Mac/ZipDir/ZipDir_Traits_Mac.h | 16 - .../Mac/ZipDir/ZipDir_Traits_Platform.h | 14 - .../Platform/Mac/platform_mac_files.cmake | 16 - .../Windows/ZipDir/ZipDir_Traits_Platform.h | 14 - .../Windows/ZipDir/ZipDir_Traits_Windows.h | 16 - .../Windows/platform_windows_files.cmake | 15 - Code/Tools/CryCommonTools/ProgressRange.h | 89 - Code/Tools/CryCommonTools/PropertyHelpers.cpp | 125 - Code/Tools/CryCommonTools/PropertyHelpers.h | 28 - Code/Tools/CryCommonTools/STLHelpers.cpp | 14 - Code/Tools/CryCommonTools/STLHelpers.h | 54 - Code/Tools/CryCommonTools/SimpleBitmap.h | 508 ---- Code/Tools/CryCommonTools/SimpleStringPool.h | 249 -- .../CryCommonTools/StealingThreadPool.cpp | 580 ----- .../Tools/CryCommonTools/StealingThreadPool.h | 123 - Code/Tools/CryCommonTools/SuffixUtil.h | 59 - .../CryCommonTools/SummedAreaFilterKernel.cpp | 442 ---- .../CryCommonTools/SummedAreaFilterKernel.h | 112 - .../CryCommonTools/TempFilePakExtraction.cpp | 129 - .../CryCommonTools/TempFilePakExtraction.h | 50 - Code/Tools/CryCommonTools/ThreadUtils.cpp | 171 -- Code/Tools/CryCommonTools/ThreadUtils.h | 288 --- Code/Tools/CryCommonTools/UI/log_icons.bmp | 3 - .../UnitTests/PathHelpersUnitTests.cpp | 807 ------- .../UnitTests/StringHelpersUnitTests.cpp | 1056 --------- Code/Tools/CryCommonTools/WeightFilterSet.cpp | 36 - Code/Tools/CryCommonTools/WeightFilterSet.h | 96 - Code/Tools/CryCommonTools/XMLPakFileSink.cpp | 55 - Code/Tools/CryCommonTools/XMLPakFileSink.h | 39 - Code/Tools/CryCommonTools/XMLWriter.cpp | 261 -- Code/Tools/CryCommonTools/XMLWriter.h | 185 -- Code/Tools/CryCommonTools/ZipDir/ZipDir.h | 30 - .../CryCommonTools/ZipDir/ZipDirCache.cpp | 298 --- .../Tools/CryCommonTools/ZipDir/ZipDirCache.h | 140 -- .../ZipDir/ZipDirCacheFactory.cpp | 804 ------- .../ZipDir/ZipDirCacheFactory.h | 143 -- .../CryCommonTools/ZipDir/ZipDirCacheRW.cpp | 2100 ----------------- .../CryCommonTools/ZipDir/ZipDirCacheRW.h | 283 --- .../CryCommonTools/ZipDir/ZipDirFind.cpp | 246 -- Code/Tools/CryCommonTools/ZipDir/ZipDirFind.h | 109 - .../CryCommonTools/ZipDir/ZipDirFindRW.cpp | 253 -- .../CryCommonTools/ZipDir/ZipDirFindRW.h | 110 - .../CryCommonTools/ZipDir/ZipDirList.cpp | 174 -- Code/Tools/CryCommonTools/ZipDir/ZipDirList.h | 138 -- .../ZipDir/ZipDirStructures.cpp | 670 ------ .../CryCommonTools/ZipDir/ZipDirTree.cpp | 356 --- Code/Tools/CryCommonTools/ZipDir/ZipDirTree.h | 103 - Code/Tools/CryCommonTools/ZipDir/ZipFile.h | 19 - .../CryCommonTools/ZipDir/ZipFileFormat.h | 388 --- .../ZipDir/ZipFileFormat_info.h | 112 - .../CryCommonTools/ZipDir/zipdirstructures.h | 426 ---- .../CryCommonTools/crycommontools_files.cmake | 39 - .../crycommontools_tests_files.cmake | 15 - Code/Tools/CryCommonTools/zlibstatd64.lib | 3 - Code/Tools/CryXML/CMakeLists.txt | 32 - Code/Tools/CryXML/CryXML.cpp | 105 - Code/Tools/CryXML/CryXML.def | 3 - Code/Tools/CryXML/CryXML_precompiled.cpp | 14 - Code/Tools/CryXML/CryXML_precompiled.h | 32 - Code/Tools/CryXML/ICryXML.h | 34 - Code/Tools/CryXML/IXMLSerializer.h | 68 - Code/Tools/CryXML/XML/xml.cpp | 1400 ----------- Code/Tools/CryXML/XML/xml.h | 471 ---- Code/Tools/CryXML/XMLSerializer.cpp | 40 - Code/Tools/CryXML/XMLSerializer.h | 31 - Code/Tools/CryXML/cryxml_files.cmake | 22 - .../Input/Bump2NormalHighQ.tif.exportsettings | 1 - ...usehighQWithAlpha256512.tif.exportsettings | 1 - ...usehighQWithAlpha512256.tif.exportsettings | 1 - .../Input/LuminanceOnly.tif.exportsettings | 1 - .../Input/NoPreset3DC_ddn.tif.exportsettings | 1 - .../Input/NoPresetX8R8G8B8.tif.exportsettings | 1 - ...PresetX8R8G8B8WithAlpha.tif.exportsettings | 1 - .../NoPresetX8R8G8B8_bump.tif.exportsettings | 1 - .../NoPresetX8R8G8B8_ddn.tif.exportsettings | 1 - .../Input/NoTIFSettings.tif.exportsettings | 1 - .../NoTIFSettings300400.tif.exportsettings | 1 - ...oTIFSettingsGrey_DDNDIF.tif.exportsettings | 1 - .../NoTIFSettings_DDNDIF.tif.exportsettings | 1 - .../Input/NormalmapLowQ.tif.exportsettings | 1 - ...ormalmapLowQReduce1_ddn.tif.exportsettings | 1 - .../NormalmapLowQ_ddn.tif.exportsettings | 1 - .../TestColorChart_cch.tif.exportsettings | 1 - .../diamand_plate_ddn.tif.exportsettings | 1 - Gems/Blast/Assets/.p4ignore | 1 - Tools/AnimationTest/assetImportTest.bat | 31 - Tools/DeepBandwidthToExcel/7z.exe | 3 - .../DeepBandwidthToExcel.exe | 3 - .../Template/[Content_Types].xml | 2 - .../DeepBandwidthToExcel/Template/_rels/.rels | 2 - .../Template/docProps/app.xml | 2 - .../Template/docProps/core.xml | 2 - .../Template/xl/_rels/workbook.xml.rels | 2 - .../Template/xl/calcChain.xml | 2 - .../Template/xl/charts/chart1.xml | 2 - .../Template/xl/charts/chart2.xml | 2 - .../Template/xl/charts/chart3.xml | 2 - .../Template/xl/charts/chart4.xml | 2 - .../Template/xl/charts/chart5.xml | 93 - .../Template/xl/charts/chart6.xml | 78 - .../Template/xl/charts/chart7.xml | 84 - .../Template/xl/charts/chart8.xml | 83 - .../xl/drawings/_rels/drawing1.xml.rels | 2 - .../xl/drawings/_rels/drawing2.xml.rels | 2 - .../xl/drawings/_rels/drawing3.xml.rels | 2 - .../xl/drawings/_rels/drawing4.xml.rels | 2 - .../xl/drawings/_rels/drawing5.xml.rels | 2 - .../xl/drawings/_rels/drawing6.xml.rels | 2 - .../xl/drawings/_rels/drawing7.xml.rels | 2 - .../xl/drawings/_rels/drawing8.xml.rels | 2 - .../Template/xl/drawings/drawing1.xml | 2 - .../Template/xl/drawings/drawing2.xml | 2 - .../Template/xl/drawings/drawing3.xml | 2 - .../Template/xl/drawings/drawing4.xml | 2 - .../Template/xl/drawings/drawing5.xml | 2 - .../Template/xl/drawings/drawing6.xml | 2 - .../Template/xl/drawings/drawing7.xml | 2 - .../Template/xl/drawings/drawing8.xml | 2 - .../Template/xl/sharedStrings.xml | 2 - .../Template/xl/styles.xml | 2 - .../Template/xl/theme/theme1.xml | 2 - .../Template/xl/workbook.xml | 2 - .../xl/worksheets/_rels/sheet1.xml.rels | 2 - .../xl/worksheets/_rels/sheet2.xml.rels | 2 - .../xl/worksheets/_rels/sheet3.xml.rels | 2 - .../xl/worksheets/_rels/sheet4.xml.rels | 2 - .../xl/worksheets/_rels/sheet5.xml.rels | 2 - .../xl/worksheets/_rels/sheet6.xml.rels | 2 - .../xl/worksheets/_rels/sheet7.xml.rels | 2 - .../xl/worksheets/_rels/sheet8.xml.rels | 2 - .../Template/xl/worksheets/sheet1.xml | 2 - .../Template/xl/worksheets/sheet2.xml | 2 - .../Template/xl/worksheets/sheet3.xml | 2 - .../Template/xl/worksheets/sheet4.xml | 19 - .../Template/xl/worksheets/sheet5.xml | 17 - .../Template/xl/worksheets/sheet6.xml | 18 - .../Template/xl/worksheets/sheet7.xml | 18 - .../Template/xl/worksheets/sheet8.xml | 18 - .../Template/xl/worksheets/sheet9.xml | 16 - .../Windows/package_filelists/atom.json | 11 - 201 files changed, 4 insertions(+), 19283 deletions(-) delete mode 100644 Code/.p4ignore delete mode 100644 Code/CryEngine/CryCommon/Mocks/IMemoryManagerMock.h delete mode 100644 Code/CryEngine/CryCommon/Mocks/INetworkMock.h delete mode 100644 Code/CryEngine/CryCommon/Mocks/MockCGFContent.h delete mode 100644 Code/CryEngine/CryCommon/Platform/Android/crycommon_android.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Android/crycommon_android_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Android/crycommon_enginesettings_android_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/AppleTV/crycommon_appletv.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Linux/crycommon_enginesettings_linux_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/iOS/crycommon_enginesettings_ios_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Terrain/Bus/HeightmapDataBus.h delete mode 100644 Code/CryEngine/CryCommon/Terrain/Bus/TerrainBus.h delete mode 100644 Code/CryEngine/CryCommon/Terrain/Bus/TerrainProviderBus.h delete mode 100644 Code/CryEngine/CryCommon/Terrain/Bus/TerrainRendererBus.h delete mode 100644 Code/CryEngine/CryCommon/Terrain/Bus/WorldMaterialRequestsBus.h delete mode 100644 Code/CryEngine/CryCommon/crycommon_linux_files.cmake delete mode 100644 Code/CryEngine/CryCommon/stl/STLAlignedAlloc.h delete mode 100644 Code/Framework/AtomCore/.p4ignore delete mode 100644 Code/Framework/AzCore/.p4ignore delete mode 100644 Code/Sandbox/.p4ignore delete mode 100644 Code/Tools/CryCommonTools/ColladaShared.h delete mode 100644 Code/Tools/CryCommonTools/Decompose.cpp delete mode 100644 Code/Tools/CryCommonTools/Decompose.h delete mode 100644 Code/Tools/CryCommonTools/Exceptions.h delete mode 100644 Code/Tools/CryCommonTools/FileUtil.cpp delete mode 100644 Code/Tools/CryCommonTools/FileUtil.h delete mode 100644 Code/Tools/CryCommonTools/FileXmlBufferSource.h delete mode 100644 Code/Tools/CryCommonTools/ILogger.h delete mode 100644 Code/Tools/CryCommonTools/IPakSystem.h delete mode 100644 Code/Tools/CryCommonTools/ISettings.h delete mode 100644 Code/Tools/CryCommonTools/LocaleChanger.cpp delete mode 100644 Code/Tools/CryCommonTools/LocaleChanger.h delete mode 100644 Code/Tools/CryCommonTools/LogFile.cpp delete mode 100644 Code/Tools/CryCommonTools/LogFile.h delete mode 100644 Code/Tools/CryCommonTools/MathHelpers.h delete mode 100644 Code/Tools/CryCommonTools/ModuleHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/ModuleHelpers.h delete mode 100644 Code/Tools/CryCommonTools/PakSystem.cpp delete mode 100644 Code/Tools/CryCommonTools/PakSystem.h delete mode 100644 Code/Tools/CryCommonTools/PakXmlFileBufferSource.h delete mode 100644 Code/Tools/CryCommonTools/PathHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/PathHelpers.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Linux.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Platform.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Linux/platform_linux_files.cmake delete mode 100644 Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Mac.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Platform.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Mac/platform_mac_files.cmake delete mode 100644 Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Platform.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Windows.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Windows/platform_windows_files.cmake delete mode 100644 Code/Tools/CryCommonTools/ProgressRange.h delete mode 100644 Code/Tools/CryCommonTools/PropertyHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/PropertyHelpers.h delete mode 100644 Code/Tools/CryCommonTools/STLHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/STLHelpers.h delete mode 100644 Code/Tools/CryCommonTools/SimpleBitmap.h delete mode 100644 Code/Tools/CryCommonTools/SimpleStringPool.h delete mode 100644 Code/Tools/CryCommonTools/StealingThreadPool.cpp delete mode 100644 Code/Tools/CryCommonTools/StealingThreadPool.h delete mode 100644 Code/Tools/CryCommonTools/SuffixUtil.h delete mode 100644 Code/Tools/CryCommonTools/SummedAreaFilterKernel.cpp delete mode 100644 Code/Tools/CryCommonTools/SummedAreaFilterKernel.h delete mode 100644 Code/Tools/CryCommonTools/TempFilePakExtraction.cpp delete mode 100644 Code/Tools/CryCommonTools/TempFilePakExtraction.h delete mode 100644 Code/Tools/CryCommonTools/ThreadUtils.cpp delete mode 100644 Code/Tools/CryCommonTools/ThreadUtils.h delete mode 100644 Code/Tools/CryCommonTools/UI/log_icons.bmp delete mode 100644 Code/Tools/CryCommonTools/UnitTests/PathHelpersUnitTests.cpp delete mode 100644 Code/Tools/CryCommonTools/UnitTests/StringHelpersUnitTests.cpp delete mode 100644 Code/Tools/CryCommonTools/WeightFilterSet.cpp delete mode 100644 Code/Tools/CryCommonTools/WeightFilterSet.h delete mode 100644 Code/Tools/CryCommonTools/XMLPakFileSink.cpp delete mode 100644 Code/Tools/CryCommonTools/XMLPakFileSink.h delete mode 100644 Code/Tools/CryCommonTools/XMLWriter.cpp delete mode 100644 Code/Tools/CryCommonTools/XMLWriter.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDir.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCache.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCache.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirFind.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirFind.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirList.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirList.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirStructures.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirTree.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirTree.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipFile.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipFileFormat.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipFileFormat_info.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/zipdirstructures.h delete mode 100644 Code/Tools/CryCommonTools/crycommontools_tests_files.cmake delete mode 100644 Code/Tools/CryCommonTools/zlibstatd64.lib delete mode 100644 Code/Tools/CryXML/CMakeLists.txt delete mode 100644 Code/Tools/CryXML/CryXML.cpp delete mode 100644 Code/Tools/CryXML/CryXML.def delete mode 100644 Code/Tools/CryXML/CryXML_precompiled.cpp delete mode 100644 Code/Tools/CryXML/CryXML_precompiled.h delete mode 100644 Code/Tools/CryXML/ICryXML.h delete mode 100644 Code/Tools/CryXML/IXMLSerializer.h delete mode 100644 Code/Tools/CryXML/XML/xml.cpp delete mode 100644 Code/Tools/CryXML/XML/xml.h delete mode 100644 Code/Tools/CryXML/XMLSerializer.cpp delete mode 100644 Code/Tools/CryXML/XMLSerializer.h delete mode 100644 Code/Tools/CryXML/cryxml_files.cmake delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/Bump2NormalHighQ.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha256512.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha512256.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/LuminanceOnly.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoPreset3DC_ddn.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8WithAlpha.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_bump.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_ddn.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings300400.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettingsGrey_DDNDIF.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings_DDNDIF.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQReduce1_ddn.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ_ddn.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/TestColorChart_cch.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/diamand_plate_ddn.tif.exportsettings delete mode 100644 Gems/Blast/Assets/.p4ignore delete mode 100644 Tools/AnimationTest/assetImportTest.bat delete mode 100644 Tools/DeepBandwidthToExcel/7z.exe delete mode 100644 Tools/DeepBandwidthToExcel/DeepBandwidthToExcel.exe delete mode 100644 Tools/DeepBandwidthToExcel/Template/[Content_Types].xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/_rels/.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/docProps/app.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/docProps/core.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/_rels/workbook.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/calcChain.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart1.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart2.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart3.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart4.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart5.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart6.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart7.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart8.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing1.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing2.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing3.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing4.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing5.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing6.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing7.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing8.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing1.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing2.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing3.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing4.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing5.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing6.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing7.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing8.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/sharedStrings.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/styles.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/theme/theme1.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/workbook.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet1.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet2.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet3.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet4.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet5.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet6.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet7.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet8.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet1.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet2.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet3.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet4.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet5.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet6.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet7.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet8.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet9.xml diff --git a/Code/.p4ignore b/Code/.p4ignore deleted file mode 100644 index f0b9f1ea6b..0000000000 --- a/Code/.p4ignore +++ /dev/null @@ -1,6 +0,0 @@ -#Ignore these directories -SDKs - -#ColinB (8/26)- I know there are depot files that this will ignore... But these files should not be -#here, they should all be in 3rdParty... so we will ignore them until I can move them, it should -#be OK for now because they shouldn't change at all anyway. diff --git a/Code/CryEngine/CryCommon/CMakeLists.txt b/Code/CryEngine/CryCommon/CMakeLists.txt index 5105ff1a5b..3a1eb90d9d 100644 --- a/Code/CryEngine/CryCommon/CMakeLists.txt +++ b/Code/CryEngine/CryCommon/CMakeLists.txt @@ -9,23 +9,15 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) -ly_get_pal_tool_dirs(pal_tool_dirs ${CMAKE_CURRENT_LIST_DIR}/Platform) - ly_add_target( NAME CryCommon STATIC NAMESPACE Legacy FILES_CMAKE crycommon_files.cmake - ${pal_dir}/crycommon_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake - PLATFORM_INCLUDE_FILES - ${pal_dir}/crycommon_${PAL_PLATFORM_NAME_LOWERCASE}.cmake INCLUDE_DIRECTORIES PUBLIC . # Lots of code without CryCommon/ .. # Dangerous since exports CryEngine's path (client code can do CrySystem/ without depending on that target) - ${pal_dir} - ${pal_tool_dirs} BUILD_DEPENDENCIES PUBLIC AZ::AzCore diff --git a/Code/CryEngine/CryCommon/Mocks/IMemoryManagerMock.h b/Code/CryEngine/CryCommon/Mocks/IMemoryManagerMock.h deleted file mode 100644 index 63df006e14..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/IMemoryManagerMock.h +++ /dev/null @@ -1,43 +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 - -class MemoryManagerMock - : public IMemoryManager -{ -public: - MOCK_METHOD1(GetProcessMemInfo, - bool(SProcessMemInfo& minfo)); - MOCK_METHOD3(TraceDefineHeap, - HeapHandle(const char* heapName, size_t size, const void* pBase)); - MOCK_METHOD6(TraceHeapAlloc, - void(HeapHandle heap, void* mem, size_t size, size_t blockSize, const char* sUsage, const char* sNameHint)); - MOCK_METHOD3(TraceHeapFree, - void(HeapHandle heap, void* mem, size_t blockSize)); - MOCK_METHOD1(TraceHeapSetColor, - void(uint32 color)); - MOCK_METHOD0(TraceHeapGetColor, - uint32()); - MOCK_METHOD1(TraceHeapSetLabel, - void(const char* sLabel)); - MOCK_METHOD1(CreateCustomMemoryHeapInstance, - ICustomMemoryHeap* const (EAllocPolicy const eAllocPolicy)); - MOCK_METHOD3(CreateGeneralExpandingMemoryHeap, - IGeneralMemoryHeap* (size_t upperLimit, size_t reserveSize, const char* sUsage)); - MOCK_METHOD3(CreateGeneralMemoryHeap, - IGeneralMemoryHeap* (void* base, size_t sz, const char* sUsage)); - MOCK_METHOD2(ReserveAddressRange, - IMemoryAddressRange* (size_t capacity, const char* sName)); - MOCK_METHOD2(CreatePageMappingHeap, - IPageMappingHeap* (size_t addressSpace, const char* sName)); -}; diff --git a/Code/CryEngine/CryCommon/Mocks/INetworkMock.h b/Code/CryEngine/CryCommon/Mocks/INetworkMock.h deleted file mode 100644 index b627f927bc..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/INetworkMock.h +++ /dev/null @@ -1,47 +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 - -struct NetworkMock : public INetwork -{ - NetworkMock() : m_gridMate(nullptr) - { - } - GridMate::IGridMate* m_gridMate; - - void Release() override {} - void GetMemoryStatistics([[maybe_unused]] ICrySizer* pSizer) override {} - void GetBandwidthStatistics([[maybe_unused]] SBandwidthStats* const pStats) override {} - void GetPerformanceStatistics([[maybe_unused]] SNetworkPerformance* pSizer) override {} - void GetProfilingStatistics([[maybe_unused]] SNetworkProfilingStats* const pStats) override {} - void SyncWithGame([[maybe_unused]] ENetworkGameSync syncType) override {} - const char* GetHostName() override { return "testhostname"; } - GridMate::IGridMate* GetGridMate() override - { - return m_gridMate; - } - ChannelId GetChannelIdForSessionMember([[maybe_unused]] GridMate::GridMember* member) const override { return ChannelId(); } - ChannelId GetServerChannelId() const override { return ChannelId(); } - ChannelId GetLocalChannelId() const override { return ChannelId(); } - CTimeValue GetSessionTime() override { return CTimeValue(); } - void ChangedAspects([[maybe_unused]] EntityId id, [[maybe_unused]] NetworkAspectType aspectBits) override {} - void SetDelegatableAspectMask([[maybe_unused]] NetworkAspectType aspectBits) override {} - void SetObjectDelegatedAspectMask([[maybe_unused]] EntityId entityId, [[maybe_unused]] NetworkAspectType aspects, [[maybe_unused]] bool set) override {} - void DelegateAuthorityToClient([[maybe_unused]] EntityId entityId, [[maybe_unused]] ChannelId clientChannelId) override {} - void InvokeActorRMI([[maybe_unused]] EntityId entityId, [[maybe_unused]] uint8 actorExtensionId, [[maybe_unused]] ChannelId targetChannelFilter, [[maybe_unused]] IActorRMIRep& rep) override {} - void InvokeScriptRMI([[maybe_unused]] ISerializable* serializable, [[maybe_unused]] bool isServerRMI, [[maybe_unused]] ChannelId toChannelId = kInvalidChannelId, [[maybe_unused]] ChannelId avoidChannelId = kInvalidChannelId) override {} - void RegisterActorRMI([[maybe_unused]] IActorRMIRep* rep) override {} - void UnregisterActorRMI([[maybe_unused]] IActorRMIRep* rep) override {} - EntityId LocalEntityIdToServerEntityId([[maybe_unused]] EntityId localId) const override { return EntityId(); } - EntityId ServerEntityIdToLocalEntityId([[maybe_unused]] EntityId serverId, [[maybe_unused]] bool allowForcedEstablishment = false) const override { return EntityId(); } -}; diff --git a/Code/CryEngine/CryCommon/Mocks/MockCGFContent.h b/Code/CryEngine/CryCommon/Mocks/MockCGFContent.h deleted file mode 100644 index 8047a863f6..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/MockCGFContent.h +++ /dev/null @@ -1,29 +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 MockIAssetWriter - : public IAssetWriter -{ -public: - ~MockIAssetWriter() override = default; - MOCK_METHOD1(WriteCGF, - bool(CContentCGF* content)); - MOCK_METHOD2(WriteCHR, - bool(CContentCGF* content, IConvertContext* convertContext)); - MOCK_METHOD3(WriteSKIN, - bool(CContentCGF* content, IConvertContext* convertContext, bool exportMorphTargets)); -}; diff --git a/Code/CryEngine/CryCommon/Platform/Android/crycommon_android.cmake b/Code/CryEngine/CryCommon/Platform/Android/crycommon_android.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Android/crycommon_android.cmake +++ /dev/null @@ -1,11 +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. -# - diff --git a/Code/CryEngine/CryCommon/Platform/Android/crycommon_android_files.cmake b/Code/CryEngine/CryCommon/Platform/Android/crycommon_android_files.cmake deleted file mode 100644 index 7b9245ae92..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Android/crycommon_android_files.cmake +++ /dev/null @@ -1,14 +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 - ../../WinBase.cpp -) diff --git a/Code/CryEngine/CryCommon/Platform/Android/crycommon_enginesettings_android_files.cmake b/Code/CryEngine/CryCommon/Platform/Android/crycommon_enginesettings_android_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Android/crycommon_enginesettings_android_files.cmake +++ /dev/null @@ -1,13 +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 -) diff --git a/Code/CryEngine/CryCommon/Platform/AppleTV/crycommon_appletv.cmake b/Code/CryEngine/CryCommon/Platform/AppleTV/crycommon_appletv.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/AppleTV/crycommon_appletv.cmake +++ /dev/null @@ -1,11 +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. -# - diff --git a/Code/CryEngine/CryCommon/Platform/Linux/crycommon_enginesettings_linux_files.cmake b/Code/CryEngine/CryCommon/Platform/Linux/crycommon_enginesettings_linux_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Linux/crycommon_enginesettings_linux_files.cmake +++ /dev/null @@ -1,13 +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 -) diff --git a/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux.cmake b/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux.cmake +++ /dev/null @@ -1,11 +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. -# - diff --git a/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux_files.cmake b/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux_files.cmake deleted file mode 100644 index 7b9245ae92..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux_files.cmake +++ /dev/null @@ -1,14 +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 - ../../WinBase.cpp -) diff --git a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac.cmake b/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac.cmake +++ /dev/null @@ -1,11 +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. -# - diff --git a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac_files.cmake b/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac_files.cmake deleted file mode 100644 index 7b9245ae92..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac_files.cmake +++ /dev/null @@ -1,14 +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 - ../../WinBase.cpp -) diff --git a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows.cmake b/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows.cmake +++ /dev/null @@ -1,11 +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. -# - diff --git a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows_files.cmake b/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows_files.cmake +++ /dev/null @@ -1,13 +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 -) diff --git a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_enginesettings_ios_files.cmake b/Code/CryEngine/CryCommon/Platform/iOS/crycommon_enginesettings_ios_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_enginesettings_ios_files.cmake +++ /dev/null @@ -1,13 +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 -) diff --git a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios.cmake b/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios.cmake +++ /dev/null @@ -1,11 +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. -# - diff --git a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios_files.cmake b/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios_files.cmake deleted file mode 100644 index 7b9245ae92..0000000000 --- a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios_files.cmake +++ /dev/null @@ -1,14 +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 - ../../WinBase.cpp -) diff --git a/Code/CryEngine/CryCommon/Terrain/Bus/HeightmapDataBus.h b/Code/CryEngine/CryCommon/Terrain/Bus/HeightmapDataBus.h deleted file mode 100644 index 93065e1196..0000000000 --- a/Code/CryEngine/CryCommon/Terrain/Bus/HeightmapDataBus.h +++ /dev/null @@ -1,102 +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 - -namespace Terrain -{ - class Viewport2D - { - public: - int m_topLeftX = 0; - int m_topLeftY = 0; - int m_width = 0; - int m_height = 0; - - Viewport2D() = default; - Viewport2D(const Viewport2D&) = default; - Viewport2D& operator=(const Viewport2D&) = default; - - Viewport2D(int topLeftX, int topLeftY, int width, int height) - : m_topLeftX(topLeftX) - , m_topLeftY(topLeftY) - , m_width(width) - , m_height(height) - { - } - }; - - // External height map data requests - class HeightmapDataRequestInfo - { - public: - HeightmapDataRequestInfo() = default; - HeightmapDataRequestInfo(const HeightmapDataRequestInfo& rhs) = default; - HeightmapDataRequestInfo& operator=(const HeightmapDataRequestInfo& rhs) = default; - - HeightmapDataRequestInfo(int viewportTopLeftX, int viewportTopLeftY, int viewportWidth, int viewportHeight, float metersPerPixel, AZ::Vector2 worldMin, AZ::Vector2 worldMax) - : m_viewport(viewportTopLeftX, viewportTopLeftY, viewportWidth, viewportHeight) - , m_metersPerPixel(metersPerPixel) - , m_worldMin(worldMin) - , m_worldMax(worldMax) - { - } - - float GetMetersPerPixel() const - { - return m_metersPerPixel; - } - - AZ::Vector2 GetWorldMin() const - { - return m_worldMin; - } - - AZ::Vector2 GetWorldMax() const - { - return m_worldMax; - } - - AZ::Vector2 GetWorldWidth() const - { - return (m_worldMax - m_worldMin); - } - - Viewport2D GetViewport() const - { - return m_viewport; - } - - private: - Viewport2D m_viewport; - AZ::Vector2 m_worldMin = AZ::Vector2(0.0f, 0.0f); - AZ::Vector2 m_worldMax = AZ::Vector2(0.0f, 0.0f); - float m_metersPerPixel = 1.0f; - }; - - class HeightmapDataNotifications - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - ////////////////////////////////////////////////////////////////////////// - - virtual void OnTerrainHeightDataChanged(const AZ::Aabb& dirtyRegion) = 0; - }; - using HeightmapDataNotificationBus = AZ::EBus; -} diff --git a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainBus.h b/Code/CryEngine/CryCommon/Terrain/Bus/TerrainBus.h deleted file mode 100644 index 2cfb5134c9..0000000000 --- a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainBus.h +++ /dev/null @@ -1,56 +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 CShader; - -namespace Terrain -{ - class TerrainDataRequests - : 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; - ////////////////////////////////////////////////////////////////////////// - - virtual float GetHeightSynchronous(float x, float y) = 0; - virtual AZ::Vector3 GetNormalSynchronous(float x, float y) = 0; - - virtual CShader* GetTerrainHeightGeneratorShader() const = 0; - virtual CShader* GetTerrainMaterialCompositingShader() const = 0; - }; - using TerrainDataRequestBus = AZ::EBus; - - class TerrainShaderRequests - : 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; - ////////////////////////////////////////////////////////////////////////// - - virtual void RefreshShader(const AZStd::string_view name, CShader* shader) = 0; - virtual void ReleaseShader(CShader* shader) const = 0; - }; - using TerrainShaderRequestBus = AZ::EBus; -} diff --git a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainProviderBus.h b/Code/CryEngine/CryCommon/Terrain/Bus/TerrainProviderBus.h deleted file mode 100644 index 6c1aca6ea7..0000000000 --- a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainProviderBus.h +++ /dev/null @@ -1,82 +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 - -#include "HeightmapDataBus.h" - -class CShader; - -namespace Terrain -{ - // This interface defines how the renderer can access the terrain system to set up state and gather information before rendering height maps - class TerrainProviderRequests - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - //! allows multiple threads to call - using MutexType = AZStd::recursive_mutex; - ////////////////////////////////////////////////////////////////////////// - - // world properties - virtual AZ::Vector3 GetWorldSize() = 0; - virtual AZ::Vector3 GetRegionSize() = 0; - virtual AZ::Vector3 GetWorldOrigin() = 0; - virtual AZ::Vector2 GetHeightRange() = 0; - - // utility - virtual void GetRegionIndex(const AZ::Vector2& worldMin, const AZ::Vector2& worldMax, int& regionIndexX, int& regionIndexY) = 0; - - virtual float GetHeightAtIndexedPosition([[maybe_unused]] int ix, [[maybe_unused]] int iy) { return 64.0f; } - virtual float GetHeightAtWorldPosition([[maybe_unused]] float fx, [[maybe_unused]] float fy) { return 64.0f; } - virtual unsigned char GetSurfaceTypeAtIndexedPosition([[maybe_unused]] int ix, [[maybe_unused]] int iy) { return 0; } - }; - using TerrainProviderRequestBus = AZ::EBus; - - // This class exists for the terrain system to inject data into the renderer for generating the GPU-side terrain height map - struct CRETerrainContext - { - // Tract map - virtual void OnTractVersionUpdate() = 0; - - CShader* m_currentShader = nullptr; - }; - - class TerrainProviderNotifications - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - //! allows multiple threads to call - using MutexType = AZStd::recursive_mutex; - ////////////////////////////////////////////////////////////////////////// - - // interface to be implemented by the game, invoked by the terrain render element - - // pull settings from the world cache, so the next accessors are accurate - virtual void SynchronizeSettings(CRETerrainContext* context) = 0; - }; - using TerrainProviderNotificationBus = AZ::EBus; -} diff --git a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainRendererBus.h b/Code/CryEngine/CryCommon/Terrain/Bus/TerrainRendererBus.h deleted file mode 100644 index ea644f5653..0000000000 --- a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainRendererBus.h +++ /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. -* -*/ - -#pragma once - -#include - -namespace Terrain -{ - class TerrainRendererRequests - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - ////////////////////////////////////////////////////////////////////////// - - //! allows multiple threads to call - using MutexType = AZStd::recursive_mutex; - - // Query state of the terrain renderer - // Returns true once the terrain renderer has fulfilled most data requests and is ready for rendering - virtual bool IsReady() = 0; - }; - using TerrainRendererRequestBus = AZ::EBus; -} diff --git a/Code/CryEngine/CryCommon/Terrain/Bus/WorldMaterialRequestsBus.h b/Code/CryEngine/CryCommon/Terrain/Bus/WorldMaterialRequestsBus.h deleted file mode 100644 index 3fb80f5f11..0000000000 --- a/Code/CryEngine/CryCommon/Terrain/Bus/WorldMaterialRequestsBus.h +++ /dev/null @@ -1,122 +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 - -struct IMaterial; -class ITexture; - -namespace Terrain -{ - struct MacroMaterial - { - // Textures - _smart_ptr m_macroColorMap = nullptr; - _smart_ptr m_macroGlossMap = nullptr; - _smart_ptr m_macroNormalMap = nullptr; - - // Material Params - AZ::Color m_macroColorMapColor; - float m_macroGlossMapScale = 1.0f; - float m_macroNormalMapScale = 1.0f; - float m_macroSpecReflectance = 0.03f; - - void Clear() - { - m_macroColorMap = nullptr; - m_macroGlossMap = nullptr; - m_macroNormalMap = nullptr; - - m_macroColorMapColor = AZ::Color(1.0f); - m_macroGlossMapScale = 1.0f; - m_macroNormalMapScale = 1.0f; - m_macroSpecReflectance = 0.03f; - } - }; - - struct TerrainMaterialLayer - { - _smart_ptr m_material = nullptr; - _smart_ptr m_splatTexture = nullptr; - - TerrainMaterialLayer(_smart_ptr material, _smart_ptr splatTexture) - : m_material(material) - , m_splatTexture(splatTexture) - { - } - }; - - struct RegionMaterials - { - MacroMaterial m_macroMaterial; - - AZStd::vector m_materialLayers; - _smart_ptr m_defaultMaterial = nullptr; - - RegionMaterials& operator=(const RegionMaterials& rhs) = default; - - void Clear() - { - m_materialLayers.clear(); - m_defaultMaterial = nullptr; - m_macroMaterial.Clear(); - } - }; - - const AZ::u32 kMaxRegionsPerTerrainMaterialRequest = 16; - typedef AZStd::pair RegionIndex; - typedef AZStd::fixed_vector RegionIndexVector; - typedef AZStd::fixed_vector RegionMaterialVector; - - enum class RequestResult - { - NoAssetsForRegion, - Loading, - Success - }; - - class WorldMaterialRequests - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - ////////////////////////////////////////////////////////////////////////// - - //! allows multiple threads to call - using MutexType = AZStd::recursive_mutex; - - virtual void LoadWorld(const AZStd::string& worldName, int regionSize) = 0; - - virtual RequestResult RequestRegionMaterials(const RegionIndexVector& regions, RegionMaterialVector& outRegionMaterials) = 0; - - // Parameters: - // int tileX, tileY : Region tile indices - // Returns: - // bool : If true, region material data is loaded and exists. outMacroMaterial will be modified with the respective macro material data - // If false, no region material data has been loaded or exists for the given tile (may still have invalid material layers). - virtual RequestResult GetMacroMaterial(int tileX, int tileY, MacroMaterial& outMacroMaterial) = 0; - - virtual void GetTerrainPOMParameters(float& pomHeightBias, float& pomDisplacement, float& selfShadowStrength) = 0; - - //Get the surface type at a given position. If not loaded yet, returns "loadingMaterial". - virtual AZStd::string_view GetSurfaceTypeAtPosition(AZ::Vector2 position) = 0; - }; - using WorldMaterialRequestBus = AZ::EBus; -} // namespace Terrain - diff --git a/Code/CryEngine/CryCommon/WinBase.cpp b/Code/CryEngine/CryCommon/WinBase.cpp index e6ea1cd4a8..47cb943240 100644 --- a/Code/CryEngine/CryCommon/WinBase.cpp +++ b/Code/CryEngine/CryCommon/WinBase.cpp @@ -12,6 +12,7 @@ // Original file Copyright Crytek GMBH or its affiliates, used under license. // Description : Linux/Mac port support for Win32API calls +#if !defined(WIN32) #include "platform.h" // Note: This should be first to get consistent debugging definitions @@ -1667,3 +1668,5 @@ __finddata64_t::~__finddata64_t() } } #endif //defined(APPLE) || defined(LINUX) + +#endif // !defined(WIN32) diff --git a/Code/CryEngine/CryCommon/crycommon_files.cmake b/Code/CryEngine/CryCommon/crycommon_files.cmake index 77b51825f1..dff4ca66e7 100644 --- a/Code/CryEngine/CryCommon/crycommon_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_files.cmake @@ -249,7 +249,6 @@ set(FILES platform_impl.cpp Win32specific.h Win64specific.h - stl/STLAlignedAlloc.h LyShine/IDraw2d.h LyShine/ILyShine.h LyShine/ISprite.h @@ -341,11 +340,7 @@ set(FILES Maestro/Types/AssetBlendKey.h Maestro/Types/AssetBlends.h Maestro/Types/SequenceType.h - Terrain/Bus/WorldMaterialRequestsBus.h - Terrain/Bus/TerrainBus.h - Terrain/Bus/TerrainRendererBus.h - Terrain/Bus/HeightmapDataBus.h - Terrain/Bus/TerrainProviderBus.h StaticInstance.h Pak/CryPakUtils.h + WinBase.cpp ) diff --git a/Code/CryEngine/CryCommon/crycommon_linux_files.cmake b/Code/CryEngine/CryCommon/crycommon_linux_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CryCommon/crycommon_linux_files.cmake +++ /dev/null @@ -1,13 +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 -) diff --git a/Code/CryEngine/CryCommon/crycommon_testing_files.cmake b/Code/CryEngine/CryCommon/crycommon_testing_files.cmake index d20a33f791..b94be27c3b 100644 --- a/Code/CryEngine/CryCommon/crycommon_testing_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_testing_files.cmake @@ -14,12 +14,10 @@ set(FILES Mocks/IConsoleMock.h Mocks/ICryPakMock.h Mocks/ILogMock.h - Mocks/IMemoryManagerMock.h Mocks/ISystemMock.h Mocks/ITimerMock.h Mocks/ICVarMock.h Mocks/IRendererMock.h Mocks/ITextureMock.h Mocks/IRemoteConsoleMock.h - Mocks/MockCGFContent.h ) diff --git a/Code/CryEngine/CryCommon/stl/STLAlignedAlloc.h b/Code/CryEngine/CryCommon/stl/STLAlignedAlloc.h deleted file mode 100644 index dc21cead81..0000000000 --- a/Code/CryEngine/CryCommon/stl/STLAlignedAlloc.h +++ /dev/null @@ -1,115 +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 : Implements an aligned allocator for STL -// based on the Mallocator (http://blogs.msdn.com/b/vcblog/archive/2008/08/28/the-mallocator.aspx) - -#pragma once - -#include // Required for size_t and ptrdiff_t and NULL - -#include - -namespace stl -{ - template - class AlignedAllocator - : public AZ::SimpleSchemaAllocator> - { - public: - AZ_TYPE_INFO(AlignedAllocator, "{DF152D8A-36ED-4A2A-9FA6-734F212716C6}"); - using Base = AZ::SimpleSchemaAllocator>; - using Descriptor = Base::Descriptor; - using Schema = AZ::ChildAllocatorSchema; - - AlignedAllocator() - : Base("AlignedAllocator", "Legacy Cry Aligned Allocator") - { - } - - pointer_type Allocate(size_type byteSize, size_type /*alignment*/, int flags /* = 0 */, const char* name /* = 0 */, const char* fileName /* = 0 */, int lineNum /* = 0 */, unsigned int suppressStackRecord /* = 0 */) override - { - return Base::Allocate(byteSize, Alignment, flags, name, fileName, lineNum, suppressStackRecord); - } - - void DeAllocate(pointer_type ptr, size_type byteSize, [[maybe_unused]] size_type alignment) override - { - return Base::DeAllocate(ptr, byteSize, Alignment); - } - - pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type /*newAlignment*/) override - { - return Base::ReAllocate(ptr, newSize, Alignment); - } - }; - - template - using aligned_alloc = AZ::AZStdAlloc>; - - ////////////////////////////////////////////////////////////////////////// - // Defines aligned vector type - ////////////////////////////////////////////////////////////////////////// - template - class aligned_vector - : public AZStd::vector > - { - public: - typedef aligned_alloc MyAlloc; - typedef AZStd::vector MySuperClass; - typedef aligned_vector MySelf; - typedef size_t size_type; - - aligned_vector() {} - explicit aligned_vector(const MyAlloc& _Al) - : MySuperClass(_Al) {} - explicit aligned_vector(size_type _Count) - : MySuperClass(_Count) {}; - aligned_vector(size_type _Count, const T& _Val) - : MySuperClass(_Count, _Val) {} - aligned_vector(size_type _Count, const T& _Val, const MyAlloc& _Al) - : MySuperClass(_Count, _Val) {} - aligned_vector(const MySelf& _Right) - : MySuperClass(_Right) {}; - - - template - aligned_vector(_Iter _First, _Iter _Last) - : MySuperClass(_First, _Last) {}; - - template - aligned_vector(_Iter _First, _Iter _Last, const MyAlloc& _Al) - : MySuperClass(_First, _Last, _Al) {}; - }; - - template - inline size_t size_of_aligned_vector(const Vec& c) - { - if (!c.empty()) - { - // Not really correct as not taking alignment into the account - return c.capacity() * sizeof(typename Vec::value_type); - } - return 0; - } -} // namespace stl - -// Specialize for the AlignedAllocator to provide one per module that does not use the -// environment for its storage. Since this allocator just uses LegacyAllocator -// to do the real work, it's fine if there is one of these per cry module -namespace AZ -{ - template - class AllocatorInstance> : public Internal::AllocatorInstanceBase, AllocatorStorage::ModuleStoragePolicy>> - { - }; -} diff --git a/Code/CryEngine/CrySystem/Tests/Test_CryPrimitives.cpp b/Code/CryEngine/CrySystem/Tests/Test_CryPrimitives.cpp index 2e6e646548..26d12ffd8c 100644 --- a/Code/CryEngine/CrySystem/Tests/Test_CryPrimitives.cpp +++ b/Code/CryEngine/CrySystem/Tests/Test_CryPrimitives.cpp @@ -12,7 +12,6 @@ #include "CrySystem_precompiled.h" #include #include -#include TEST(StringTests, CUT_Strings) { @@ -424,21 +423,6 @@ TEST_F(CryPrimitives, CUT_FixedString) EXPECT_EQ("0123", str5); } -////////////////////////////////////////////////////////////////////////// -// Unit Testing of aligned_vector -////////////////////////////////////////////////////////////////////////// -TEST_F(CryPrimitives, CUT_AlignedVector) -{ - stl::aligned_vector vec; - - vec.push_back(1); - vec.push_back(2); - vec.push_back(3); - - EXPECT_TRUE(vec.size() == 3); - EXPECT_TRUE(((INT_PTR)(&vec[0]) % 16) == 0); -} - TEST_F(CryPrimitives, CUT_DynArray) { LegacyDynArray a; diff --git a/Code/Framework/AtomCore/.p4ignore b/Code/Framework/AtomCore/.p4ignore deleted file mode 100644 index 6722cd96e7..0000000000 --- a/Code/Framework/AtomCore/.p4ignore +++ /dev/null @@ -1 +0,0 @@ -*.xml diff --git a/Code/Framework/AzCore/.p4ignore b/Code/Framework/AzCore/.p4ignore deleted file mode 100644 index 6722cd96e7..0000000000 --- a/Code/Framework/AzCore/.p4ignore +++ /dev/null @@ -1 +0,0 @@ -*.xml diff --git a/Code/Sandbox/.p4ignore b/Code/Sandbox/.p4ignore deleted file mode 100644 index 9c6b6fcd91..0000000000 --- a/Code/Sandbox/.p4ignore +++ /dev/null @@ -1,5 +0,0 @@ -#Ignore these directories -SDKs - -#ignore these files -*.user diff --git a/Code/Tools/CMakeLists.txt b/Code/Tools/CMakeLists.txt index db5476756b..278474819c 100644 --- a/Code/Tools/CMakeLists.txt +++ b/Code/Tools/CMakeLists.txt @@ -15,7 +15,6 @@ add_subdirectory(AWSNativeSDKInit) add_subdirectory(AzTestRunner) add_subdirectory(CrashHandler) add_subdirectory(CryCommonTools) -add_subdirectory(CryXML) add_subdirectory(News) add_subdirectory(PythonBindingsExample) add_subdirectory(RemoteConsole) diff --git a/Code/Tools/CryCommonTools/CMakeLists.txt b/Code/Tools/CryCommonTools/CMakeLists.txt index 0188506e97..63f535b1af 100644 --- a/Code/Tools/CryCommonTools/CMakeLists.txt +++ b/Code/Tools/CryCommonTools/CMakeLists.txt @@ -13,44 +13,18 @@ if (NOT PAL_TRAIT_BUILD_HOST_TOOLS) return() endif() -ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) - ly_add_target( NAME CryCommonTools STATIC NAMESPACE Legacy FILES_CMAKE crycommontools_files.cmake - ${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake INCLUDE_DIRECTORIES PUBLIC . - ${pal_dir} BUILD_DEPENDENCIES PRIVATE - 3rdParty::lz4 - 3rdParty::zlib - 3rdParty::zstd AZ::AzCore PUBLIC Legacy::CryCommon AZ::AzFramework ) - -if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) - ly_add_target( - NAME CryCommonTools.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} - NAMESPACE Legacy - FILES_CMAKE - crycommontools_tests_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - UnitTests - BUILD_DEPENDENCIES - PRIVATE - Legacy::CryCommonTools - AZ::AzTest - ) - ly_add_googletest( - NAME Legacy::CryCommonTools.Tests - ) -endif() diff --git a/Code/Tools/CryCommonTools/ColladaShared.h b/Code/Tools/CryCommonTools/ColladaShared.h deleted file mode 100644 index edc8341fe1..0000000000 --- a/Code/Tools/CryCommonTools/ColladaShared.h +++ /dev/null @@ -1,18 +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_CRYCOMMONTOOLS_COLLADASHARED_H -#define CRYINCLUDE_CRYCOMMONTOOLS_COLLADASHARED_H -#pragma once - -static const char* g_LumberyardExportNodeTag = "LumberyardExportNode"; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_COLLADASHARED_H diff --git a/Code/Tools/CryCommonTools/Decompose.cpp b/Code/Tools/CryCommonTools/Decompose.cpp deleted file mode 100644 index 3cf88db251..0000000000 --- a/Code/Tools/CryCommonTools/Decompose.cpp +++ /dev/null @@ -1,514 +0,0 @@ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include - -// Taken from http://tog.acm.org/GraphicsGems/gemsiv/polar_decomp/Decompose.c - -/**** Decompose.c ****/ -/* Ken Shoemake, 1993 */ -#include -#include "Decompose.h" - -#pragma warning(disable:4244) // conversion from 'double' to 'float', possible loss of data -#pragma warning(disable:4305) // 'initializing' : truncation from 'double' to 'float' - -namespace decomp { - - /******* Matrix Preliminaries *******/ - - /** Fill out 3x3 matrix to 4x4 **/ -#define mat_pad(A) (A[W][X]=A[X][W]=A[W][Y]=A[Y][W]=A[W][Z]=A[Z][W]=0,A[W][W]=1) - -/** Copy nxn matrix A to C using "gets" for assignment **/ -#define mat_copy(C,gets,A,n) {int i,j; for(i=0;i= 0.0) { - s = sqrt(tr + mat[W][W]); - qu.w = s * 0.5; - s = 0.5 / s; - qu.x = (mat[Z][Y] - mat[Y][Z]) * s; - qu.y = (mat[X][Z] - mat[Z][X]) * s; - qu.z = (mat[Y][X] - mat[X][Y]) * s; - } else { - int h = X; - if (mat[Y][Y] > mat[X][X]) h = Y; - if (mat[Z][Z] > mat[h][h]) h = Z; - switch (h) { -#define caseMacro(i,j,k,I,J,K) \ - case I:\ - s = sqrt( (mat[I][I] - (mat[J][J]+mat[K][K])) + mat[W][W] );\ - qu.i = s*0.5;\ - s = 0.5 / s;\ - qu.j = (mat[I][J] + mat[J][I]) * s;\ - qu.k = (mat[K][I] + mat[I][K]) * s;\ - qu.w = (mat[K][J] - mat[J][K]) * s;\ - break - caseMacro(x, y, z, X, Y, Z); - caseMacro(y, z, x, Y, Z, X); - caseMacro(z, x, y, Z, X, Y); - } - } - if (mat[W][W] != 1.0) qu = Qt_Scale(qu, 1 / sqrt(mat[W][W])); - return (qu); - } - /******* Decomp Auxiliaries *******/ - - static HMatrix mat_id = { {1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1} }; - - /** Compute either the 1 or infinity norm of M, depending on tpose **/ - float mat_norm(HMatrix M, int tpose) - { - int i; - float sum, max; - max = 0.0; - for (i = 0; i < 3; i++) { - if (tpose) sum = fabs(M[0][i]) + fabs(M[1][i]) + fabs(M[2][i]); - else sum = fabs(M[i][0]) + fabs(M[i][1]) + fabs(M[i][2]); - if (max < sum) max = sum; - } - return max; - } - - float norm_inf(HMatrix M) { return mat_norm(M, 0); } - float norm_one(HMatrix M) { return mat_norm(M, 1); } - - /** Return index of column of M containing maximum abs entry, or -1 if M=0 **/ - int find_max_col(HMatrix M) - { - float abs, max; - int i, j, col; - max = 0.0; col = -1; - for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { - abs = M[i][j]; if (abs < 0.0) abs = -abs; - if (abs > max) { max = abs; col = j; } - } - return col; - } - - /** Setup u for Household reflection to zero all v components but first **/ - void make_reflector(float* v, float* u) - { - float s = sqrt(vdot(v, v)); - u[0] = v[0]; u[1] = v[1]; - u[2] = v[2] + ((v[2] < 0.0) ? -s : s); - s = sqrt(2.0 / vdot(u, u)); - u[0] = u[0] * s; u[1] = u[1] * s; u[2] = u[2] * s; - } - - /** Apply Householder reflection represented by u to column vectors of M **/ - void reflect_cols(HMatrix M, float* u) - { - int i, j; - for (i = 0; i < 3; i++) { - float s = u[0] * M[0][i] + u[1] * M[1][i] + u[2] * M[2][i]; - for (j = 0; j < 3; j++) M[j][i] -= u[j] * s; - } - } - /** Apply Householder reflection represented by u to row vectors of M **/ - void reflect_rows(HMatrix M, float* u) - { - int i, j; - for (i = 0; i < 3; i++) { - float s = vdot(u, M[i]); - for (j = 0; j < 3; j++) M[i][j] -= u[j] * s; - } - } - - /** Find orthogonal factor Q of rank 1 (or less) M **/ - void do_rank1(HMatrix M, HMatrix Q) - { - float v1[3], v2[3], s; - int col; - mat_copy(Q, =, mat_id, 4); - /* If rank(M) is 1, we should find a non-zero column in M */ - col = find_max_col(M); - if (col < 0) return; /* Rank is 0 */ - v1[0] = M[0][col]; v1[1] = M[1][col]; v1[2] = M[2][col]; - make_reflector(v1, v1); reflect_cols(M, v1); - v2[0] = M[2][0]; v2[1] = M[2][1]; v2[2] = M[2][2]; - make_reflector(v2, v2); reflect_rows(M, v2); - s = M[2][2]; - if (s < 0.0) Q[2][2] = -1.0; - reflect_cols(Q, v1); reflect_rows(Q, v2); - } - - /** Find orthogonal factor Q of rank 2 (or less) M using adjoint transpose **/ - void do_rank2(HMatrix M, HMatrix MadjT, HMatrix Q) - { - float v1[3], v2[3]; - float w, x, y, z, c, s, d; - int col; - /* If rank(M) is 2, we should find a non-zero column in MadjT */ - col = find_max_col(MadjT); - if (col < 0) { do_rank1(M, Q); return; } /* Rank<2 */ - v1[0] = MadjT[0][col]; v1[1] = MadjT[1][col]; v1[2] = MadjT[2][col]; - make_reflector(v1, v1); reflect_cols(M, v1); - vcross(M[0], M[1], v2); - make_reflector(v2, v2); reflect_rows(M, v2); - w = M[0][0]; x = M[0][1]; y = M[1][0]; z = M[1][1]; - if (w * z > x* y) { - c = z + w; s = y - x; d = sqrt(c * c + s * s); c = c / d; s = s / d; - Q[0][0] = Q[1][1] = c; Q[0][1] = -(Q[1][0] = s); - } else { - c = z - w; s = y + x; d = sqrt(c * c + s * s); c = c / d; s = s / d; - Q[0][0] = -(Q[1][1] = c); Q[0][1] = Q[1][0] = s; - } - Q[0][2] = Q[2][0] = Q[1][2] = Q[2][1] = 0.0; Q[2][2] = 1.0; - reflect_cols(Q, v1); reflect_rows(Q, v2); - } - - - /******* Polar Decomposition *******/ - - /* Polar Decomposition of 3x3 matrix in 4x4, - * M = QS. See Nicholas Higham and Robert S. Schreiber, - * Fast Polar Decomposition of An Arbitrary Matrix, - * Technical Report 88-942, October 1988, - * Department of Computer Science, Cornell University. - */ - float polar_decomp(HMatrix M, HMatrix Q, HMatrix S) - { -#define TOL 1.0e-6 - HMatrix Mk, MadjTk, Ek; - float det, M_one, M_inf, MadjT_one, MadjT_inf, E_one, gamma, g1, g2; - int i, j; - mat_tpose(Mk, =, M, 3); - M_one = norm_one(Mk); M_inf = norm_inf(Mk); - do { - adjoint_transpose(Mk, MadjTk); - det = vdot(Mk[0], MadjTk[0]); - if (det == 0.0) { do_rank2(Mk, MadjTk, Mk); break; } - MadjT_one = norm_one(MadjTk); MadjT_inf = norm_inf(MadjTk); - gamma = sqrt(sqrt((MadjT_one * MadjT_inf) / (M_one * M_inf)) / fabs(det)); - g1 = gamma * 0.5; - g2 = 0.5 / (gamma * det); - mat_copy(Ek, =, Mk, 3); - mat_binop(Mk, =, g1 * Mk, +, g2 * MadjTk, 3); - mat_copy(Ek, -=, Mk, 3); - E_one = norm_one(Ek); - M_one = norm_one(Mk); M_inf = norm_inf(Mk); - } while (E_one > (M_one * TOL)); - mat_tpose(Q, =, Mk, 3); mat_pad(Q); - mat_mult(Mk, M, S); mat_pad(S); - for (i = 0; i < 3; i++) for (j = i; j < 3; j++) - S[i][j] = S[j][i] = 0.5 * (S[i][j] + S[j][i]); - return (det); - } - - - - - - - - - - - - - - - - - - /******* Spectral Decomposition *******/ - - /* Compute the spectral decomposition of symmetric positive semi-definite S. - * Returns rotation in U and scale factors in result, so that if K is a diagonal - * matrix of the scale factors, then S = U K (U transpose). Uses Jacobi method. - * See Gene H. Golub and Charles F. Van Loan. Matrix Computations. Hopkins 1983. - */ - HVect spect_decomp(HMatrix S, HMatrix U) - { - HVect kv; - double Diag[3], OffD[3]; /* OffD is off-diag (by omitted index) */ - double g, h, fabsh, fabsOffDi, t, theta, c, s, tau, ta, OffDq, a, b; - static char nxt[] = { Y,Z,X }; - int sweep, i, j; - mat_copy(U, =, mat_id, 4); - Diag[X] = S[X][X]; Diag[Y] = S[Y][Y]; Diag[Z] = S[Z][Z]; - OffD[X] = S[Y][Z]; OffD[Y] = S[Z][X]; OffD[Z] = S[X][Y]; - for (sweep = 20; sweep > 0; sweep--) { - float sm = fabs(OffD[X]) + fabs(OffD[Y]) + fabs(OffD[Z]); - if (sm == 0.0) break; - for (i = Z; i >= X; i--) { - int p = nxt[i]; int q = nxt[p]; - fabsOffDi = fabs(OffD[i]); - g = 100.0 * fabsOffDi; - if (fabsOffDi > 0.0) { - h = Diag[q] - Diag[p]; - fabsh = fabs(h); - if (fabsh + g == fabsh) { - t = OffD[i] / h; - } else { - theta = 0.5 * h / OffD[i]; - t = 1.0 / (fabs(theta) + sqrt(theta * theta + 1.0)); - if (theta < 0.0) t = -t; - } - c = 1.0 / sqrt(t * t + 1.0); s = t * c; - tau = s / (c + 1.0); - ta = t * OffD[i]; OffD[i] = 0.0; - Diag[p] -= ta; Diag[q] += ta; - OffDq = OffD[q]; - OffD[q] -= s * (OffD[p] + tau * OffD[q]); - OffD[p] += s * (OffDq - tau * OffD[p]); - for (j = Z; j >= X; j--) { - a = U[j][p]; b = U[j][q]; - U[j][p] -= s * (b + tau * a); - U[j][q] += s * (a - tau * b); - } - } - } - } - kv.x = Diag[X]; kv.y = Diag[Y]; kv.z = Diag[Z]; kv.w = 1.0; - return (kv); - } - - /******* Spectral Axis Adjustment *******/ - - /* Given a unit quaternion, q, and a scale vector, k, find a unit quaternion, p, - * which permutes the axes and turns freely in the plane of duplicate scale - * factors, such that q p has the largest possible w component, i.e. the - * smallest possible angle. Permutes k's components to go with q p instead of q. - * See Ken Shoemake and Tom Duff. Matrix Animation and Polar Decomposition. - * Proceedings of Graphics Interface 1992. Details on p. 262-263. - */ - Quat snuggle(Quat q, HVect* k) - { -#define SQRTHALF (0.7071067811865475244f) -#define sgn(n,v) ((n)?-(v):(v)) -#define swap(a,i,j) {a[3]=a[i]; a[i]=a[j]; a[j]=a[3];} -#define cycle(a,p) if (p) {a[3]=a[0]; a[0]=a[1]; a[1]=a[2]; a[2]=a[3];}\ - else {a[3]=a[2]; a[2]=a[1]; a[1]=a[0]; a[0]=a[3];} - Quat p; - float ka[4]; - int i, turn = -1; - ka[X] = k->x; ka[Y] = k->y; ka[Z] = k->z; - if (ka[X] == ka[Y]) { if (ka[X] == ka[Z]) turn = W; else turn = Z; } - else { if (ka[X] == ka[Z]) turn = Y; else if (ka[Y] == ka[Z]) turn = X; } - if (turn >= 0) { - Quat qtoz, qp; - unsigned neg[3], win; - double mag[3], t; - static Quat qxtoz = { 0,SQRTHALF,0,SQRTHALF }; - static Quat qytoz = { SQRTHALF,0,0,SQRTHALF }; - static Quat qppmm = { 0.5, 0.5,-0.5,-0.5 }; - static Quat qpppp = { 0.5, 0.5, 0.5, 0.5 }; - static Quat qmpmm = { -0.5, 0.5,-0.5,-0.5 }; - static Quat qpppm = { 0.5, 0.5, 0.5,-0.5 }; - static Quat q0001 = { 0.0, 0.0, 0.0, 1.0 }; - static Quat q1000 = { 1.0, 0.0, 0.0, 0.0 }; - switch (turn) { - default: return (Qt_Conj(q)); - case X: q = Qt_Mul(q, qtoz = qxtoz); swap(ka, X, Z) break; - case Y: q = Qt_Mul(q, qtoz = qytoz); swap(ka, Y, Z) break; - case Z: qtoz = q0001; break; - } - q = Qt_Conj(q); - mag[0] = (double)q.z * q.z + (double)q.w * q.w - 0.5; - mag[1] = (double)q.x * q.z - (double)q.y * q.w; - mag[2] = (double)q.y * q.z + (double)q.x * q.w; - for (i = 0; i < 3; i++) if (neg[i] = (mag[i] < 0.0)) mag[i] = -mag[i]; - if (mag[0] > mag[1]) { if (mag[0] > mag[2]) win = 0; else win = 2; } - else { if (mag[1] > mag[2]) win = 1; else win = 2; } - switch (win) { - case 0: if (neg[0]) p = q1000; else p = q0001; break; - case 1: if (neg[1]) p = qppmm; else p = qpppp; cycle(ka, 0) break; - case 2: if (neg[2]) p = qmpmm; else p = qpppm; cycle(ka, 1) break; - } - qp = Qt_Mul(q, p); - t = sqrt(mag[win] + 0.5); - p = Qt_Mul(p, Qt_(0.0, 0.0, -qp.z / t, qp.w / t)); - p = Qt_Mul(qtoz, Qt_Conj(p)); - } else { - float qa[4], pa[4]; - unsigned lo, hi, neg[4], par = 0; - double all, big, two; - qa[0] = q.x; qa[1] = q.y; qa[2] = q.z; qa[3] = q.w; - for (i = 0; i < 4; i++) { - pa[i] = 0.0; - if (neg[i] = (qa[i] < 0.0)) qa[i] = -qa[i]; - par ^= neg[i]; - } - /* Find two largest components, indices in hi and lo */ - if (qa[0] > qa[1]) lo = 0; else lo = 1; - if (qa[2] > qa[3]) hi = 2; else hi = 3; - if (qa[lo] > qa[hi]) { - if (qa[lo ^ 1] > qa[hi]) { hi = lo; lo ^= 1; } - else { hi ^= lo; lo ^= hi; hi ^= lo; } - } else {if (qa[hi^1]>qa[lo]) lo = hi^1;} - all = (qa[0] + qa[1] + qa[2] + qa[3]) * 0.5; - two = (qa[hi] + qa[lo]) * SQRTHALF; - big = qa[hi]; - if (all > two) { - if (all > big) {/*all*/ - {int i; for (i = 0; i < 4; i++) pa[i] = sgn(neg[i], 0.5); } - cycle(ka, par) - } else {/*big*/ pa[hi] = sgn(neg[hi],1.0);} - } else { - if (two > big) {/*two*/ - pa[hi] = sgn(neg[hi], SQRTHALF); pa[lo] = sgn(neg[lo], SQRTHALF); - if (lo > hi) { hi ^= lo; lo ^= hi; hi ^= lo; } - if (hi == W) { hi = "\001\002\000"[lo]; lo = 3 - hi - lo; } - swap(ka, hi, lo) - } else {/*big*/ pa[hi] = sgn(neg[hi],1.0);} - } - p.x = -pa[0]; p.y = -pa[1]; p.z = -pa[2]; p.w = pa[3]; - } - k->x = ka[X]; k->y = ka[Y]; k->z = ka[Z]; - return (p); - } - - - - - - - - - - - - /******* Decompose Affine Matrix *******/ - - /* Decompose 4x4 affine matrix A as TFRUK(U transpose), where t contains the - * translation components, q contains the rotation R, u contains U, k contains - * scale factors, and f contains the sign of the determinant. - * Assumes A transforms column vectors in right-handed coordinates. - * See Ken Shoemake and Tom Duff. Matrix Animation and Polar Decomposition. - * Proceedings of Graphics Interface 1992. - */ - void decomp_affine(HMatrix A, AffineParts* parts) - { - HMatrix Q, S, U; - Quat p; - float det; - parts->t = Qt_(A[X][W], A[Y][W], A[Z][W], 0); - det = polar_decomp(A, Q, S); - if (det < 0.0) { - mat_copy(Q, =, -Q, 3); - parts->f = -1; - } else parts->f = 1; - parts->q = Qt_FromMatrix(Q); - parts->k = spect_decomp(S, U); - parts->u = Qt_FromMatrix(U); - p = snuggle(parts->u, &parts->k); - parts->u = Qt_Mul(parts->u, p); - } - - /******* Invert Affine Decomposition *******/ - - /* Compute inverse of affine decomposition. - */ - void invert_affine(AffineParts* parts, AffineParts* inverse) - { - Quat t, p; - inverse->f = parts->f; - inverse->q = Qt_Conj(parts->q); - inverse->u = Qt_Mul(parts->q, parts->u); - inverse->k.x = (parts->k.x == 0.0) ? 0.0 : 1.0 / parts->k.x; - inverse->k.y = (parts->k.y == 0.0) ? 0.0 : 1.0 / parts->k.y; - inverse->k.z = (parts->k.z == 0.0) ? 0.0 : 1.0 / parts->k.z; - inverse->k.w = parts->k.w; - t = Qt_(-parts->t.x, -parts->t.y, -parts->t.z, 0); - t = Qt_Mul(Qt_Conj(inverse->u), Qt_Mul(t, inverse->u)); - t = Qt_(inverse->k.x * t.x, inverse->k.y * t.y, inverse->k.z * t.z, 0); - p = Qt_Mul(inverse->q, inverse->u); - t = Qt_Mul(p, Qt_Mul(t, Qt_Conj(p))); - inverse->t = (inverse->f > 0.0) ? t : Qt_(-t.x, -t.y, -t.z, 0); - } - -} diff --git a/Code/Tools/CryCommonTools/Decompose.h b/Code/Tools/CryCommonTools/Decompose.h deleted file mode 100644 index 88e04737b6..0000000000 --- a/Code/Tools/CryCommonTools/Decompose.h +++ /dev/null @@ -1,30 +0,0 @@ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -namespace decomp { -// Taken from http://tog.acm.org/GraphicsGems/gemsiv/polar_decomp/Decompose.h - -/**** Decompose.h - Basic declarations ****/ -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_DECOMPOSE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_DECOMPOSE_H -#pragma once - -typedef struct {float x, y, z, w;} Quat; /* Quaternion */ -enum QuatPart {X, Y, Z, W}; -typedef Quat HVect; /* Homogeneous 3D vector */ -typedef float HMatrix[4][4]; /* Right-handed, for column vectors */ -typedef struct { - HVect t; /* Translation components */ - Quat q; /* Essential rotation */ - Quat u; /* Stretch rotation */ - HVect k; /* Stretch factors */ - float f; /* Sign of determinant */ -} AffineParts; -float polar_decomp(HMatrix M, HMatrix Q, HMatrix S); -HVect spect_decomp(HMatrix S, HMatrix U); -Quat snuggle(Quat q, HVect *k); -void decomp_affine(HMatrix A, AffineParts *parts); -void invert_affine(AffineParts *parts, AffineParts *inverse); - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_DECOMPOSE_H - -} diff --git a/Code/Tools/CryCommonTools/Exceptions.h b/Code/Tools/CryCommonTools/Exceptions.h deleted file mode 100644 index cc8830f0dd..0000000000 --- a/Code/Tools/CryCommonTools/Exceptions.h +++ /dev/null @@ -1,43 +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_CRYCOMMONTOOLS_EXCEPTIONS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXCEPTIONS_H -#pragma once - - -#include -#include - -class BaseException - : public std::exception -{ -public: - BaseException(const string& msg) - : msg(msg) {} - virtual const char* what() const throw () {return msg.c_str(); } - -private: - string msg; -}; - -template -class Exception - : public BaseException -{ -public: - Exception(const string& msg) - : BaseException(msg) {} -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXCEPTIONS_H diff --git a/Code/Tools/CryCommonTools/FileUtil.cpp b/Code/Tools/CryCommonTools/FileUtil.cpp deleted file mode 100644 index d42a60bcc2..0000000000 --- a/Code/Tools/CryCommonTools/FileUtil.cpp +++ /dev/null @@ -1,175 +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 -#include "FileUtil.h" -#include "PathHelpers.h" -#include "StringHelpers.h" - -#include -#include - - -////////////////////////////////////////////////////////////////////////// -// returns true if 'dir' is a subdirectory of 'baseDir' or same directory as 'baseDir' -// note: returns false in case of wrong names passed -static bool IsSubdirOrSameDir(const char* dir, const char* baseDir) -{ - - AZ::IO::LocalFileIO localFileIO; - - char szFullPathDir[AZ_MAX_PATH_LEN]; - if(!localFileIO.ConvertToAbsolutePath(dir, szFullPathDir, sizeof(szFullPathDir))) - { - return false; - } - - char szFullPathBaseDir[2 * 1024]; - if(!localFileIO.ConvertToAbsolutePath(baseDir, szFullPathBaseDir, sizeof(szFullPathBaseDir))) - { - return false; - } - - const char* p = szFullPathDir; - const char* q = szFullPathBaseDir; - for (;; ++p, ++q) - { - if (tolower(*p) == tolower(*q)) - { - if (*p == 0) - { - // dir is exactly same as baseDir - return true; - } - continue; - } - - if ((*p == '/' || *p == '\\') && (*q == '/' || *q == '\\')) - { - continue; - } - - if (*p == 0) - { - // dir length is shorter than baseDir length. so it's not a subdir - return false; - } - - if (*q == 0) - { - // baseDir is shorter than dir. so may be it's a subdir. - const bool isSubdir = (*p == '/' || *p == '\\'); - return isSubdir; - } - - return false; - } -} - -////////////////////////////////////////////////////////////////////////// -// the paths must have trailing slash -static bool ScanDirectoryRecursive(const string& root, const string& path, const string& file, std::vector& files, bool recursive, const string& dirToIgnore) -{ - bool anyFound = false; - if (!dirToIgnore.empty()) - { - if (IsSubdirOrSameDir(root.c_str(), dirToIgnore.c_str())) - { - return anyFound; - } - } - - AZ::IO::LocalFileIO localFileIO; - localFileIO.FindFiles(root.c_str(), file.c_str(), [&](const char* filePath) -> bool - { - bool isDir = localFileIO.IsDirectory(filePath); - if (!isDir) - { - const string foundFilename(filePath); - if (StringHelpers::MatchesWildcardsIgnoreCase(foundFilename, file)) - { - anyFound = true; - files.push_back(PathHelpers::Join(path, PathHelpers::GetFilename(filePath))); - } - } - - return true; // Keep iterating - }); - - if (recursive) - { - localFileIO.FindFiles(root.c_str(), "*", [&](const char* filePath) -> bool - { - bool isDir = localFileIO.IsDirectory(filePath); - // If recursive. - if (isDir && strcmp(filePath, ".") && strcmp(filePath, "..")) - { - if (ScanDirectoryRecursive(filePath, PathHelpers::Join(path, PathHelpers::GetFilename(filePath)), file, files, recursive, dirToIgnore)) - { - anyFound = true; - } - } - return true; // Keep iterating - }); - } - - return anyFound; -} - -////////////////////////////////////////////////////////////////////////// - -bool FileUtil::ScanDirectory(const string& path, const string& file, std::vector& files, bool recursive, const string& dirToIgnore) -{ - return ScanDirectoryRecursive(path, "", file, files, recursive, dirToIgnore); -} - - -bool FileUtil::EnsureDirectoryExists(const char* szPathIn) -{ - if (!szPathIn || !szPathIn[0]) - { - return true; - } - - if (DirectoryExists(szPathIn)) - { - return true; - } - - std::vector path(szPathIn, szPathIn + strlen(szPathIn) + 1); - char* p = &path[0]; - - // Skip '/' and '//' in the beginning - while (*p == '/' || *p == '\\') - { - ++p; - } - - for (;; ) - { - while (*p != '/' && *p != '\\' && *p) - { - ++p; - } - const char saved = *p; - *p = 0; - AZ::IO::LocalFileIO().CreatePath(&path[0]); - *p++ = saved; - if (saved == 0) - { - break; - } - } - - return DirectoryExists(szPathIn); -} diff --git a/Code/Tools/CryCommonTools/FileUtil.h b/Code/Tools/CryCommonTools/FileUtil.h deleted file mode 100644 index cf258c074b..0000000000 --- a/Code/Tools/CryCommonTools/FileUtil.h +++ /dev/null @@ -1,311 +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_CRYCOMMONTOOLS_FILEUTIL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_FILEUTIL_H -#pragma once - -#include -#include - -#include - -#if AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX) -#include -#endif -#if defined(AZ_PLATFORM_LINUX) -#include "Linux64Specific.h" -#endif // defined(AZ_PLATFORM_LINUX) - -#include -#include - -namespace FileUtil -{ - // Magic number explanation: - // Both epochs are Gregorian. 1970 - 1601 = 369. Assuming a leap - // year every four years, 369 / 4 = 92. However, 1700, 1800, and 1900 - // were NOT leap years, so 89 leap years, 280 non-leap years. - // 89 * 366 + 280 * 365 = 134744 days between epochs. Of course - // 60 * 60 * 24 = 86400 seconds per day, so 134744 * 86400 = - // 11644473600 = SECS_BETWEEN_EPOCHS. - // - // This result is also confirmed in the MSDN documentation on how - // to convert a time_t value to a win32 FILETIME. - #define SECS_BETWEEN_EPOCHS 11644473600ll - /* 10^7 */ - #define SECS_TO_100NS 10000000ll - - // Find all files matching filespec. - bool ScanDirectory(const string& path, const string& filespec, std::vector& files, bool recursive, const string& dirToIgnore); - - // Ensures that directory specified by szPathIn exists by creating all needed (sub-)directories. - // Returns false in case of a failure. - // Example: "c:\temp\test" ("c:\temp\test\" also works) - ensures that "c:\temp\test" exists. - bool EnsureDirectoryExists(const char* szPathIn); - - // converts the FILETIME to the C Timestamp (compatible with dbghelp.dll) - inline DWORD FiletimeToUnixTime(const FILETIME& ft) - { - return (DWORD)((((int64&)ft) / SECS_TO_100NS) - SECS_BETWEEN_EPOCHS); - } - - // converts the FILETIME to 64bit C timestamp - inline AZ::u64 FiletimeTo64BitUnixTime(const FILETIME& fileTime) - { - const AZ::u64 time = static_cast(fileTime.dwHighDateTime) << 32 | fileTime.dwLowDateTime; - return ((time / SECS_TO_100NS) - SECS_BETWEEN_EPOCHS); - } - - // converts the C Timestamp (compatible with dbghelp.dll) to FILETIME - inline FILETIME UnixTimeToFiletime(DWORD nCTime) - { - const int64 time = (nCTime + SECS_BETWEEN_EPOCHS) * SECS_TO_100NS; - return (FILETIME&)time; - } - - //converts the 64 bit C Timestamp to FILETIME - inline void UnixTime64BitToFiletime(AZ::u64 nCTime, FILETIME& fileTime) - { - const AZ::u64 time = (nCTime + SECS_BETWEEN_EPOCHS) * SECS_TO_100NS; - fileTime.dwLowDateTime = static_cast(time); - fileTime.dwHighDateTime = static_cast(time >> 32); - } - - inline FILETIME GetInvalidFileTime() - { - FILETIME fileTime; - fileTime.dwLowDateTime = 0; - fileTime.dwHighDateTime = 0; - return fileTime; - } - - // returns file time stamps -#if defined(AZ_PLATFORM_WINDOWS) - inline bool GetFileTimes(const char* filename, FILETIME* ftimeCreate = nullptr, FILETIME* ftimeAccess = nullptr, FILETIME* ftimeModify = nullptr) - { - WIN32_FIND_DATAA FindFileData; - const HANDLE hFind = FindFirstFileA(filename, &FindFileData); - if (hFind == INVALID_HANDLE_VALUE) - { - return false; - } - - if (ftimeModify == nullptr && ftimeCreate == nullptr && ftimeAccess == nullptr) - { - FindClose(hFind); - return true; - } - - FindClose(hFind); - if (ftimeCreate) - { - ftimeCreate->dwLowDateTime = FindFileData.ftCreationTime.dwLowDateTime; - ftimeCreate->dwHighDateTime = FindFileData.ftCreationTime.dwHighDateTime; - } - if (ftimeModify) - { - ftimeModify->dwLowDateTime = FindFileData.ftLastWriteTime.dwLowDateTime; - ftimeModify->dwHighDateTime = FindFileData.ftLastWriteTime.dwHighDateTime; - } - if (ftimeAccess) - { - ftimeAccess->dwLowDateTime = FindFileData.ftLastAccessTime.dwLowDateTime; - ftimeAccess->dwHighDateTime = FindFileData.ftCreationTime.dwHighDateTime; - } - return true; - } -#else - inline bool GetFileTimes(const char* filename, AZ::u64* timeCreate = nullptr, AZ::u64* timeAccess = nullptr, AZ::u64* timeModify = nullptr) - { - - struct stat statResult; - if (stat(filename, &statResult) != 0) - { - return false; - } - - if (timeCreate) - { - *timeCreate =static_cast(statResult.st_ctime); - } - if (timeModify) - { - *timeModify =static_cast(statResult.st_mtime); - } - if (timeAccess) - { - *timeAccess =static_cast(statResult.st_atime); - } - return true; - } -#endif - - - - inline FILETIME GetLastWriteFileTime(const char* filename) - { - FILETIME timeModify = GetInvalidFileTime(); -#if defined(AZ_PLATFORM_WINDOWS) - GetFileTimes(filename, nullptr, nullptr, &timeModify); -#else - AZ::u64 modTime = 0; - GetFileTimes(filename, nullptr, nullptr, &modTime); - if(modTime != 0) - { - UnixTime64BitToFiletime(modTime, timeModify); - } -#endif - return timeModify; - } - - inline bool FileTimesAreEqual(const FILETIME& fileTime0, const FILETIME& fileTime1) - { - return - (fileTime0.dwLowDateTime == fileTime1.dwLowDateTime) && - (fileTime0.dwHighDateTime == fileTime1.dwHighDateTime); - } - - inline bool FileTimesAreEqual(const char* const srcfilename, const char* const targetfilename) - { - FILETIME ftSource = FileUtil::GetLastWriteFileTime(srcfilename); - FILETIME ftTarget = FileUtil::GetLastWriteFileTime(targetfilename); - return FileTimesAreEqual(ftSource, ftTarget); - } - - inline bool FileTimeIsValid(const FILETIME& fileTime) - { - return !FileTimesAreEqual(GetInvalidFileTime(), fileTime); - } - - inline bool SetFileTimes(const char* const filename, const FILETIME& creationFileTime, const FILETIME& accessFileTime, const FILETIME& modifcationFileTime) - { -#if defined(AZ_PLATFORM_WINDOWS) - const HANDLE hf = CreateFileA(filename, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); - if (hf != INVALID_HANDLE_VALUE) - { - if (SetFileTime(hf, &creationFileTime, &accessFileTime, &modifcationFileTime)) - { - if (CloseHandle(hf)) - { - return true; - } - } - - CloseHandle(hf); - } -#else - AZ::u64 creationTime = FiletimeTo64BitUnixTime(creationFileTime); - AZ::u64 modificationTime = FiletimeTo64BitUnixTime(modifcationFileTime); - - struct utimbuf puttime; - puttime.modtime = modificationTime; - puttime.actime = creationTime; - - if (utime(filename, &puttime) == 0) - { - return true; - } - -#endif - return false; - } - - inline bool SetFileTimes(const char* const filename, const FILETIME& fileTime) - { -#if defined(AZ_PLATFORM_WINDOWS) - const HANDLE hf = CreateFileA(filename, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); - if (hf != INVALID_HANDLE_VALUE) - { - if (SetFileTime(hf, &fileTime, &fileTime, &fileTime)) - { - if (CloseHandle(hf)) - { - return true; - } - } - - CloseHandle(hf); - } -#else - - AZ::u64 newTime = FiletimeTo64BitUnixTime(fileTime); - - struct utimbuf puttime; - puttime.modtime = newTime; - puttime.actime = newTime; - - if (utime(filename, &puttime) == 0) - { - return true; - } -#endif - return false; - } - - inline bool SetFileTimes(const char* const srcfilename, const char* const targetfilename) - { -#if defined(AZ_PLATFORM_WINDOWS) - FILETIME creationFileTime, accessFileTime, modifcationFileTime; - if (GetFileTimes(srcfilename, &creationFileTime, &accessFileTime, &modifcationFileTime)) - { - const HANDLE hf = CreateFileA(targetfilename, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); - if (hf != INVALID_HANDLE_VALUE) - { - if (SetFileTime(hf, &creationFileTime, &accessFileTime, &modifcationFileTime)) - { - if (CloseHandle(hf)) - { - return true; - } - } - - CloseHandle(hf); - } - } -#else - AZ::u64 creationFileTime, accessFileTime, modifcationFileTime; - if (GetFileTimes(srcfilename, &creationFileTime, &accessFileTime, &modifcationFileTime)) - { - struct utimbuf puttime; - puttime.modtime = modifcationFileTime; - puttime.actime = accessFileTime; - - if (utime(targetfilename, &puttime) == 0) - { - return true; - } - } -#endif - return false; - } - - inline uint64 GetFileSize(const char* const filename) - { - AZ::u64 fileSize = AZ::IO::SystemFile::Length(filename); - return fileSize >= 0? fileSize : -1; - - } - - inline bool FileExists(const char* szPath) - { - return AZ::IO::LocalFileIO().Exists(szPath); - } - - inline bool DirectoryExists(const char* szPath) - { - return AZ::IO::LocalFileIO().IsDirectory(szPath); - } -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_FILEUTIL_H diff --git a/Code/Tools/CryCommonTools/FileXmlBufferSource.h b/Code/Tools/CryCommonTools/FileXmlBufferSource.h deleted file mode 100644 index de802a3311..0000000000 --- a/Code/Tools/CryCommonTools/FileXmlBufferSource.h +++ /dev/null @@ -1,48 +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_CRYCOMMONTOOLS_FILEXMLBUFFERSOURCE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_FILEXMLBUFFERSOURCE_H -#pragma once - - -class FileXmlBufferSource - : public IXmlBufferSource -{ -public: - FileXmlBufferSource(const char* path) - { - file = std::fopen(path, "r"); - } - ~FileXmlBufferSource() - { - if (file) - { - std::fclose(file); - } - } - - virtual int Read(void* buffer, int size) const - { - if (!file) - { - return 0; - } - return std::fread(buffer, 1, size, file); - } - -private: - mutable std::FILE* file; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_FILEXMLBUFFERSOURCE_H diff --git a/Code/Tools/CryCommonTools/ILogger.h b/Code/Tools/CryCommonTools/ILogger.h deleted file mode 100644 index cbcbae3094..0000000000 --- a/Code/Tools/CryCommonTools/ILogger.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_CRYCOMMONTOOLS_ILOGGER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ILOGGER_H -#pragma once - - -#include -#include - -class ILogger -{ -public: - enum ESeverity - { - eSeverity_Debug, - eSeverity_Info, - eSeverity_Warning, - eSeverity_Error - }; - - virtual ~ILogger() - { - } - - void Log(ESeverity eSeverity, const char* const format, ...) - { - char buffer[2048]; - { - va_list args; - va_start(args, format); - _vsnprintf_s(buffer, sizeof(buffer), sizeof(buffer) - 1, format, args); - va_end(args); - } - LogImpl(eSeverity, buffer); - } - -protected: - virtual void LogImpl(ESeverity eSeverity, const char* text) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ILOGGER_H diff --git a/Code/Tools/CryCommonTools/IPakSystem.h b/Code/Tools/CryCommonTools/IPakSystem.h deleted file mode 100644 index d8646c3a2c..0000000000 --- a/Code/Tools/CryCommonTools/IPakSystem.h +++ /dev/null @@ -1,49 +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_CRYCOMMONTOOLS_IPAKSYSTEM_H -#define CRYINCLUDE_CRYCOMMONTOOLS_IPAKSYSTEM_H -#pragma once - -#include - -struct PakSystemFile; -struct PakSystemArchive; -struct IPakSystem -{ - virtual PakSystemFile* Open(const char* filename, const char* mode) = 0; - virtual bool ExtractNoOverwrite(const char* filename, const char* extractToFile = 0) = 0; - virtual void Close(PakSystemFile* file) = 0; - virtual int GetLength(PakSystemFile* file) const = 0; - virtual int Read(PakSystemFile* file, void* buffer, int size) = 0; - virtual bool EoF(PakSystemFile* file) = 0; - - virtual PakSystemArchive* OpenArchive(const char* path, size_t fileAlignment = 1, bool encrypted = false, const uint32 encryptionKey[4] = 0) = 0; - virtual void CloseArchive(PakSystemArchive* archive) = 0; - - // Summary: - // Adds a new file to the pak or update an existing one. - // Adds a directory (creates several nested directories if needed) - // Arguments: - // path - relative path inside archive - // data, size - file content - // modTime - modification timestamp of the file - // compressionLevel - level of compression (correnponds to zlib-levels): - // -1 or [0-9] where -1=default compression, 0=no compression, 9=best compression - virtual void AddToArchive(PakSystemArchive* archive, const char* path, void* data, int size, int64 modTime, int compressionLevel = -1) = 0; - - virtual bool DeleteFromArchive(PakSystemArchive* archive, const char* path) = 0; - virtual bool CheckIfFileExist(PakSystemArchive* archive, const char* path, int64 modTime) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_IPAKSYSTEM_H diff --git a/Code/Tools/CryCommonTools/ISettings.h b/Code/Tools/CryCommonTools/ISettings.h deleted file mode 100644 index bba3100215..0000000000 --- a/Code/Tools/CryCommonTools/ISettings.h +++ /dev/null @@ -1,57 +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_CRYCOMMONTOOLS_ISETTINGS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ISETTINGS_H -#pragma once - - -class ISettings -{ -public: - virtual bool GetSettingString(char* buffer, int bufferSizeInBytes, const char* key) = 0; - virtual bool GetSettingInt(int& value, const char* key) = 0; -}; - -inline bool GetSettingByRef(ISettings* settings, const string& key, string& value) -{ - char buffer[1024]; - bool success = false; - if (settings) - { - success = settings->GetSettingString(buffer, sizeof(buffer), key.c_str()); - } - if (success) - { - value = buffer; - } - return success; -} - -inline bool GetSettingByRef(ISettings* settings, const string& key, int& value) -{ - return settings->GetSettingInt(value, key.c_str()); -} - -template -inline T GetSetting(ISettings* settings, const string& key, const T& dflt) -{ - T value; - if (!GetSettingByRef(settings, key, value)) - { - value = dflt; - } - return value; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ISETTINGS_H diff --git a/Code/Tools/CryCommonTools/LocaleChanger.cpp b/Code/Tools/CryCommonTools/LocaleChanger.cpp deleted file mode 100644 index 3a9edee30a..0000000000 --- a/Code/Tools/CryCommonTools/LocaleChanger.cpp +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "LocaleChanger.h" -#include - -LocaleChanger::LocaleChanger(int category, const char* newLocale) -{ - m_category = category; - m_oldLocale = setlocale(category, newLocale); -} - -LocaleChanger::~LocaleChanger() -{ - setlocale(m_category, m_oldLocale.c_str()); -} diff --git a/Code/Tools/CryCommonTools/LocaleChanger.h b/Code/Tools/CryCommonTools/LocaleChanger.h deleted file mode 100644 index 3b85c462a2..0000000000 --- a/Code/Tools/CryCommonTools/LocaleChanger.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_CRYCOMMONTOOLS_LOCALECHANGER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_LOCALECHANGER_H -#pragma once - - -class LocaleChanger -{ -public: - LocaleChanger(int category, const char* newLocale); - ~LocaleChanger(); - -private: - int m_category; - string m_oldLocale; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_LOCALECHANGER_H diff --git a/Code/Tools/CryCommonTools/LogFile.cpp b/Code/Tools/CryCommonTools/LogFile.cpp deleted file mode 100644 index ef98be776b..0000000000 --- a/Code/Tools/CryCommonTools/LogFile.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "LogFile.h" - -LogFile::LogFile(const char* const filename) - : m_file(0) - , m_hasWarnings(false) - , m_hasErrors(false) -{ - m_file = std::fopen(filename, "w"); -} - -LogFile::~LogFile() -{ - if (m_file) - { - fclose(m_file); - } -} - -bool LogFile::IsOpen() const -{ - return m_file != 0; -} - -bool LogFile::HasWarningsOrErrors() const -{ - return m_hasWarnings || m_hasErrors; -} - -void LogFile::LogImpl(ESeverity eSeverity, const char* const text) -{ - const char* severityMessage = 0; - switch (eSeverity) - { - case eSeverity_Debug: - severityMessage = " "; - break; - case eSeverity_Info: - severityMessage = " "; - break; - case eSeverity_Warning: - severityMessage = "W: "; - break; - case eSeverity_Error: - severityMessage = "E: "; - break; - default: - severityMessage = "?: "; - break; - } - - if (eSeverity == eSeverity_Warning) - { - m_hasWarnings = true; - } - if (eSeverity == eSeverity_Error) - { - m_hasErrors = true; - } - - if (m_file) - { - fprintf(m_file, "%s%s\n", severityMessage, text); - fflush(m_file); - } -} diff --git a/Code/Tools/CryCommonTools/LogFile.h b/Code/Tools/CryCommonTools/LogFile.h deleted file mode 100644 index d26c457165..0000000000 --- a/Code/Tools/CryCommonTools/LogFile.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_CRYCOMMONTOOLS_LOGFILE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_LOGFILE_H -#pragma once - - -#include "ILogger.h" - -class LogFile - : public ILogger -{ -public: - LogFile(const char* filename); - ~LogFile(); - - bool IsOpen() const; - bool HasWarningsOrErrors() const; - - // ILogger - virtual void LogImpl(ESeverity eSeverity, const char* message); - -private: - std::FILE* m_file; - bool m_hasWarnings; - bool m_hasErrors; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_LOGFILE_H diff --git a/Code/Tools/CryCommonTools/MathHelpers.h b/Code/Tools/CryCommonTools/MathHelpers.h deleted file mode 100644 index d21c14aa6c..0000000000 --- a/Code/Tools/CryCommonTools/MathHelpers.h +++ /dev/null @@ -1,72 +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_CRYCOMMONTOOLS_MATHHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_MATHHELPERS_H -#pragma once - - -#include -#if (_M_IX86_FP > 0) -#include -#endif - -namespace MathHelpers -{ -#if (_M_IX86_FP > 0) - inline int FastRoundFloatTowardZero(float f) - { - return _mm_cvtt_ss2si(_mm_set_ss(f)); - } -#else - inline int FastRoundFloatTowardZero(float f) - { - return int(f); - } -#endif - -#if defined(AZ_PLATFORM_WINDOWS) - - inline unsigned int EnableFloatingPointExceptions(unsigned int mask) - { - _clearfp(); - unsigned int oldMask; - _controlfp_s(&oldMask, 0, 0); - unsigned int newMask; - _controlfp_s(&newMask, ~mask, _MCW_EM); - return ~oldMask; - } - - class AutoFloatingPointExceptions - { - public: - AutoFloatingPointExceptions(const unsigned int mask) - : m_mask(EnableFloatingPointExceptions(mask)) - { - } - - ~AutoFloatingPointExceptions() - { - EnableFloatingPointExceptions(m_mask); - } - - private: - unsigned int m_mask; - }; - -#endif //AZ_PLATFORM_WINDOWS -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_MATHHELPERS_H - - diff --git a/Code/Tools/CryCommonTools/ModuleHelpers.cpp b/Code/Tools/CryCommonTools/ModuleHelpers.cpp deleted file mode 100644 index 2ce5c2639a..0000000000 --- a/Code/Tools/CryCommonTools/ModuleHelpers.cpp +++ /dev/null @@ -1,44 +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 -#include "ModuleHelpers.h" - -HMODULE ModuleHelpers::GetCurrentModule(CurrentModuleSpecifier moduleSpecifier) -{ - switch (moduleSpecifier) - { - case CurrentModuleSpecifier_Executable: - return GetModuleHandle(0); - - case CurrentModuleSpecifier_Library: - MEMORY_BASIC_INFORMATION mbi; - static int dummy; - VirtualQuery(&dummy, &mbi, sizeof(mbi)); - HMODULE instance = reinterpret_cast(mbi.AllocationBase); - return instance; - } - - return 0; -} - -std::basic_string ModuleHelpers::GetCurrentModulePath(CurrentModuleSpecifier moduleSpecifier) -{ - // Here's a trick that will get you the handle of the module - // you're running in without any a-priori knowledge: - // http://www.dotnet247.com/247reference/msgs/13/65259.aspx - HMODULE instance = GetCurrentModule(moduleSpecifier); - TCHAR moduleNameBuffer[MAX_PATH]; - GetModuleFileName(instance, moduleNameBuffer, sizeof(moduleNameBuffer) / sizeof(moduleNameBuffer[0])); - return moduleNameBuffer; -} diff --git a/Code/Tools/CryCommonTools/ModuleHelpers.h b/Code/Tools/CryCommonTools/ModuleHelpers.h deleted file mode 100644 index cb9049e89b..0000000000 --- a/Code/Tools/CryCommonTools/ModuleHelpers.h +++ /dev/null @@ -1,31 +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_CRYCOMMONTOOLS_MODULEHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_MODULEHELPERS_H -#pragma once - - -namespace ModuleHelpers -{ - enum CurrentModuleSpecifier - { - CurrentModuleSpecifier_Executable, - CurrentModuleSpecifier_Library - }; - - HMODULE GetCurrentModule(CurrentModuleSpecifier moduleSpecifier); - std::basic_string GetCurrentModulePath(CurrentModuleSpecifier moduleSpecifier); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_MODULEHELPERS_H diff --git a/Code/Tools/CryCommonTools/PakSystem.cpp b/Code/Tools/CryCommonTools/PakSystem.cpp deleted file mode 100644 index 42a129c5e6..0000000000 --- a/Code/Tools/CryCommonTools/PakSystem.cpp +++ /dev/null @@ -1,380 +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 -#include "PakSystem.h" -#include "PathHelpers.h" -#include "StringHelpers.h" -#include "ZipDir/ZipDir.h" - -#include -#include -#include - - - -PakSystemFile::PakSystemFile() -{ - type = PakSystemFileType_Unknown; - file = NULL; - zip = NULL; - fileEntry = NULL; - data = NULL; - dataPosition = 0; -} - -PakSystem::PakSystem() -{ -} - -PakSystemFile* PakSystem::Open(const char* a_path, const char* a_mode) -{ - string normalPath = a_path; - - string const zipExt = ".zip"; - bool bZip = StringHelpers::EndsWithIgnoreCase(normalPath, zipExt); - - if (bZip) - { - // If it's a .zip file, then we'll try to look for a file without .zip extension inside of the .zip file - normalPath.erase(normalPath.length() - zipExt.length(), zipExt.length()); - } - - string zipPath = normalPath + zipExt; - string filename = PathHelpers::GetFilename(normalPath); - - if (!normalPath.empty() && normalPath[0] == '@') - { - // File is inside pak file. - int splitter = normalPath.find_first_of("|;,"); - if (splitter >= 0) - { - zipPath = normalPath.substr(1, splitter - 1); - filename = StringHelpers::MakeLowerCase(normalPath.substr(splitter + 1)); - bZip = true; - } - else - { - return 0; - } - } - - if (!bZip) - { - // Try to open the file. - FILE* f = nullptr; - azfopen(&f, normalPath.c_str(), a_mode); - if (f) - { - std::unique_ptr file(new PakSystemFile()); - file->type = PakSystemFileType_File; - file->file = f; - - return file.release(); - } - } - - // if it's simple and read-only, it's assumed it's read-only - unsigned const nFactoryFlags = ZipDir::CacheFactory::FLAGS_DONT_COMPACT | ZipDir::CacheFactory::FLAGS_READ_ONLY; - - bool bFileExists = false; - const uint32* decryptionKey = 0; // use default one - - if (bZip) - { - // a caller asked to open a .zip file. check if the .zip file on disk exist - FILE* f = nullptr; - azfopen(&f, zipPath.c_str(), "rb"); - if (f) - { - fclose(f); - bFileExists = true; - } - } - else - { - // a caller specified normal file. we already failed to find it on disk, - // so the file could be within a .pak file. let's find all 'potential' - // pak files and look within these for a matching file - - std::vector foundFileCountainer; // pak files found - - for (string dirToSearch = normalPath;; ) - { - dirToSearch = PathHelpers::GetDirectory(dirToSearch); - - AZ::IO::LocalFileIO localFileIO; - localFileIO.FindFiles(dirToSearch.c_str(), "*.pak", [&](const char* filePath) -> bool - { - const string foundFilename(filePath); - if (StringHelpers::EqualsIgnoreCase(PathHelpers::FindExtension(foundFilename), "pak")) - { - foundFileCountainer.push_back(foundFilename); - } - return true; // continue iterating - }); - - if (PathHelpers::GetFilename(dirToSearch).empty()) - { - // We've reached the top of the path - break; - } - } - - // iterate through found containers and look for relevant files within them - for (int iFile = 0; iFile < foundFileCountainer.size(); ++iFile) - { - zipPath = foundFileCountainer[ iFile ]; - string pathToZip = PathHelpers::GetDirectory(zipPath); - - // construct filename by removing path to zip from path to filename - string pathToFile = PathHelpers::GetDirectory(string(normalPath)); - string pureFileName = PathHelpers::GetFilename(string(normalPath)); - if (pathToFile.length() != pathToZip.length() && pathToZip.length() > 0) - { - pathToFile = pathToFile.substr(pathToZip.length() + 1); - } - filename = pathToFile.empty() - ? pureFileName - : pathToFile + "\\" + pureFileName; - - ZipDir::CacheFactory factory(ZipDir::ZD_INIT_FAST, nFactoryFlags); - ZipDir::CachePtr testZip = factory.New(zipPath.c_str(), decryptionKey); - ZipDir::FileEntry* testFileEntry = (testZip ? testZip->FindFile(filename.c_str()) : 0); - - // break out if we have a testFileEntry, as we've found our first (and best) candidate. - if (testFileEntry) - { - bFileExists = true; - break; - } - } - } - - { - ZipDir::CacheFactory factory(ZipDir::ZD_INIT_FAST, nFactoryFlags); - ZipDir::CachePtr zip = (bFileExists ? factory.New(zipPath.c_str(), decryptionKey) : 0); - ZipDir::FileEntry* fileEntry = (zip ? zip->FindFile(filename.c_str()) : 0); - - if (fileEntry) - { - std::unique_ptr file(new PakSystemFile()); - file->type = PakSystemFileType_PakFile; - file->zip = zip; - file->fileEntry = fileEntry; - file->data = zip->AllocAndReadFile(file->fileEntry); - file->dataPosition = 0; - return file.release(); - } - } - - return 0; -} - - -//Extracts archived file to disk without overwriting any files -//returns true on success, false on failure (due to potential overwrite or no file -//in archive -bool PakSystem::ExtractNoOverwrite(const char* fileToExtract, const char* extractToFile) -{ - if (0 == extractToFile) - { - extractToFile = fileToExtract; - } - - //open file using pak system - PakSystemFile* fileZip = Open(fileToExtract, "r"); - if (!fileZip) - { - return false; - } - - // Try to open a writable file - FILE* fFileOnDisk = nullptr; - azfopen(&fFileOnDisk, extractToFile, "wb"); - if (!fFileOnDisk) - { - Close(fileZip); - return false; - } - - fwrite(fileZip->data, fileZip->fileEntry->desc.lSizeUncompressed, 1, fFileOnDisk); - fclose(fFileOnDisk); - - Close(fileZip); - - return true; -} - - -void PakSystem::Close(PakSystemFile* file) -{ - if (file) - { - switch (file->type) - { - case PakSystemFileType_File: - fclose(file->file); - break; - - case PakSystemFileType_PakFile: - file->zip->Free(file->data); - break; - } - delete file; - } -} - - -int PakSystem::GetLength(PakSystemFile* file) const -{ - if (file) - { - switch (file->type) - { - case PakSystemFileType_File: - { - if (file->file) - { - long pos = ftell(file->file); - fseek(file->file, 0, SEEK_END); - int result = ftell(file->file); - fseek(file->file, pos, SEEK_SET); - return result; - } - break; - } - case PakSystemFileType_PakFile: - { - if (file->fileEntry) - { - return file->fileEntry->desc.lSizeUncompressed; - } - break; - } - default: - { - break; - } - } - } - return 0; -} - - -int PakSystem::Read(PakSystemFile* file, void* buffer, int size) -{ - int readBytes = 0; - - if (file) - { - switch (file->type) - { - case PakSystemFileType_File: - { - readBytes = fread(buffer, 1, size, file->file); - } - break; - - case PakSystemFileType_PakFile: - { - int fileSize = file->fileEntry->desc.lSizeUncompressed; - readBytes = (fileSize - file->dataPosition > size ? size : fileSize - file->dataPosition); - memcpy(buffer, static_cast(file->data) + file->dataPosition, readBytes); - file->dataPosition += readBytes; - } - break; - } - } - - return readBytes; -} - -bool PakSystem::EoF(PakSystemFile* file) -{ - bool EoF = true; - if (file) - { - switch (file->type) - { - case PakSystemFileType_File: - { - EoF = (0 != feof(file->file)); - } - break; - - case PakSystemFileType_PakFile: - { - int fileSize = file->fileEntry->desc.lSizeUncompressed; - EoF = (file->dataPosition >= fileSize); - } - break; - } - } - - return EoF; -} - -PakSystemArchive* PakSystem::OpenArchive(const char* path, size_t fileAlignment, bool encrypted, const uint32 encryptionKey[4]) -{ - //unsigned nFactoryFlags = ZipDir::CacheFactory::FLAGS_DONT_COMPACT | ZipDir::CacheFactory::FLAGS_CREATE_NEW; - unsigned nFactoryFlags = 0; - ZipDir::CacheFactory factory(ZipDir::ZD_INIT_FAST, nFactoryFlags); - ZipDir::CacheRWPtr cache = factory.NewRW(path, fileAlignment, encrypted, encryptionKey); - PakSystemArchive* archive = (cache ? new PakSystemArchive() : 0); - if (archive) - { - archive->zip = cache; - } - return archive; -} - -void PakSystem::CloseArchive(PakSystemArchive* archive) -{ - if (archive) - { - archive->zip->Close(); - delete archive; - } -} - -void PakSystem::AddToArchive(PakSystemArchive* archive, const char* path, void* data, int size, int64 modTime, int compressionLevel) -{ - int compressionMethod = ZipFile::METHOD_DEFLATE; - if (compressionLevel == 0) - { - compressionMethod = ZipFile::METHOD_STORE; - } - archive->zip->UpdateFile(path, data, size, compressionMethod, compressionLevel, modTime); -} - -////////////////////////////////////////////////////////////////////////// -bool PakSystem::CheckIfFileExist(PakSystemArchive* archive, const char* path, int64 modTime) -{ - assert(archive); - - ZipDir::FileEntry* pFileEntry = archive->zip->FindFile(path); - if (pFileEntry) - { - return pFileEntry->CompareFileTimeNTFS(modTime); - } - - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool PakSystem::DeleteFromArchive(PakSystemArchive* archive, const char* path) -{ - ZipDir::ErrorEnum err = archive->zip->RemoveFile(path); - return ZipDir::ZD_ERROR_SUCCESS == err; -} diff --git a/Code/Tools/CryCommonTools/PakSystem.h b/Code/Tools/CryCommonTools/PakSystem.h deleted file mode 100644 index ba57f26d4d..0000000000 --- a/Code/Tools/CryCommonTools/PakSystem.h +++ /dev/null @@ -1,69 +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_CRYCOMMONTOOLS_PAKSYSTEM_H -#define CRYINCLUDE_CRYCOMMONTOOLS_PAKSYSTEM_H -#pragma once - - -#include "IPakSystem.h" -#include "ZipDir/ZipDir.h" // TODO: get rid of thid include - -enum PakSystemFileType -{ - PakSystemFileType_Unknown, - PakSystemFileType_File, - PakSystemFileType_PakFile -}; -struct PakSystemFile -{ - PakSystemFile(); - PakSystemFileType type; - - // PakSystemFileType_File - FILE* file; - - // PakSystemFileType_PakFile - ZipDir::CachePtr zip; - ZipDir::FileEntry* fileEntry; - void* data; - int dataPosition; -}; - -struct PakSystemArchive -{ - ZipDir::CacheRWPtr zip; -}; - -class PakSystem - : public IPakSystem -{ -public: - PakSystem(); - - // IPakSystem - virtual PakSystemFile* Open(const char* filename, const char* mode); - virtual bool ExtractNoOverwrite(const char* filename, const char* extractToFile = 0); - virtual void Close(PakSystemFile* file); - virtual int GetLength(PakSystemFile* file) const; - virtual int Read(PakSystemFile* file, void* buffer, int size); - virtual bool EoF(PakSystemFile* file); - - virtual PakSystemArchive* OpenArchive(const char* path, size_t fileAlignment, bool encrypted, const uint32 encryptionKey[4]); - virtual void CloseArchive(PakSystemArchive* archive); - virtual void AddToArchive(PakSystemArchive* archive, const char* path, void* data, int size, int64 modTime, int compressionLevel); - virtual bool DeleteFromArchive(PakSystemArchive* archive, const char* path); - virtual bool CheckIfFileExist(PakSystemArchive* archive, const char* path, int64 modTime); -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_PAKSYSTEM_H diff --git a/Code/Tools/CryCommonTools/PakXmlFileBufferSource.h b/Code/Tools/CryCommonTools/PakXmlFileBufferSource.h deleted file mode 100644 index cd9aa9d211..0000000000 --- a/Code/Tools/CryCommonTools/PakXmlFileBufferSource.h +++ /dev/null @@ -1,74 +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_CRYCOMMONTOOLS_PAKXMLFILEBUFFERSOURCE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_PAKXMLFILEBUFFERSOURCE_H -#pragma once - - -#include "../CryXML/IXMLSerializer.h" -#include "IPakSystem.h" - -class PakXmlFileBufferSource - : public IXmlBufferSource -{ -public: - PakXmlFileBufferSource(IPakSystem* pakSystem, const char* path) - : pakSystem(pakSystem) - { - file = pakSystem->Open(path, "r"); - } - ~PakXmlFileBufferSource() - { - if (file) - { - pakSystem->Close(file); - } - } - - virtual int Read(void* buffer, int size) const - { - return pakSystem->Read(file, buffer, size); - }; - - IPakSystem* pakSystem; - PakSystemFile* file; -}; - -class PakXmlBufferSource - : public IXmlBufferSource -{ -public: - PakXmlBufferSource(const char* buffer, size_t length) - : position(buffer) - , end(buffer + length) - { - } - - virtual int Read(void* output, int size) const - { - size_t bytesLeft = end - position; - size_t bytesToCopy = size < bytesLeft ? size : bytesLeft; - if (bytesToCopy > 0) - { - memcpy(output, position, bytesToCopy); - position += bytesToCopy; - } - return bytesToCopy; - }; - - mutable const char* position; - const char* end; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_PAKXMLFILEBUFFERSOURCE_H diff --git a/Code/Tools/CryCommonTools/PathHelpers.cpp b/Code/Tools/CryCommonTools/PathHelpers.cpp deleted file mode 100644 index 4abd28183e..0000000000 --- a/Code/Tools/CryCommonTools/PathHelpers.cpp +++ /dev/null @@ -1,621 +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 -#include "PathHelpers.h" -#include "StringHelpers.h" -#include "Util.h" - -#include -#include -#include -#include -#include - - -// Returns position of last extension in last name (string::npos if not found) -// note: returns string::npos for names starting from '.' and having no -// '.' later (for example 'aaa/.ccc', 'a:.abc', '.rc') -template -static inline size_t findExtensionPosition_Tpl(const TS& path) -{ - const size_t dotPos = path.rfind('.'); - if (dotPos == TS::npos) - { - return TS::npos; - } - - static const typename TS::value_type separators[] = { '\\', '/', ':', 0 }; - const size_t separatorPos = path.find_last_of(separators); - if (separatorPos != TS::npos) - { - if (separatorPos + 1 >= dotPos) - { - return TS::npos; - } - } - else if (dotPos == 0) - { - return TS::npos; - } - - return dotPos + 1; -} - -static size_t findExtensionPosition(const string& path) -{ - return findExtensionPosition_Tpl(path); -} - -static size_t findExtensionPosition(const wstring& path) -{ - return findExtensionPosition_Tpl(path); -} - - -string PathHelpers::FindExtension(const string& path) -{ - const size_t extPos = findExtensionPosition(path); - return (extPos == string::npos) ? string() : path.substr(extPos, string::npos); -} - -wstring PathHelpers::FindExtension(const wstring& path) -{ - const size_t extPos = findExtensionPosition(path); - return (extPos == wstring::npos) ? wstring() : path.substr(extPos, wstring::npos); -} - - -template -static inline TS ReplaceExtension_Tpl(const TS& path, const TS& newExtension) -{ - if (path.empty()) - { - return TS(); - } - - if (newExtension.empty()) - { - return PathHelpers::RemoveExtension(path); - } - - const typename TS::value_type last = path[path.length() - 1]; - if ((last == '\\') || (last == '/') || (last == ':') || (last == '.')) - { - return path; - } - - const size_t extPos = findExtensionPosition(path); - static const typename TS::value_type dot[] = { '.', 0 }; - return ((extPos == TS::npos) ? path + dot : path.substr(0, extPos)) + newExtension; -} - -string PathHelpers::ReplaceExtension(const string& path, const string& newExtension) -{ - return ReplaceExtension_Tpl(path, newExtension); -} - -wstring PathHelpers::ReplaceExtension(const wstring& path, const wstring& newExtension) -{ - return ReplaceExtension_Tpl(path, newExtension); -} - - -string PathHelpers::RemoveExtension(const string& path) -{ - const size_t extPos = findExtensionPosition(path); - return (extPos == string::npos) ? path : path.substr(0, extPos - 1); -} - -wstring PathHelpers::RemoveExtension(const wstring& path) -{ - const size_t extPos = findExtensionPosition(path); - return (extPos == wstring::npos) ? path : path.substr(0, extPos - 1); -} - - -template -static inline TS GetDirectory_Tpl(const TS& path) -{ - static const typename TS::value_type separators[] = { '/', '\\', ':', 0 }; - const size_t pos = path.find_last_of(separators); - - if (pos == TS::npos) - { - return TS(); - } - - if (path[pos] == ':' || pos == 0 || path[pos - 1] == ':') - { - return path.substr(0, pos + 1); - } - - // Handle paths like "\\machine" - if (pos == 1 && (path[0] == '/' || path[0] == '\\')) - { - return path; - } - - return path.substr(0, pos); -} - -string PathHelpers::GetDirectory(const string& path) -{ - return GetDirectory_Tpl(path); -} - -wstring PathHelpers::GetDirectory(const wstring& path) -{ - return GetDirectory_Tpl(path); -} - - -template -static inline TS GetFilename_Tpl(const TS& path) -{ - static const typename TS::value_type separators[] = { '/', '\\', ':', 0 }; - const size_t pos = path.find_last_of(separators); - - if (pos == TS::npos) - { - return path; - } - - // Handle paths like "\\machine" - if (pos == 1 && (path[0] == '/' || path[0] == '\\')) - { - return TS(); - } - - return path.substr(pos + 1, TS::npos); -} - -string PathHelpers::GetFilename(const string& path) -{ - return GetFilename_Tpl(path); -} - -wstring PathHelpers::GetFilename(const wstring& path) -{ - return GetFilename_Tpl(path); -} - - -template -static inline TS AddSeparator_Tpl(const TS& path) -{ - if (path.empty()) - { - return TS(); - } - const typename TS::value_type last = path[path.length() - 1]; - if (last == '/' || last == '\\' || last == ':') - { - return path; - } -#if defined(AZ_PLATFORM_WINDOWS) - static const typename TS::value_type separator[] = { '\\', 0 }; -#else - static const typename TS::value_type separator[] = { '/', 0 }; -#endif - return path + separator; -} - -string PathHelpers::AddSeparator(const string& path) -{ - return AddSeparator_Tpl(path); -} - -wstring PathHelpers::AddSeparator(const wstring& path) -{ - return AddSeparator_Tpl(path); -} - - -template -static inline TS RemoveSeparator_Tpl(const TS& path) -{ - if (path.empty()) - { - return TS(); - } - const typename TS::value_type last = path[path.length() - 1]; - if ((last == '/' || last == '\\') && path.length() > 1 && path[path.length() - 2] != ':') - { - return path.substr(0, path.length() - 1); - } - return path; -} - -string PathHelpers::RemoveSeparator(const string& path) -{ - return RemoveSeparator_Tpl(path); -} - -wstring PathHelpers::RemoveSeparator(const wstring& path) -{ - return RemoveSeparator_Tpl(path); -} - - -template -static inline TS RemoveDuplicateSeparators_Tpl(const TS& path) -{ - if (path.length() <= 1) - { - return path; - } - - TS ret; - ret.reserve(path.length()); - - const typename TS::value_type* p = path.c_str(); - - // We start from the second char just to avoid damaging UNC paths with double backslash at the beginning (e.g. "\\Server04\file.txt") - ret += *p++; - - while (*p) - { - ret += *p++; - if (p[-1] == '\\' || p[-1] == '/') - { - while (*p == '\\' || *p == '/') - { - ++p; - } - } - } - - return ret; -} - -string PathHelpers::RemoveDuplicateSeparators(const string& path) -{ - return RemoveDuplicateSeparators_Tpl(path); -} - -wstring PathHelpers::RemoveDuplicateSeparators(const wstring& path) -{ - return RemoveDuplicateSeparators_Tpl(path); -} - - -template -static inline TS Join_Tpl(const TS& path1, const TS& path2) -{ - if (path1.empty()) - { - return path2; - } - if (path2.empty()) - { - return path1; - } - - if (!PathHelpers::IsRelative(path2)) - { - assert(0 && "Join(): path2 is not relative"); - return TS(); - } - - const typename TS::value_type last = path1[path1.length() - 1]; - if (last == '/' || last == '\\' || last == ':') - { - return path1 + path2; - } -#if defined(AZ_PLATFORM_WINDOWS) - static const typename TS::value_type separator[] = { '\\', 0 }; -#else - static const typename TS::value_type separator[] = { '/', 0 }; -#endif - return path1 + separator + path2; -} - - -string PathHelpers::Join(const string& path1, const string& path2) -{ - return Join_Tpl(path1, path2); -} - -wstring PathHelpers::Join(const wstring& path1, const wstring& path2) -{ - return Join_Tpl(path1, path2); -} - - -template -static inline bool IsRelative_Tpl(const TS& path) -{ - if (path.empty()) - { - return true; - } - return path[0] != '/' && path[0] != '\\' && path.find(':') == TS::npos; -} - -bool PathHelpers::IsRelative(const string& path) -{ - return IsRelative_Tpl(path); -} - -bool PathHelpers::IsRelative(const wstring& path) -{ - return IsRelative_Tpl(path); -} - - -string PathHelpers::ToUnixPath(const string& path) -{ - return StringHelpers::Replace(path, '\\', '/'); -} - -wstring PathHelpers::ToUnixPath(const wstring& path) -{ - wstring s(path); - std::replace(s.begin(), s.end(), L'\\', L'/'); - return s; -} - - -string PathHelpers::ToDosPath(const string& path) -{ - return StringHelpers::Replace(path, '/', '\\'); -} - -wstring PathHelpers::ToDosPath(const wstring& path) -{ - wstring s(path); - std::replace(s.begin(), s.end(), L'/', L'\\'); - return s; -} - -string PathHelpers::ToPlatformPath(const string& path) -{ -#if defined(AZ_PLATFORM_WINDOWS) - return ToDosPath(path); -#else - return ToUnixPath(path); -#endif -} - -wstring PathHelpers::ToPlatformPath(const wstring& path) -{ -#if defined(AZ_PLATFORM_WINDOWS) - return ToDosPath(path); -#else - return ToUnixPath(path); -#endif -} - - -string PathHelpers::GetAsciiPath(const char* pPath) -{ - AZStd::wstring wstr; - AZStd::to_wstring(wstr, pPath); - return GetAsciiPath(wstr.c_str()); -} - -string PathHelpers::GetAsciiPath(const wchar_t* pPath) -{ - if (!pPath[0]) - { - return string(); - } - - wstring w = ToPlatformPath(RemoveSeparator(wstring(pPath))); - - if (StringHelpers::Utf16ContainsAsciiOnly(w.c_str())) - { - return StringHelpers::ConvertAsciiUtf16ToAscii(w.c_str()); - } - - // The path is non-ASCII, so let's resort to using short - // filenames where needed (short names are always ASCII-only) - - // Long names components - std::vector p0; - StringHelpers::Split(w, wstring(L"\\"), true, p0); - - // find last component that is not in ASCII char set - int lastNonAscii; - for (lastNonAscii = (int)p0.size() - 1; lastNonAscii >= 0; --lastNonAscii) - { - if (!StringHelpers::Utf16ContainsAsciiOnly(p0[lastNonAscii].c_str())) - { - break; - } - } - assert(lastNonAscii >= 0); - - string res; - res.reserve(w.length()); - - w.clear(); - for (int i = 0; i <= lastNonAscii; ++i) - { - w.append(p0[i]); - if (i < lastNonAscii) - { - w.push_back('\\'); - } - } - - enum - { - kBufferLen = AZ_MAX_PATH_LEN - }; - wchar_t bufferWchars[kBufferLen]; - -#if defined(AZ_PLATFORM_WINDOWS) - const int charCount = GetShortPathNameW(w.c_str(), bufferWchars, kBufferLen); -#else - const int charCount = w.length(); - wcsncpy(bufferWchars, w.c_str(), kBufferLen); -#endif - if (charCount <= 0 || charCount >= kBufferLen) - { - return string(); - } -#if defined(AZ_PLATFORM_WINDOWS) - // Paranoid - if (!StringHelpers::Utf16ContainsAsciiOnly(bufferWchars)) - { - assert(0); - return string(); - } -#endif - - // Short names components - std::vector p1; - StringHelpers::Split(wstring(bufferWchars), wstring(L"\\"), true, p1); - - for (size_t i = 0; i < (int)p0.size(); ++i) - { - if (!p0[i].empty()) - { - const wstring& p = - (i > lastNonAscii || StringHelpers::Utf16ContainsAsciiOnly(p0[i].c_str())) - ? p0[i] - : p1[i]; - res.append(StringHelpers::ConvertAsciiUtf16ToAscii(p.c_str())); - } - if (i + 1 < (int)p0.size()) - { - res.push_back('\\'); - } - } - - return res; -} - - -string PathHelpers::GetAbsoluteAsciiPath(const char* pPath) -{ - char fullPath[AZ_MAX_PATH_LEN]; - AZ::IO::LocalFileIO localFileIO; - - AZStd::string normalizedPath(pPath); - AzFramework::StringFunc::Path::Normalize(normalizedPath); - - localFileIO.ConvertToAbsolutePath(normalizedPath.c_str(), fullPath, AZ_MAX_PATH_LEN); - fullPath[sizeof(fullPath) - 1] = '\0'; - - AZStd::wstring wstr; - AZStd::to_wstring(wstr, fullPath); - return GetAsciiPath(wstr.c_str()); -} - -string PathHelpers::GetAbsoluteAsciiPath(const wchar_t* pPath) -{ - AZStd::string str; - AZStd::to_string(str, pPath); - - AzFramework::StringFunc::Path::Normalize(str); - - char fullPath[AZ_MAX_PATH_LEN]; - AZ::IO::LocalFileIO localFileIO; - localFileIO.ConvertToAbsolutePath(str.c_str(), fullPath, AZ_MAX_PATH_LEN); - fullPath[sizeof(fullPath) - 1] = '\0'; - - AZStd::wstring wstr; - AZStd::to_wstring(wstr, fullPath); - return GetAsciiPath(wstr.c_str()); -} - - -string PathHelpers::GetShortestRelativeAsciiPath(const string& baseFolder, const string& dependentPath) -{ - const string d = GetAbsoluteAsciiPath(dependentPath.c_str()); - if (d.empty()) - { - return PathHelpers::CanonicalizePath(dependentPath); - } - - const string b = GetAbsoluteAsciiPath(baseFolder.c_str()); - if (b.empty()) - { - return PathHelpers::CanonicalizePath(dependentPath); - } - - const string b2 = AddSeparator(b); - if (StringHelpers::StartsWithIgnoreCase(d, b2)) - { - const size_t len = d.length() - b2.length(); - // note: len == 0 is possible in case of "C:\" and "C:\". - return (len == 0) ? string(".") : d.substr(b2.length(), len); - } - - std::vector p0; - StringHelpers::Split(b2, string("\\"), true, p0); - std::vector p1; - StringHelpers::Split(d, string("\\"), true, p1); - - if (!StringHelpers::EqualsIgnoreCase(p0[0], p1[0])) - { - // got different drive letters - return PathHelpers::CanonicalizePath(dependentPath); - } - - if (StringHelpers::EqualsIgnoreCase(d, b)) - { - // exactly same path - return string("."); - } - - // Search for first non-matching component - for (int i = 1; i < (int)p0.size(); ++i) - { - if (StringHelpers::EqualsIgnoreCase(p0[i], p1[i])) - { - continue; - } - - string s; - s.reserve(Util::getMax(d.length(), b.length())); - for (int j = i; j < (int)p0.size(); ++j) - { - if (!p0[j].empty()) - { - s.append("..\\"); - } - } - for (int j = i; j < (int)p1.size(); ++j) - { - s.append(p1[j]); - if (j + 1 < (int)p1.size()) - { - s.push_back('\\'); - } - } - return s; - } - - assert(0); - return string(); -} - - -string PathHelpers::CanonicalizePath(const string& path) -{ - string result = RemoveSeparator(path); - // remove .\ or ./ at the path beginning. - if (result.length() > 2) - { - if (result[0] == '.' && (result[1] == '\\' || result[1] == '/')) - { - result = result.substr(2); - } - } - - return result; -} diff --git a/Code/Tools/CryCommonTools/PathHelpers.h b/Code/Tools/CryCommonTools/PathHelpers.h deleted file mode 100644 index 4cf509d876..0000000000 --- a/Code/Tools/CryCommonTools/PathHelpers.h +++ /dev/null @@ -1,110 +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_CRYCOMMONTOOLS_PATHHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_PATHHELPERS_H -#pragma once - -#include - -namespace PathHelpers -{ - // checks to see what the extension is in a string path - // returns the extension if found or an empty string if not found - string FindExtension(const string& path); - wstring FindExtension(const wstring& path); - - // replace an extension of a string path with a new specified extension - // returns a string with the replaced extension or the original string if unable to replace the extension - string ReplaceExtension(const string& path, const string& newExtension); - wstring ReplaceExtension(const wstring& path, const wstring& newExtension); - - // removes the extension of a specified string path - // returns a string with the extension removed or the original string if no extension was found - string RemoveExtension(const string& path); - wstring RemoveExtension(const wstring& path); - - // "abc/def/ghi" -> "abc/def" - // "abc/def/ghi/" -> "abc/def/ghi" - // "/" -> "/" - // gets the directory path out of a specified string path - // returns a string of the directory path - string GetDirectory(const string& path); - wstring GetDirectory(const wstring& path); - - // gets the file name out of a specified string path - // returns a string of the file name - string GetFilename(const string& path); - wstring GetFilename(const wstring& path); - - // add a backslash to a specified path if it doesn't already have a separator - // returns a path with the appended backslash unless there was already a separator - string AddSeparator(const string& path); - wstring AddSeparator(const wstring& path); - - // removes a forward slash or backslash from the end of a specified string path if found - // returns a string with the separator removed - string RemoveSeparator(const string& path); - wstring RemoveSeparator(const wstring& path); - - // removes extra forward slashes and backslashes if they're contained within the string path - // returns a string with the extra forward slashes and backslashes removed - string RemoveDuplicateSeparators(const string& path); - wstring RemoveDuplicateSeparators(const wstring& path); - - // It's not allowed to pass an absolute path in path2. - // Join(GetDirectory(fname), GetFilename(fname)) returns fname. - // merges two string paths together into one - // returns the merged string paths - string Join(const string& path1, const string& path2); - wstring Join(const wstring& path1, const wstring& path2); - - // checks to see if the path is a relative path - // returns true if it is or false if it is not - bool IsRelative(const string& path); - bool IsRelative(const wstring& path); - - // converts a string path to a unix path format - // returns the path in unix format - string ToUnixPath(const string& path); - wstring ToUnixPath(const wstring& path); - - // converts a string path to a dos path format - // returns the path in dos format - string ToDosPath(const string& path); - wstring ToDosPath(const wstring& path); - - // converts a string to the platform's path format. - // returns the path in the platform's path format. - string ToPlatformPath(const string& path); - wstring ToPlatformPath(const wstring& path); - - // char* pPath: in ASCII or UTF-8 encoding - // wchar_t* pPath: in UTF-16 encoding - // Non-ASCII components of pPath (everything from &pPath[0] to last non-ASCII - // part, inclusively) should exist on disk, otherwise an empty string is returned. - string GetAsciiPath(const char* pPath); - string GetAsciiPath(const wchar_t* pPath); - - // pPath passed should be in ASCII or UTF-8 encoding - string GetAbsoluteAsciiPath(const char* pPath); - // pPath passed should be in UTF-16 encoding - string GetAbsoluteAsciiPath(const wchar_t* pPath); - - // baseFolder and dependentPath passed should be in ASCII or UTF-8 encoding - string GetShortestRelativeAsciiPath(const string& baseFolder, const string& dependentPath); - - string CanonicalizePath(const string& path); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_PATHHELPERS_H diff --git a/Code/Tools/CryCommonTools/Platform/Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h b/Code/Tools/CryCommonTools/Platform/Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h deleted file mode 100644 index 03a0b4ff38..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h +++ /dev/null @@ -1,15 +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 - -#define AZ_TRAIT_CRYCOMMONTOOLS_FSEEK(file, offset, s) fseek(file, offset, s) -#define AZ_TRAIT_CRYCOMMONTOOLS_FTELL(file) ftell(file) diff --git a/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Linux.h b/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Linux.h deleted file mode 100644 index 81a38177c2..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Linux.h +++ /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. -* -*/ -#pragma once - -#include <../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h> - -#define AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 0 diff --git a/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Platform.h b/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Platform.h deleted file mode 100644 index 6232c6462b..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Platform.h +++ /dev/null @@ -1,15 +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 <../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h> -#include diff --git a/Code/Tools/CryCommonTools/Platform/Linux/platform_linux_files.cmake b/Code/Tools/CryCommonTools/Platform/Linux/platform_linux_files.cmake deleted file mode 100644 index 9c71b39bf1..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Linux/platform_linux_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 - ZipDir/ZipDir_Traits_Platform.h - ZipDir/ZipDir_Traits_Linux.h - ../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h -) diff --git a/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Mac.h b/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Mac.h deleted file mode 100644 index 111a31dc55..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Mac.h +++ /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. -* -*/ -#pragma once - -#include <../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h> - -#define AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 1 diff --git a/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Platform.h b/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Platform.h deleted file mode 100644 index e601614c59..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Platform.h +++ /dev/null @@ -1,14 +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 diff --git a/Code/Tools/CryCommonTools/Platform/Mac/platform_mac_files.cmake b/Code/Tools/CryCommonTools/Platform/Mac/platform_mac_files.cmake deleted file mode 100644 index b1fb3fa9a1..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Mac/platform_mac_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 - ZipDir/ZipDir_Traits_Platform.h - ZipDir/ZipDir_Traits_Mac.h - ../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h -) diff --git a/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Platform.h b/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Platform.h deleted file mode 100644 index 1d177a5c8c..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Platform.h +++ /dev/null @@ -1,14 +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 diff --git a/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Windows.h b/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Windows.h deleted file mode 100644 index 6d9c5314e4..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Windows.h +++ /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. -* -*/ -#pragma once - -#define AZ_TRAIT_CRYCOMMONTOOLS_FSEEK(file, offset, s) _fseeki64(file, (__int64)offset, s) -#define AZ_TRAIT_CRYCOMMONTOOLS_FTELL(file) (size_t)_ftelli64(file) -#define AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 1 diff --git a/Code/Tools/CryCommonTools/Platform/Windows/platform_windows_files.cmake b/Code/Tools/CryCommonTools/Platform/Windows/platform_windows_files.cmake deleted file mode 100644 index 252842e917..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Windows/platform_windows_files.cmake +++ /dev/null @@ -1,15 +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 - ZipDir/ZipDir_Traits_Platform.h - ZipDir/ZipDir_Traits_Windows.h -) diff --git a/Code/Tools/CryCommonTools/ProgressRange.h b/Code/Tools/CryCommonTools/ProgressRange.h deleted file mode 100644 index 297d862980..0000000000 --- a/Code/Tools/CryCommonTools/ProgressRange.h +++ /dev/null @@ -1,89 +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_CRYCOMMONTOOLS_PROGRESSRANGE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_PROGRESSRANGE_H -#pragma once - - -class ProgressRange -{ -public: - template - ProgressRange(T* object, void (T::* setter)(float progress)) - : m_target(new MethodTarget(object, setter)) - , m_progress(0.0f) - , m_start(0.0f) - , m_scale(1.0f) - { - m_target->Set(m_start); - } - - ProgressRange(ProgressRange& parent, float scale) - : m_target(new ParentRangeTarget(parent)) - , m_progress(0.0f) - , m_start(parent.m_progress) - , m_scale(scale) - { - m_target->Set(m_start); - } - - ~ProgressRange() - { - m_target->Set(m_start + m_scale); - delete m_target; - } - - void SetProgress(float progress) - { - assert(progress > -0.01f && progress < 1.1f); - m_progress = progress; - m_target->Set(m_start + m_scale * progress); - } - -private: - struct ITarget - { - virtual ~ITarget() {} - virtual void Set(float progress) = 0; - }; - - struct ParentRangeTarget - : public ITarget - { - ParentRangeTarget(ProgressRange& range) - : range(range) {} - virtual void Set(float progress) {range.SetProgress(progress); } - ProgressRange& range; - }; - - template - struct MethodTarget - : public ITarget - { - typedef void (T::* Setter)(float progress); - MethodTarget(T* object, Setter setter) - : object(object) - , setter(setter) {} - virtual void Set(float progress) {(object->*setter)(progress); } - T* object; - Setter setter; - }; - - ITarget* m_target; - float m_progress; - float m_start; - float m_scale; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_PROGRESSRANGE_H diff --git a/Code/Tools/CryCommonTools/PropertyHelpers.cpp b/Code/Tools/CryCommonTools/PropertyHelpers.cpp deleted file mode 100644 index aaaa1df309..0000000000 --- a/Code/Tools/CryCommonTools/PropertyHelpers.cpp +++ /dev/null @@ -1,125 +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 -#include "PropertyHelpers.h" -#include "StringHelpers.h" - - -bool PropertyHelpers::GetPropertyValue(const string& a_propertiesString, const char* a_propertyName, string& a_value) -{ - if ((a_propertyName == 0) || (a_propertyName[0] == 0)) - { - return false; - } - - const char* lineStart = a_propertiesString.c_str(); - - while (*lineStart) - { - string key; - string value; - - const size_t lineEndPosition = strcspn(lineStart, "\n"); - const size_t equalPosition = strcspn(lineStart, "="); - - if (equalPosition < lineEndPosition) - { - key = string(lineStart, equalPosition); - value = string(lineStart + equalPosition + 1, lineEndPosition - equalPosition - 1); - } - else - { - key = string(lineStart, lineEndPosition); - value = ""; - } - - key = StringHelpers::Trim(key); - - if (_stricmp(key.c_str(), a_propertyName) == 0) - { - a_value = StringHelpers::Trim(value); - return true; - } - - lineStart += lineEndPosition; - if (*lineStart) - { - ++lineStart; - } - } - - return false; -} - -void PropertyHelpers::SetPropertyValue(string& a_propertiesString, const char* a_propertyName, const char* a_value) -{ - if ((a_propertyName == 0) || (a_propertyName[0] == 0)) - { - return; - } - - const string newValue = StringHelpers::Trim(string(a_value)); - - const char* lineStart = a_propertiesString.c_str(); - - while (*lineStart) - { - const size_t lineEndPosition = strcspn(lineStart, "\n"); - const size_t equalPosition = strcspn(lineStart, "="); - - const string key = StringHelpers::Trim(string(lineStart, ((equalPosition < lineEndPosition) ? equalPosition : lineEndPosition))); - - if (_stricmp(key.c_str(), a_propertyName) == 0) - { - const size_t prefixSz = lineStart - a_propertiesString.c_str(); - const size_t expressionSz = lineEndPosition; - - if (newValue.empty()) - { - a_propertiesString = a_propertiesString.substr(0, prefixSz) + string(a_propertyName) + a_propertiesString.substr(prefixSz + expressionSz, string::npos); - } - else - { - a_propertiesString = a_propertiesString.substr(0, prefixSz) + string(a_propertyName) + string("=") + newValue + a_propertiesString.substr(prefixSz + expressionSz, string::npos); - } - return; - } - - lineStart += lineEndPosition; - if (*lineStart) - { - ++lineStart; - } - } - - if (a_propertiesString.empty() || (a_propertiesString[a_propertiesString.size() - 1] != '\n')) - { - a_propertiesString += string("\r\n"); - } - - if (newValue.empty()) - { - a_propertiesString += string(a_propertyName); - } - else - { - a_propertiesString += string(a_propertyName) + string("=") + newValue; - } -} - -bool PropertyHelpers::HasProperty(const string& a_propertiesString, const char* a_propertyName) -{ - string value; - return PropertyHelpers::GetPropertyValue(a_propertiesString, a_propertyName, value); -} diff --git a/Code/Tools/CryCommonTools/PropertyHelpers.h b/Code/Tools/CryCommonTools/PropertyHelpers.h deleted file mode 100644 index 0a2f428cc8..0000000000 --- a/Code/Tools/CryCommonTools/PropertyHelpers.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_PROPERTYHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_PROPERTYHELPERS_H -#pragma once - - -namespace PropertyHelpers -{ - bool GetPropertyValue(const string& propertiesString, const char* propertyName, string& value); - void SetPropertyValue(string& a_propertiesString, const char* propertyName, const char* value); - bool HasProperty(const string& propertiesString, const char* propertyName); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_PROPERTYHELPERS_H - - diff --git a/Code/Tools/CryCommonTools/STLHelpers.cpp b/Code/Tools/CryCommonTools/STLHelpers.cpp deleted file mode 100644 index c1b65f25b2..0000000000 --- a/Code/Tools/CryCommonTools/STLHelpers.cpp +++ /dev/null @@ -1,14 +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 diff --git a/Code/Tools/CryCommonTools/STLHelpers.h b/Code/Tools/CryCommonTools/STLHelpers.h deleted file mode 100644 index 6fbf0c7d11..0000000000 --- a/Code/Tools/CryCommonTools/STLHelpers.h +++ /dev/null @@ -1,54 +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_CRYCOMMONTOOLS_STLHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_STLHELPERS_H -#pragma once - - -#include - -namespace STLHelpers -{ - template - inline const char* constchar_cast(const Type& type) - { - return type; - } - - template <> - inline const char* constchar_cast(const std::string& type) - { - return type.c_str(); - } - - template - struct less_strcmp - { - bool operator()(const Type& left, const Type& right) const - { - return strcmp(constchar_cast(left), constchar_cast(right)) < 0; - } - }; - - template - struct less_stricmp - { - bool operator()(const Type& left, const Type& right) const - { - return _stricmp(constchar_cast(left), constchar_cast(right)) < 0; - } - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_STLHELPERS_H diff --git a/Code/Tools/CryCommonTools/SimpleBitmap.h b/Code/Tools/CryCommonTools/SimpleBitmap.h deleted file mode 100644 index ce4e93c626..0000000000 --- a/Code/Tools/CryCommonTools/SimpleBitmap.h +++ /dev/null @@ -1,508 +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 -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_SIMPLEBITMAP_H -#define CRYINCLUDE_CRYCOMMONTOOLS_SIMPLEBITMAP_H - -#include -#include // STL vector -#include "platform.h" // uint32 -#include "Cry_Math.h" // uint32 -#include "Util.h" // getMin() - -enum EImageFilteringMode -{ - eifm2DBorder = 0, - eifmCubemapFilter = 1, -}; - -namespace -{ - enum ECubeFace - { - ecfPosX = 0, - ecfNegX = 1, - ecfPosY = 2, - ecfNegY = 3, - ecfPosZ = 4, - ecfNegZ = 5, - ecfUnknown = -1, - }; - - struct JumpEntry - { - ECubeFace face; - int rot; - }; - - static const JumpEntry XJmpTable[] = - { - {ecfNegZ, 0}, {ecfPosZ, 2}, // ecfPosXa - {ecfPosZ, 0}, {ecfNegZ, 2}, // ecfNegXa - {ecfPosX, 1}, {ecfNegX, 3}, // ecfPosYa - {ecfPosX, 3}, {ecfNegX, 1}, // ecfNegYa - {ecfPosX, 0}, {ecfNegX, 0}, // ecfPosZa - {ecfPosX, 2}, {ecfNegX, 2} // ecfNegZa - }; - - static const JumpEntry YJmpTable[] = - { - {ecfPosY, 3}, {ecfNegY, 1}, // ecfPosXa - {ecfPosY, 1}, {ecfNegY, 3}, // ecfNegXa - {ecfNegZ, 2}, {ecfPosZ, 0}, // ecfPosYa - {ecfPosZ, 0}, {ecfNegZ, 2}, // ecfNegYa - {ecfNegY, 0}, {ecfPosY, 2}, // ecfPosZa - {ecfNegY, 2}, {ecfPosY, 0} // ecfNegZa - }; -} - -//! memory block used as bitmap -//! if you might need mipmaps please consider using ImageObject instead -template -class CSimpleBitmap -{ -public: - - CSimpleBitmap() - : m_dwWidth(0) - , m_dwHeight(0) - { - } - - ~CSimpleBitmap() - { - } - - // copy constructor - CSimpleBitmap(const CSimpleBitmap& rhs) - : m_dwWidth(0) - , m_dwHeight(0) - { - *this = rhs; // call assignment operator - } - - // assignment operator - CSimpleBitmap& operator=(const CSimpleBitmap& rhs) - { - if (&rhs != this) - { - m_data = rhs.m_data; - m_dwWidth = rhs.m_dwWidth; - m_dwHeight = rhs.m_dwHeight; - } - return *this; - } - - //! free all the memory resources - void FreeData() - { - m_data = std::vector(); - m_dwWidth = 0; - m_dwHeight = 0; - } - - //! /return true=success, false=failed because of low memory - bool SetSize(const uint32 indwWidth, const uint32 indwHeight) - { - if (m_dwWidth * m_dwHeight != indwWidth * indwHeight) - { - FreeData(); - m_data.resize(indwWidth * indwHeight); - m_dwWidth = indwWidth; - m_dwHeight = indwHeight; - } - return true; - } - -private: - ECubeFace JumpX(const ECubeFace srcFace, const bool isdXPos, int* rotCoords) const - { - int index = (int)srcFace * 2 + (isdXPos ? 0 : 1); - assert(index < sizeof(XJmpTable)); - const JumpEntry& jmp = XJmpTable[index]; - (*rotCoords) += jmp.rot; - return jmp.face; - } - - ECubeFace JumpY(const ECubeFace srcFace, const bool isdYPos, int* rotCoords) const - { - int index = (int)srcFace * 2 + (isdYPos ? 0 : 1); - assert(index < sizeof(YJmpTable)); - const JumpEntry& jmp = YJmpTable[index]; - (*rotCoords) += jmp.rot; - return jmp.face; - } - - // table that shows to which face we jump - ECubeFace JumpTable(const ECubeFace srcFace, int isdXPos, int isdYPos, int* rotCoords) const - { - if (isdXPos != 0) // recursive jump until dx==0 - { - int newSwap = 0; - ECubeFace newFace = JumpX(srcFace, isdXPos > 0, &newSwap); - (*rotCoords) += newSwap; - isdXPos -= ((isdXPos > 0) ? 1 : -1); - RotateCoord(&isdXPos, &isdYPos, newSwap); - return JumpTable(newFace, isdXPos, isdYPos, rotCoords); - } - if (isdYPos != 0) // recursive jump until dy==0 - { - int newSwap = 0; - ECubeFace newFace = JumpY(srcFace, isdYPos > 0, &newSwap); - (*rotCoords) += newSwap; - isdYPos -= ((isdYPos > 0) ? 1 : -1); - RotateCoord(&isdXPos, &isdYPos, newSwap); - return JumpTable(newFace, isdXPos, isdYPos, rotCoords); - } - assert(isdXPos == 0 && isdYPos == 0); - return srcFace; - } - - void RotateCoord(int* x, int* y, int mode) const - { - if (mode != 0) - { - if (mode == 2) // 180 degrees - { - (*x) = -(*x); - (*y) = -(*y); - } - else - { - if (mode == 1) // 90 dergees - { - int tmp = (*y); - (*y) = (*x); - (*x) = -tmp; - } - else // 270 degrees - { - assert(mode == 3); - int tmp = (*y); - (*y) = -(*x); - (*x) = tmp; - } - } - } - } - -public: - //! works only within the Bitmap for filter kernels - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - //! /param outValue - //! /return pointer to the raster element value if position was in the bitmap, NULL otherwise - const RasterElement* GetForFiltering_2D(const int inX, const int inY) const - { - return Get(inX, inY); - } - - //! works only within the Bitmap for filter kernels - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - //! /param outValue - //! /return pointer to the raster element value if position was in the bitmap, NULL otherwise - const RasterElement* GetForFiltering_Cubemap(const int inX, const int inY, const int srcX, const int srcY) const - { - if (m_data.empty()) - { - return false; - } - - assert(m_dwWidth == m_dwHeight * 6); - assert(srcX >= 0 && srcX < m_dwWidth); - assert(srcY >= 0 && srcY < m_dwHeight); - - const int sideSize = m_dwHeight; - - ECubeFace srcFace = (ECubeFace)(srcX / sideSize); - - if (inX >= 0 && inX < m_dwWidth && inY >= 0 && inY < m_dwHeight) // if we're inside the cubemap - { - ECubeFace destFace = (ECubeFace)(inX / sideSize); - if (destFace == srcFace) // we have the same face as src texel - { - return &m_data[inY * m_dwWidth + inX]; - } - } - const int halfSideSize = Util::getMax(1, sideSize / 2); - - // ternary logic - const int isdXPositive = int(floorf((float)inX / sideSize) - floorf((float)srcX / sideSize)); - const int isdYPositive = int(floorf((float)inY / sideSize) - floorf((float)srcY / sideSize)); - //if(isdXPositive==0&&isdYPositive<0&&srcFace==ecfPosY) - //{ - // int tmp = 0; - //} - assert(isdXPositive != 0 || isdYPositive != 0); - int rotCoords = 0; // quadrants to rotate coords - ECubeFace destFace = JumpTable(srcFace, isdXPositive, isdYPositive, &rotCoords); - rotCoords = ((rotCoords % 4) + 4) % 4; - int destX = inX - srcFace * sideSize; - int destY = inY; - - // rotate coords - destX -= halfSideSize; // center coords - destY -= halfSideSize; - RotateCoord(&destX, &destY, rotCoords); - destX += halfSideSize; // shift back - destY += halfSideSize; - - destX = ((destX + sideSize) % sideSize + sideSize) % sideSize; // tile in the face - destY = ((destY + sideSize) % sideSize + sideSize) % sideSize; - - destX = Util::getMin(destX, sideSize - 1); - destY = Util::getMin(destY, sideSize - 1); - destX += sideSize * destFace; - - assert(destX < m_dwWidth); - assert((ECubeFace)(destX / sideSize) == destFace); - - return &m_data[destY * m_dwWidth + destX]; - } - - const RasterElement* GetForFiltering(const Vec3& inDir) const - { - Vec3 vcAbsDir(fabsf(inDir.x), fabsf(inDir.y), fabsf(inDir.z)); - ECubeFace face; - int rotQuadrant = 0; - Vec2 texCoord; - if (vcAbsDir.x > vcAbsDir.y && vcAbsDir.x > vcAbsDir.z) - { - if (inDir.x > 0) - { - rotQuadrant = 3; - face = ecfPosX; - } - else - { - rotQuadrant = 1; - face = ecfNegX; - } - texCoord = Vec2(inDir.y, inDir.z) / vcAbsDir.x; - } - else if (vcAbsDir.y > vcAbsDir.x && vcAbsDir.y > vcAbsDir.z) - { - if (inDir.y > 0) - { - rotQuadrant = 2; - face = ecfPosY; - } - else - { - rotQuadrant = 0; - face = ecfNegY; - } - texCoord = Vec2(inDir.x, inDir.z) / vcAbsDir.y; - } - else - { - assert(vcAbsDir.z >= vcAbsDir.x && vcAbsDir.z >= vcAbsDir.y); - if (inDir.z > 0) - { - rotQuadrant = 1; - face = ecfPosZ; - } - else - { - rotQuadrant = 3; - face = ecfNegZ; - } - texCoord = Vec2(inDir.x, inDir.y) / vcAbsDir.z; - } - - texCoord = texCoord * .5f + Vec2(.5f, .5f); - assert(texCoord.x <= 1.f && texCoord.x >= 0); - assert(texCoord.y <= 1.f && texCoord.y >= 0); - - Vec2i texelPos(texCoord.x * (m_dwHeight - 1), texCoord.y * (m_dwHeight - 1)); - - texelPos.x += face * m_dwHeight; // plus face - return &m_data[texelPos.y * m_dwWidth + texelPos.x]; - } - - //! works only within the Bitmap - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - //! /param outValue - //! /return pointer to raster element value if position was in the bitmap, NULL otherwise - const RasterElement* Get(const uint32 inX, const uint32 inY) const - { - if (m_data.empty()) - { - return 0; - } - if (inX >= m_dwWidth || inY >= m_dwHeight) - { - return 0; - } - return &m_data[inY * m_dwWidth + inX]; - } - - - //! bilinear, works only well within 0..1 - bool GetFiltered(const float infX, const float infY, RasterElement& outValue) const - { - float fIX = floorf(infX), fIY = floorf(infY); - float fFX = infX - fIX, fFY = infY - fIY; - int iXa = (int)fIX, iYa = (int)fIY; - int iXb = iXa + 1, iYb = iYa + 1; - - if (iXb == m_dwWidth) - { - iXb = 0; - } - - if (iYb == m_dwHeight) - { - iYb = 0; - } - - const RasterElement* p[4]; - - if ((p[0] = Get(iXa, iYa)) && (p[1] = Get(iXb, iYa)) && (p[2] = Get(iXa, iYb)) && (p[3] = Get(iXb, iYb))) - { - outValue = - (*p[0]) * ((1.0f - fFX) * (1.0f - fFY)) + // left top - (*p[1]) * ((fFX) * (1.0f - fFY)) + // right top - (*p[2]) * ((1.0f - fFX) * (fFY)) + // left bottom - (*p[3]) * ((fFX) * (fFY)); // right bottom - - return true; - } - - return false; - } - - //! works only within the Bitmap - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - const RasterElement& GetRef(const uint32 inX, const uint32 inY) const - { - assert(!m_data.empty()); - assert(inX < m_dwWidth && inY < m_dwHeight); - return m_data[inY * m_dwWidth + inX]; - } - - //! works only within the Bitmap - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - RasterElement& GetRef(const uint32 inX, const uint32 inY) - { - assert(!m_data.empty()); - assert(inX < m_dwWidth && inY < m_dwHeight); - return m_data[inY * m_dwWidth + inX]; - } - - //! works even outside of the Bitmap (tiled) - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - RasterElement& GetTiledRef(const uint32 inX, const uint32 inY) - { - assert(!m_data.empty()); - const uint32 x = inX % m_dwWidth; - const uint32 y = inY % m_dwHeight; - return m_data[y * m_dwWidth + x]; - } - - //! works only within the Bitmap - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - //! /param inValue - bool Set(const uint32 inX, const uint32 inY, const RasterElement& inValue) - { - if (m_data.empty()) - { - assert(!m_data.empty()); - return false; - } - - if (inX >= m_dwWidth || inY >= m_dwHeight) - { - return false; - } - - m_data[inY * m_dwWidth + inX] = inValue; - - return true; - } - - uint32 GetWidth() const - { - return m_dwWidth; - } - - uint32 GetHeight() const - { - return m_dwHeight; - } - - // Returns size of one line in bytes - size_t GetPitch() const - { - return m_dwWidth * sizeof(RasterElement); - } - - uint32 GetBitmapSizeInBytes() const - { - return m_dwWidth * m_dwHeight * sizeof(RasterElement); - } - - //! /return could be 0 if the pixel is outside the bitmap - const RasterElement* GetPointer(const uint32 inX = 0, const uint32 inY = 0) const - { - if (inX >= m_dwWidth || inY >= m_dwHeight) - { - return 0; - } - return &m_data[inY * m_dwWidth + inX]; - } - - //! /return could be 0 if the pixel is outside the bitmap - RasterElement* GetPointer(const uint32 inX = 0, const uint32 inY = 0) - { - if (inX >= m_dwWidth || inY >= m_dwHeight) - { - return 0; - } - return &m_data[inY * m_dwWidth + inX]; - } - - void Fill(const RasterElement& inValue) - { - const uint32 n = m_dwHeight * m_dwWidth; - for (uint32 i = 0; i < n; ++i) - { - m_data[i] = inValue; - } - } - - bool IsValid() const - { - return !m_data.empty(); - } - -protected: // ------------------------------------------------------ - - std::vector m_data; //!< [m_dwWidth * m_dwHeight] - - uint32 m_dwWidth; - uint32 m_dwHeight; -}; - - - - - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_SIMPLEBITMAP_H diff --git a/Code/Tools/CryCommonTools/SimpleStringPool.h b/Code/Tools/CryCommonTools/SimpleStringPool.h deleted file mode 100644 index 4e65ce1be6..0000000000 --- a/Code/Tools/CryCommonTools/SimpleStringPool.h +++ /dev/null @@ -1,249 +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_CRYCOMMONTOOLS_SIMPLESTRINGPOOL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_SIMPLESTRINGPOOL_H -#pragma once - -#include - -///////////////////////////////////////////////////////////////////// -// String pool implementation. -// Inspired by expat implementation. -///////////////////////////////////////////////////////////////////// -class CSimpleStringPool -{ -public: - enum - { - STD_BLOCK_SIZE = 4096 - }; - struct BLOCK - { - BLOCK* next; - int size; - char s[1]; - }; - unsigned int m_blockSize; - BLOCK* m_blocks; - BLOCK* m_free_blocks; - const char* m_end; - char* m_ptr; - char* m_start; - int nUsedSpace; - int nUsedBlocks; - - CSimpleStringPool() - { - m_blockSize = STD_BLOCK_SIZE; - m_blocks = 0; - m_start = 0; - m_ptr = 0; - m_end = 0; - nUsedSpace = 0; - nUsedBlocks = 0; - m_free_blocks = 0; - } - ~CSimpleStringPool() - { - BLOCK* pBlock = m_blocks; - while (pBlock) - { - BLOCK* temp = pBlock->next; - //nFree++; - free(pBlock); - pBlock = temp; - } - pBlock = m_free_blocks; - while (pBlock) - { - BLOCK* temp = pBlock->next; - //nFree++; - free(pBlock); - pBlock = temp; - } - m_blocks = 0; - m_ptr = 0; - m_start = 0; - m_end = 0; - } - void SetBlockSize(unsigned int nBlockSize) - { - if (nBlockSize > 1024 * 1024) - { - nBlockSize = 1024 * 1024; - } - unsigned int size = 512; - while (size < nBlockSize) - { - size *= 2; - } - - m_blockSize = size - offsetof(BLOCK, s); - } - void Clear() - { - if (m_free_blocks) - { - BLOCK* pLast = m_blocks; - while (pLast) - { - BLOCK* temp = pLast->next; - if (!temp) - { - break; - } - pLast = temp; - } - if (pLast) - { - pLast->next = m_free_blocks; - } - } - m_free_blocks = m_blocks; - m_blocks = 0; - m_start = 0; - m_ptr = 0; - m_end = 0; - nUsedSpace = 0; - } - char* Append(const char* ptr, int nStrLen) - { - char* ret = m_ptr; - if (m_ptr && nStrLen + 1 < (m_end - m_ptr)) - { - memcpy(m_ptr, ptr, nStrLen); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - } - else - { - int nNewBlockSize = (std::max)(nStrLen + 1, (int)m_blockSize); - AllocBlock(nNewBlockSize, nStrLen + 1); - memcpy(m_ptr, ptr, nStrLen); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - ret = m_start; - } - nUsedSpace += nStrLen; - return ret; - } - char* ReplaceString(const char* str1, const char* str2) - { - int nStrLen1 = check_cast(strlen(str1)); - int nStrLen2 = check_cast(strlen(str2)); - - // undo ptr1 add. - if (m_ptr != m_start) - { - m_ptr = m_ptr - nStrLen1 - 1; - } - - assert(m_ptr == str1); - - int nStrLen = nStrLen1 + nStrLen2; - - char* ret = m_ptr; - if (m_ptr && nStrLen + 1 < (m_end - m_ptr)) - { - memcpy(m_ptr, str1, nStrLen1); - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - } - else - { - int nNewBlockSize = (std::max)(nStrLen + 1, check_cast(m_blockSize)); - if (m_ptr == m_start) - { - ReallocBlock(nNewBlockSize * 2); // Reallocate current block. - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - } - else - { - AllocBlock(nNewBlockSize, nStrLen + 1); - memcpy(m_ptr, str1, nStrLen1); - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - } - - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - ret = m_start; - } - nUsedSpace += nStrLen; - return ret; - } -private: - void AllocBlock(int blockSize, int nMinBlockSize) - { - if (m_free_blocks) - { - BLOCK* pBlock = m_free_blocks; - BLOCK* pPrev = 0; - while (pBlock) - { - if (pBlock->size >= nMinBlockSize) - { - // Reuse free block - if (pPrev) - { - pPrev->next = pBlock->next; - } - else - { - m_free_blocks = pBlock->next; - } - - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + pBlock->size; - return; - } - pPrev = pBlock; - pBlock = pBlock->next; - } - } - size_t nMallocSize = offsetof(BLOCK, s) + blockSize * sizeof(char); - //nMallocs++; - BLOCK* pBlock = (BLOCK*)malloc(nMallocSize); - pBlock->size = blockSize; - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + blockSize; - nUsedBlocks++; - } - void ReallocBlock(int blockSize) - { - BLOCK* pThisBlock = m_blocks; - BLOCK* pPrevBlock = m_blocks->next; - m_blocks = pPrevBlock; - - size_t nMallocSize = offsetof(BLOCK, s) + blockSize * sizeof(char); - - //nMallocs++; - BLOCK* pBlock = (BLOCK*)realloc(pThisBlock, nMallocSize); - pBlock->size = blockSize; - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + blockSize; - } -}; - - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_SIMPLESTRINGPOOL_H diff --git a/Code/Tools/CryCommonTools/StealingThreadPool.cpp b/Code/Tools/CryCommonTools/StealingThreadPool.cpp deleted file mode 100644 index e4a6f87243..0000000000 --- a/Code/Tools/CryCommonTools/StealingThreadPool.cpp +++ /dev/null @@ -1,580 +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 -#include "StealingThreadPool.h" -#include "ThreadUtils.h" -#include -#include -#include - -namespace ThreadUtils { - class StealingWorker - { - public: - StealingWorker(StealingThreadPool* pool, int index, bool trace, AZStd::condition_variable& jobsCV) - : m_pool(pool) - , m_index(index) - , m_tracingEnabled(trace) - , m_lastStartTime(0) - , m_exitFlag(0) - , m_jobsCV(jobsCV) - { - } - - static unsigned int __stdcall ThreadFunc(void* param) - { - StealingWorker* self = (StealingWorker*)(param); - self->Work(); - return 0; - } - - void Start(int startTime) - { - m_lastStartTime = startTime; - - string threadName; - threadName.Format("StealingWorker %d", m_index); - - AZStd::thread_desc threadDesc; - threadDesc.m_name = threadName.c_str(); - m_thread = AZStd::thread(AZStd::bind(StealingWorker::ThreadFunc, (void*)this), &threadDesc); - - } - - bool GetJobLockless(Job& job) - { - if (m_jobs.empty()) - { - return false; - } - job = m_jobs.front(); - m_jobs.pop_front(); - - return true; - } - - bool GetJob(Job& job) - { - AZStd::lock_guard lock(m_lockJobs); - return GetJobLockless(job); - } - - void ExecuteJob(Job& job) - { - --m_pool->m_numJobsWaitingForExecution; - job.Run(); - - if (m_tracingEnabled) - { - int time = (int)GetTickCount(); - - JobTrace trace; - trace.m_job = job; - trace.m_duration = time - m_lastStartTime; - m_traces.push_back(trace); - - m_lastStartTime = time; - } - - --m_pool->m_numJobs; - m_pool->m_jobFinishedCV.notify_all(); - } - - bool TryToStealJob(Job& job) - { - while (true) - { - StealingWorker* victim = m_pool->FindBestVictim(m_index); - if (!victim) - { - return false; - } - if (StealJobs(job, victim)) - { - return true; - } - } - } - - void Work() - { - Job job; - - while (true) - { - AZStd::mutex loadMutex; - AZStd::unique_lock loadLock(loadMutex, AZStd::defer_lock_t()); - - while (m_pool->m_numJobsWaitingForExecution == 0) - { - - m_jobsCV.wait(loadLock); - - if (m_exitFlag == 1) - { - return; - } - } - - if (GetJob(job)) - { - ExecuteJob(job); - } - else if (TryToStealJob(job)) - { - ExecuteJob(job); - } - } - } - - // Called from different worker thread - bool StealJobs(Job& job, StealingWorker* victim) - { - if (victim == this) - { - assert(0 && "Trying to steal own jobs"); - return false; - } - - bool order = m_index < victim->m_index; - AZStd::lock_guard lock1(order ? m_lockJobs : victim->m_lockJobs); - AZStd::lock_guard lock2(order ? victim->m_lockJobs : m_lockJobs); - - if (victim->m_jobs.empty()) - { - return false; - } - - int numJobs = (int)victim->m_jobs.size(); - size_t stealUntil = numJobs - numJobs / 2; - Jobs::iterator begin = victim->m_jobs.begin(); - Jobs::iterator end = victim->m_jobs.begin() + stealUntil; - - m_jobs.insert(m_jobs.end(), begin, end); - victim->m_jobs.erase(begin, end); - - return GetJobLockless(job); - } - - // Called from any thread - void Submit(const Job& job) - { - AZStd::lock_guard lock(m_lockJobs); - - m_jobs.push_back(job); - m_jobs.back().m_debugInitialThread = m_index; - - m_jobsCV.notify_one(); - } - - // Called from any thread - void Submit(const Jobs& jobs) - { - const size_t numJobs = jobs.size(); - - AZStd::lock_guard lock(m_lockJobs); - - m_jobs.insert(m_jobs.begin(), jobs.begin(), jobs.end()); - for (size_t i = 0; i < numJobs; ++i) - { - m_jobs[i].m_debugInitialThread = m_index; - } - - m_jobsCV.notify_one(); - } - - long NumJobsPending() const - { - AZStd::lock_guard lock(m_lockJobs); - return m_jobs.size(); - } - - // Called from main thread - void SignalExit() - { - CryInterlockedCompareExchange(&m_exitFlag, 1, 0); - } - - void GetTraces(JobTraces& traces) - { - if (m_tracingEnabled) - { - m_traces.swap(traces); - } - } - - private: - StealingThreadPool* m_pool; - AZStd::thread m_thread; - int m_index; - bool m_tracingEnabled; - int m_lastStartTime; - JobTraces m_traces; - - Jobs m_jobs; - mutable AZStd::mutex m_lockJobs; - AZStd::condition_variable& m_jobsCV; - - LONG m_exitFlag; - friend class StealingThreadPool; - }; - - // --------------------------------------------------------------------------- - - StealingThreadPool::StealingThreadPool(int numThreads, bool enableTracing) - : m_numThreads(numThreads) - , m_numJobs(0) - , m_numJobsWaitingForExecution(0) - , m_enableTracing(enableTracing) - { - m_workers.resize(numThreads); - for (int i = 0; i < numThreads; ++i) - { - m_workers[i] = new StealingWorker(this, i, m_enableTracing, m_jobsCV); - } - } - - StealingThreadPool::~StealingThreadPool() - { - WaitAllJobs(); - - size_t numThreads = m_workers.size(); - for (size_t i = 0; i < numThreads; ++i) - { - m_workers[i]->SignalExit(); - } - m_jobsCV.notify_all(); - - m_threadTraces.resize(numThreads); - for (size_t i = 0; i < numThreads; ++i) - { - m_workers[i]->GetTraces(m_threadTraces[i]); - } - } - - void StealingThreadPool::Start() - { - int startTime = (int)GetTickCount(); - size_t numThreads = m_workers.size(); - for (int i = 0; i < numThreads; ++i) - { - m_workers[i]->Start(startTime); - } - } - - void StealingThreadPool::WaitAllJobs() - { - AZStd::mutex loadMutex; - AZStd::unique_lock loadLock(loadMutex, AZStd::defer_lock_t()); - - while (m_numJobs > 0) - { - m_jobsCV.wait(loadLock); - } - } - - // Called from any thread - void StealingThreadPool::Submit(const Job& job) - { - ++m_numJobs; - ++m_numJobsWaitingForExecution; - - if (StealingWorker* worker = FindWorstWorker()) - { - worker->Submit(job); - } - } - - // Called from any thread - void StealingThreadPool::Submit(const Jobs& jobs) - { - m_numJobs += jobs.size(); - m_numJobsWaitingForExecution += jobs.size(); - if (StealingWorker* worker = FindWorstWorker()) - { - worker->Submit(jobs); - } - } - - JobGroup* StealingThreadPool::CreateJobGroup(JobFunc func, void* data) - { - return new JobGroup(this, func, data); - } - - StealingWorker* StealingThreadPool::FindBestVictim(int exceptFor) const - { - int maxJobs = 0; - StealingWorker* bestVictim = 0; - for (size_t i = 0; i < m_workers.size(); ++i) - { - if (i == exceptFor) - { - continue; - } - StealingWorker* worker = m_workers[i]; - long numJobs = worker->NumJobsPending(); - if (numJobs > maxJobs) - { - maxJobs = numJobs; - bestVictim = worker; - } - } - return bestVictim; - } - - StealingWorker* StealingThreadPool::FindWorstWorker() const - { - if (m_workers.empty()) - { - return 0; - } - - int minJobs = INT_MAX; - StealingWorker* worstWorker = m_workers[0]; - for (size_t i = 0; i < m_workers.size(); ++i) - { - StealingWorker* worker = m_workers[i]; - long numJobs = worker->NumJobsPending(); - if (numJobs < minJobs) - { - minJobs = numJobs; - worstWorker = worker; - } - } - return worstWorker; - } - - static bool WriteString(FILE* f, const char* str) - { - return fwrite(str, strlen(str), 1, f) == 1; - } - - static int Interpolate(int a, int b, float phase) - { - return int(float(a) + float(b - a) * phase); - } - - static int InterpolateColor(int c1, int c2, float phase) - { - const int r1 = (c1 & 0x0000ff); - const int g1 = (c1 & 0x00ff00) >> 8; - const int b1 = (c1 & 0xff0000) >> 16; - const int r2 = (c2 & 0x0000ff); - const int g2 = (c2 & 0x00ff00) >> 8; - const int b2 = (c2 & 0xff0000) >> 16; - - const int r = min(255, max(0, Interpolate(r1, r2, phase))); - const int g = min(255, max(0, Interpolate(g1, g2, phase))); - const int b = min(255, max(0, Interpolate(b1, b2, phase))); - - return r + (g << 8) + (b << 16); - } - - static const int g_animColors[] = { - 0xff0000, 0x0000ff, 0x00ff00, - 0xffff00, 0xff00ff, 0x00ffff, - 0xff8080, 0x8080ff, 0x80ff80, - 0xffff80, 0xff80ff, 0x80ffff - }; - - static int ColorizeJobTrace(const ThreadUtils::JobTrace& trace) - { - const int numColors = sizeof(g_animColors) / sizeof(g_animColors[0]); - const int initialThread = trace.m_job.m_debugInitialThread; - const int index = initialThread % numColors; - const float brightness = aznumeric_cast(pow(0.5f, initialThread / numColors)); - return InterpolateColor(0, InterpolateColor(g_animColors[index], 0xffffff, 0.5f), brightness); - } - - bool StealingThreadPool::SaveTracesGraph(const char* filename) - { - if (!m_enableTracing) - { - return false; - } - - const float screenWidth = 1240.0f; - - float duration = 0; - for (size_t t = 0; t < m_threadTraces.size(); ++t) - { - float threadDuration = 0; - const JobTraces& traces = m_threadTraces[t]; - for (int i = 0; i < traces.size(); ++i) - { - threadDuration += traces[i].m_duration; - } - duration = max(threadDuration, duration); - } - - const float padding = 10.0f; - const float rowHeight = 60.0f; - const float xScale = fabsf(duration) > FLT_EPSILON ? (screenWidth - padding * 2.0f) / duration : 1.0f; - - const float width = screenWidth; - const float height = (m_threadTraces.size() + 0.5f) * rowHeight; - - FILE* f = nullptr; - azfopen(&f, filename, "wt"); - if (!f) - { - return false; - } - - char buf[4096]; - azsnprintf(buf, sizeof(buf), - "\n" - "\n", - width, height - ); - - if (!WriteString(f, buf)) - { - return false; - } - - for (size_t t = 0; t < m_threadTraces.size(); ++t) - { - float x = padding; - float y = rowHeight * 0.5f + rowHeight * t; - - azsnprintf(buf, sizeof(buf), - " Thread %i\n", - x, y, x, y, static_cast(t + 1)); - - if (!WriteString(f, buf)) - { - return false; - } - - - y += padding; - - const ThreadUtils::JobTraces& traces = m_threadTraces[t]; - for (int i = 0; i < traces.size(); ++i) - { - const float width2 = traces[i].m_duration * xScale; - const float height2 = rowHeight * 0.5f; - - const int color = ColorizeJobTrace(traces[i]); - const int strokeColor = 0; - azsnprintf(buf, sizeof(buf), - " \n", - color, strokeColor, width2, height2, x, y); - - if (!WriteString(f, buf)) - { - return false; - } - - x += width2; - } - - y += rowHeight; - } - - if (!WriteString(f, "\n\n")) - { - return false; - } - - fclose(f); - return true; - } - - // --------------------------------------------------------------------------- - - void JobGroup::Process(JobGroup::GroupInfo* info) - { - info->m_job.Run(); - - long jobsLeft = --info->m_group->m_numJobsRunning; - assert(jobsLeft >= 0); - if (jobsLeft == 0) - { - info->m_group->m_finishJob.Run(); - delete info->m_group; - } - } - - JobGroup::JobGroup(StealingThreadPool* pool, JobFunc func, void* data) - : m_pool(pool) - , m_numJobsRunning(0) - , m_finishJob(func, data) - , m_submited(false) - { - } - - void JobGroup::Submit() - { - if (m_submited) - { - assert(0); - return; - } - - if (m_numJobsRunning == 0) - { - m_pool->Submit(m_finishJob); - return; - } - - Jobs jobs; - jobs.resize(m_infos.size()); - for (size_t i = 0; i < m_infos.size(); ++i) - { - jobs[i] = Job((JobFunc) & JobGroup::Process, &m_infos[i]); - } - - m_pool->Submit(jobs); - } - - void JobGroup::Add(JobFunc func, void* data) - { - if (m_submited) - { - assert(0); - return; - } - - GroupInfo info; - info.m_job = Job(func, data); - info.m_group = this; - - m_infos.push_back(info); - ++m_numJobsRunning; - } -} diff --git a/Code/Tools/CryCommonTools/StealingThreadPool.h b/Code/Tools/CryCommonTools/StealingThreadPool.h deleted file mode 100644 index 8576ed0416..0000000000 --- a/Code/Tools/CryCommonTools/StealingThreadPool.h +++ /dev/null @@ -1,123 +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_CRYCOMMONTOOLS_STEALINGTHREADPOOL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_STEALINGTHREADPOOL_H -#pragma once - - -#include "ThreadUtils.h" -#include -#include -#include -#include -#if AZ_TRAIT_OS_PLATFORM_APPLE -#include "AppleSpecific.h" -#endif - -namespace ThreadUtils { - class StealingWorker; - class JobGroup; - - // Simple stealing thread pool - class StealingThreadPool - { - public: - explicit StealingThreadPool(int numThreads, bool enableTracing = false); - ~StealingThreadPool(); - - void Start(); - void WaitAllJobs(); - - const std::vector& Traces() const{ return m_threadTraces; } - bool SaveTracesGraph(const char* filename); - - // Submits single independent job - template - void Submit(void(* jobFunc)(T*), T* data) - { - Submit(Job((JobFunc)jobFunc, data)); - } - - // Create a group of jobs. A group of jobs can be followed by one "finishing" job. - // It is a way to express dependencies between jobs. - template - JobGroup* CreateJobGroup(void(* jobFunc)(T*), T* data) - { - return CreateJobGroup((JobFunc)jobFunc, (void*)data); - } - - uint GetNumThreads() const { return aznumeric_cast(m_numThreads); } - - private: - StealingWorker* FindBestVictim(int exceptFor) const; - StealingWorker* FindWorstWorker() const; - - void Submit(const Job& job); - void Submit(const Jobs& jobs); - JobGroup* CreateJobGroup(JobFunc, void* data); - - size_t m_numThreads; - typedef std::vector ThreadWorkers; - ThreadWorkers m_workers; - - bool m_enableTracing; - std::vector m_threadTraces; - - AZStd::atomic_long m_numJobsWaitingForExecution; - AZStd::atomic_long m_numJobs; - AZStd::condition_variable m_jobsCV; - AZStd::condition_variable m_jobFinishedCV; - - - friend class JobGroup; - friend class StealingWorker; - }; - - - // JobGroup represents a group of jobs that can be followed by one "finishing" - // job. This is a way to express dependencies between jobs. - class JobGroup - { - public: - template - void Add(void(* jobFunc)(T*), T* data) - { - Add((JobFunc)jobFunc, data); - } - - // Submits group to thread pool - void Submit(); - private: - struct GroupInfo - { - Job m_job; - JobGroup* m_group; - }; - typedef std::vector GroupInfos; - - JobGroup(StealingThreadPool* pool, JobFunc func, void* data); - - static void Process(JobGroup::GroupInfo* job); - void Add(JobFunc func, void* data); - - volatile LONG m_numJobsRunning; - StealingThreadPool* m_pool; - GroupInfos m_infos; - Job m_finishJob; - bool m_submited; - friend class StealingThreadPool; - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_STEALINGTHREADPOOL_H diff --git a/Code/Tools/CryCommonTools/SuffixUtil.h b/Code/Tools/CryCommonTools/SuffixUtil.h deleted file mode 100644 index 632e86525f..0000000000 --- a/Code/Tools/CryCommonTools/SuffixUtil.h +++ /dev/null @@ -1,59 +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_CRYCOMMONTOOLS_SUFFIXUTIL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_SUFFIXUTIL_H -#pragma once - - -// convenience class to work with suffixes in filenames, like in like dirt_ddn.dds -class SuffixUtil -{ -public: - - // filename allowed to have many suffixes (e.g. "test_ddn_bump.dds" has "bump" and "ddn" - // as suffixes (assuming that suffixSeparator is '_'). - // suffixes in file extension are also considered (e.g. "test_abc.my_data" has "abc" and "data" as suffixes) - // suffixes in path part are also considered. if it's not what you want - remove path before calling this function. - // comparison is case insensitive - static bool HasSuffix(const char* const filename, const char suffixSeparator, const char* const suffix) - { - assert(filename); - assert(suffix && suffix[0]); - - const size_t suffixLen = strlen(suffix); - - for (const char* p = filename; *p; ++p) - { - if (p[0] != suffixSeparator) - { - continue; - } - - if (azmemicmp(&p[1], suffix, suffixLen) != 0) - { - continue; - } - - const char c = p[1 + suffixLen]; - if ((c == 0) || (c == suffixSeparator) || (c == '.')) - { - return true; - } - } - - return false; - } -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_SUFFIXUTIL_H diff --git a/Code/Tools/CryCommonTools/SummedAreaFilterKernel.cpp b/Code/Tools/CryCommonTools/SummedAreaFilterKernel.cpp deleted file mode 100644 index 3ee26df3bd..0000000000 --- a/Code/Tools/CryCommonTools/SummedAreaFilterKernel.cpp +++ /dev/null @@ -1,442 +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 -#include -#include // assert() -#include // floorf() -#include "SummedAreaFilterKernel.h" // CSummedAreaFilterKernel - -CSummedAreaFilterKernel::CSummedAreaFilterKernel() -{ - m_eFilterType = eEmpty; - m_fCorrectionFactor = 0.0f; -} - -// http://www.sixsigma.de/english/sixsigma/6s_e_gauss.htm -bool CSummedAreaFilterKernel::CreateFromGauss(const unsigned long indwSize) -{ - assert(indwSize > 2); - - int iInit = 0; - - if (!Alloc(indwSize, indwSize, &iInit)) - { - return false; - } - - for (unsigned long y = 0; y < indwSize; y++) - { - for (unsigned long x = 0; x < indwSize; x++) - { - float fX = (float)(x) - (float)(indwSize) * 0.5f; - float fY = (float)(y) - (float)(indwSize) * 0.5f; - - double r1 = sqrt(fX * fX + fY * fY) / (indwSize * 0.5 - 2.0); - - if (r1 > 1) - { - m_pData[y * indwSize + x] = 0; - } - else - { - double fSigma = 1.0 / 3.0; // we aim for 6*sigma = 99,99996 of all values - - double fWeight = exp(-r1 * r1 / (2 * fSigma * fSigma)); - - fWeight -= (1.0 - 0.9999996); - - m_pData[y * indwSize + x] = (int)(255.0f * fWeight); - } - } - } - - m_eFilterType = eGaussBlur; - _SumUpTableAndNormalize(); - return true; -} - - -// create summed area table -void CSummedAreaFilterKernel::_SumUpTableAndNormalize() -{ - for (unsigned long y = 0; y < m_dwHeight; y++) - { - int iFromLeft = 0; - - for (unsigned long x = 0; x < m_dwWidth; x++) - { - iFromLeft += m_pData[y * m_dwWidth + x]; - - if (y != 0) - { - m_pData[y * m_dwWidth + x] = iFromLeft + m_pData[(y - 1) * m_dwWidth + x]; - } - else - { - m_pData[y * m_dwWidth + x] = iFromLeft; - } - } - } - - m_fCorrectionFactor = 1.0f / ((float)m_pData[m_dwHeight * m_dwWidth - 1]); -} - - -// windows size 16x16 = radius 8 -bool CSummedAreaFilterKernel::CreateFromSincCalc(const unsigned long indwSize) -{ - assert(indwSize > 2); - - int iInit = 0; - - if (!Alloc(indwSize, indwSize, &iInit)) - { - return false; - } - - for (unsigned long y = 0; y < indwSize; y++) - { - for (unsigned long x = 0; x < indwSize; x++) - { - float fX = (float)(x - indwSize * 0.5f); - float fY = (float)(y - indwSize * 0.5f); - - float r1 = sqrtf(fX * fX + fY * fY) / (indwSize * 0.5f - 2.0f); - - if (r1 > 1.0f) - { - m_pData[y * indwSize + x] = 0; - } - else - { - r1 *= 3.1415926535897932384626433832795f; - - float r2 = r1 * 8.0f; - - // http://home.no.net/dmaurer/~dersch/interpolator/interpolator.html - // weight = [ sin(x*pi) / (x*pi) ] * [ sin(x*pi / 8) / (x*pi/8) ] - - // http://www.binbooks.com/books/photo/i/l/57186AF8DE - // sinc(x) = sin(pi * x) / (pi * x) - // L8interp(x) = sinc(x) * sinc(x/8) if abs(x) <= 8 - // = 0 if abs(x) > 8 - - float fWeight = (sinf(r1) * sinf(r2)) / (r1 * r2); - - m_pData[y * indwSize + x] = (int)(255.0f * fWeight); - } - } - } - - m_eFilterType = eSinc; - _SumUpTableAndNormalize(); - - return true; -} - - - - - -bool CSummedAreaFilterKernel::CreateFromRAWFile(const char* filename, const unsigned long indwSize, const int iniMidValue) -{ - assert(iniMidValue >= 0 && iniMidValue < 255); - - int iInit = 0; - - if (!Alloc(indwSize, indwSize, &iInit)) - { - return false; - } - - FILE* in = fopen(filename, "rb"); - if (!in) - { - return false; - } - - for (unsigned long y = 0; y < m_dwHeight; y++) - { - for (unsigned long x = 0; x < m_dwWidth; x++) - { - unsigned char val; - - if (fread(&val, 1, 1, in) != 1) - { - fclose(in); - return false; - } - - m_pData[y * m_dwWidth + x] = (int)val - iniMidValue; - } - } - - fclose(in); - - m_eFilterType = eRAW; - _SumUpTableAndNormalize(); - - return true; -} - - -std::string CSummedAreaFilterKernel::GetInfoString(void) const -{ - std::string sRet = "FilterKernel("; - - switch (m_eFilterType) - { - case eEmpty: - sRet += "Empty"; - break; - case eSinc: - sRet += "Sinc16x16"; - break; - case eRAW: - sRet += "RAW"; - break; - case eGaussBlur: - sRet += "GaussBlur"; - break; - case eGaussSharp: - sRet += "GaussSharp"; - break; - default: - assert(0); - } - - sRet += ")"; - - return(sRet); -} - -float CSummedAreaFilterKernel::GetAreaNonAA(float infAx, float infAy, float infDx, float infDy) const -{ - assert(m_eFilterType != eEmpty); - - int ax = (int)floorf(infAx * 127.5f + 127.5f); - int ay = (int)floorf(infAy * 127.5f + 127.5f); - int dx = (int)floorf(infDx * 127.5f + 127.5f); - int dy = (int)floorf(infDy * 127.5f + 127.5f); - - if (ax < 0) - { - ax = 0; - } - else if (ax > 255) - { - ax = 255; - } - if (dx < 0) - { - dx = 0; - } - else if (dx > 255) - { - dx = 255; - } - if (ay < 0) - { - ay = 0; - } - else if (ay > 255) - { - ay = 255; - } - if (dy < 0) - { - dy = 0; - } - else if (dy > 255) - { - dy = 255; - } - - unsigned long area = m_pData[dy * m_dwWidth + dx] - m_pData[dy * m_dwWidth + ax] - m_pData[ay * m_dwWidth + dx] + m_pData[ay * m_dwWidth + ax]; - - return(m_fCorrectionFactor * (float)area); -} - - - -// optimizable -float CSummedAreaFilterKernel::GetAreaAA(float infAx, float infAy, float infDx, float infDy) const -{ - assert(m_eFilterType != eEmpty); - - infAx = infAx * 127.5f + 127.5f; - infAy = infAy * 127.5f + 127.5f; - infDx = infDx * 127.5f + 127.5f; - infDy = infDy * 127.5f + 127.5f; - - float fSum = _GetBilinearFiltered(infDx, infDy) - - _GetBilinearFiltered(infAx, infDy) - - _GetBilinearFiltered(infDx, infAy) - + _GetBilinearFiltered(infAx, infAy); - - return(fSum * m_fCorrectionFactor); -} - - -float CSummedAreaFilterKernel::_GetBilinearFiltered(const float infX, const float infY) const -{ - float fIX = floorf(infX), fIY = floorf(infY); - float fFX = infX - fIX, fFY = infY - fIY; - int iX = (int)fIX, iY = (int)fIY; - - if (iX < 0) - { - iX = 0; - } - else if (iX > 254) - { - iX = 254; - } - if (iY < 0) - { - iY = 0; - } - else if (iY > 254) - { - iY = 254; - } - - float fArea = m_pData[ iY * m_dwWidth + iX ] * ((1.0f - fFX) * (1.0f - fFY)) // left top - + m_pData[ iY * m_dwWidth + iX + 1 ] * ((fFX) * (1.0f - fFY)) // right top - + m_pData[(iY + 1) * m_dwWidth + iX ] * ((1.0f - fFX) * (fFY)) // left bottom - + m_pData[ iY * m_dwWidth + iX + 257] * ((fFX) * (fFY)); // right bottom - - return(fArea); -} - - - -bool CSummedAreaFilterKernel::CreateWeightFilter(CSimpleBitmap& outFilter, const float infX, const float infY, - const float infWeight, const float infR) const -{ - assert(infX >= 0.0f); - assert(infX < 1.0f); - assert(infY >= 0.0f); - assert(infY < 1.0f); - assert(infWeight >= 0.0f); - assert(infR > 0.0f); - - float fLeftTop = ceilf(infR); - int iSide = 2 * (int)fLeftTop + 1; - - float fInit = 0.0f; - - if (!outFilter.Alloc(iSide, iSide, &fInit)) - { - return false; - } - - AddWeights(outFilter, infX + fLeftTop, infY + fLeftTop, infWeight, infR); - - return true; -} - - -bool CSummedAreaFilterKernel::CreateWeightFilterBlock(CSimpleBitmap& outFilter, const unsigned long indwSideLength, - const float infR) const -{ - assert(indwSideLength >= 0); - assert(infR > 0.0f); - - float fLeftTop = ceilf(infR); - int iSide = 2 * (int)fLeftTop + 1; - - float fInit = 0.0f; - - if (!outFilter.Alloc(iSide, iSide, &fInit)) - { - return false; - } - - float fStep = 1.0f / (float)indwSideLength; - float fHalf = fStep * 0.5f; - - float fWeight = fStep * fStep; - - for (float y = fHalf; y < 1.0f; y += fStep) - { - for (float x = fHalf; x < 1.0f; x += fStep) - { - AddWeights(outFilter, x + fLeftTop, y + fLeftTop, fWeight, infR); - } - } - - // check -#ifdef _DEBUG - float fSum = 0.0f; - for (int y = 0; y < iSide; y++) - { - for (int x = 0; x < iSide; x++) - { - float f; - - outFilter.Get(x, y, f); - fSum += f; - } - } - assert(fSum >= 0.98f); - assert(fSum <= 1.02f); -#endif - - return true; -} - - -void CSummedAreaFilterKernel::AddWeights(CSimpleBitmap& inoutFilter, const float infX, const float infY, - const float infWeight, const float infR) const -{ - assert(infWeight >= 0.0f); - assert(infR > 0.0f); - - if (infWeight <= 0.0f) - { - return; - } - - float fInvR = 1.0f / infR; - float sx = floorf(infX - infR); - float sy = floorf(infY - infR); - - int iax = (int)sx; - int iay = (int)sy; - int iex = (int)ceilf(infX + infR); - int iey = (int)ceilf(infY + infR); - - float x, y; - int ix, iy; - - for (iy = iay, y = (sy - infY) * fInvR; iy <= iey; iy++, y += fInvR) - { - for (ix = iax, x = (sx - infX) * fInvR; ix <= iex; ix++, x += fInvR) - { - float fArea = GetAreaAA(x, y, x + fInvR, y + fInvR); // better quality - // float fArea=m_Filter.GetAreaNonAA(x,y,x+fInvR,y+fInvR); // faster - - // assert(fArea<=1.0f); // may be wrong if we use sharpening filter - - float fOldVal; - - inoutFilter.Get(ix, iy, fOldVal); - inoutFilter.Set(ix, iy, fOldVal + fArea * infWeight); - } - } -} - - - diff --git a/Code/Tools/CryCommonTools/SummedAreaFilterKernel.h b/Code/Tools/CryCommonTools/SummedAreaFilterKernel.h deleted file mode 100644 index 55af94f12c..0000000000 --- a/Code/Tools/CryCommonTools/SummedAreaFilterKernel.h +++ /dev/null @@ -1,112 +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 -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_SUMMEDAREAFILTERKERNEL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_SUMMEDAREAFILTERKERNEL_H - -#include // STL string -#include "SimpleBitmap.h" // SimpleBitmap<> - -// squared of any size (summed area tables limit the size and/or values) -// normalized(sum=1) - -// optimized for high quality, not speed -// for faster filter kernels extract the neccessary size and use this 1:1 - -// based on summed area tables - -class CSummedAreaFilterKernel - : public CSimpleBitmap -{ -public: - - //! constructor init is eEmpty - CSummedAreaFilterKernel(); - - //! load 8 bit photoshop 256x256 raw image - slow - //! typical filtersize for a gaussian filter kernel is 1.44 - //! /param iniMidValue [0..255[ this enables sharpening - sharpening may expand the result range - bool CreateFromRAWFile(const char* filename, const unsigned long indwSize = 256, const int iniMidValue = 0); - - //! sharpest possible result - filter diameter size has to be 16*pixelsize (256 samples per pixel) - //! theory: http://home.no.net/dmaurer/~dersch/interpolator/interpolator.html - //! /param indwSize >2 - bool CreateFromSincCalc(const unsigned long indwSize = 256); - - //! shttp://www.sixsigma.de/english/sixsigma/6s_e_gauss.htm - //! /param indwSize >2 - bool CreateFromGauss(const unsigned long indwSize = 256); - - //! optimizable O(k*1) with high k - //! bokeh is in the range ([-1..1],[-1..1]) - //! return normalized result - float GetAreaAA(float infAx, float infAy, float infDx, float infDy) const; - - //! O(k*1) with low k - //! bokeh is in the range ([-1..1],[-1..1]) - //! return normalized result - float GetAreaNonAA(float infAx, float infAy, float infDx, float infDy) const; - - //! - //! /return e.g. "FilterKernel(Sinc16x16)" - std::string GetInfoString(void) const; - - //! /param infX [0..1[ - //! /param infY [0..1[ - //! /param infWeight [0..[ - //! /param infR >0, radius - bool CreateWeightFilter(CSimpleBitmap& outFilter, const float infX, const float infY, - const float infWeight, const float infR) const; - - //! weight for the whole block is 1.0 - //! /param indwSideLength [1,..[ e.g. 3 for 3x3 block - //! /param infR >0, radius - bool CreateWeightFilterBlock(CSimpleBitmap& outFilter, const unsigned long indwSideLength, const float infR) const; - - //! with user filter kernel - //! /param infX - //! /param infY - //! /param infWeight [0..[ - //! /param infR >0, radius - void AddWeights(CSimpleBitmap& inoutFilter, const float infX, const float infY, - const float infWeight, const float infR) const; - -private: // -------------------------------------------------------------------- - - enum EFilterState - { - eEmpty, //!< after calling constructor - eSinc, //!< from CreateFromSincCalc - eRAW, //!< from CreateFromRAWFile - eGaussBlur, //!< from CreateFromGauss - eDisc, //!< not implemented - eGaussSharp //!< not implemented - }; - - EFilterState m_eFilterType; //!< for error checks and GetInfoString() - float m_fCorrectionFactor; //!< to get the normalized (whole kernel has sum of 1) result - - //! optimizable - //! bokeh is in the range ([0..255],[0..255]) - //! /param infX - //! /param infY - //! /return not normalized result - float _GetBilinearFiltered(const float infX, const float infY) const; - - //! sum the stored values in the bitmap together - //! calculate m_fCorrectionFactor - void _SumUpTableAndNormalize(void); -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_SUMMEDAREAFILTERKERNEL_H diff --git a/Code/Tools/CryCommonTools/TempFilePakExtraction.cpp b/Code/Tools/CryCommonTools/TempFilePakExtraction.cpp deleted file mode 100644 index 52aa6896d6..0000000000 --- a/Code/Tools/CryCommonTools/TempFilePakExtraction.cpp +++ /dev/null @@ -1,129 +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 : Opens a temporary file for read only access, where the file could be -// located in a zip or pak file. Note that if the file specified -// already exists it does not delete it when finished. - - -#include "TempFilePakExtraction.h" -#include "FileUtil.h" -#include "PathHelpers.h" -#include "IPakSystem.h" - - -TempFilePakExtraction::TempFilePakExtraction(const char* filename, const char* tempPath, IPakSystem* pPakSystem) - : m_strOriginalFileName(filename) - , m_strTempFileName(filename) -{ - if (!pPakSystem || !tempPath) - { - return; - } - - { - FILE* fileOnDisk = nullptr; - azfopen(&fileOnDisk, m_strOriginalFileName.c_str(), "rb"); - if (fileOnDisk) - { - fclose(fileOnDisk); - return; - } - } - - // Choose the name for the temporary file. - string tempFullFileName; - { - uint32 tempNumber = 0; - { - LARGE_INTEGER performanceCount; - if (QueryPerformanceCounter(&performanceCount)) - { - tempNumber = performanceCount.u.LowPart; - } - } - - string tempName; - { - // CryEngine's pak system supports filenames in format "@pakFilename|fileInPak", - // so let's handle such cases by using fileInPak part of the filename. - const size_t pos = m_strOriginalFileName.find_last_of('|'); - if (pos != string::npos) - { - tempName = m_strOriginalFileName.substr(pos + 1, string::npos); - if (tempName.empty()) - { - tempName = "BadFilenameSyntax"; - } - } - else - { - tempName = m_strOriginalFileName; - } - tempName = PathHelpers::GetFilename(tempName); - } - - int tryCount = 2000; - while (--tryCount >= 0) - { - tempFullFileName.Format("%sRC%04x_%s", tempPath, (tempNumber & 0xFFFF), tempName.c_str()); - - if (!FileUtil::FileExists(tempFullFileName.c_str())) - { - FILE* f = nullptr; - azfopen(&f, tempFullFileName.c_str(), "wb"); - if (f) - { - fclose(f); - break; - } - } - - tempFullFileName.clear(); - ++tempNumber; - } - - if (tempFullFileName.empty()) - { - return; - } - } - - if (pPakSystem->ExtractNoOverwrite(m_strOriginalFileName.c_str(), tempFullFileName.c_str())) - { - m_strTempFileName = tempFullFileName; - AZ::IO::SystemFile::SetWritable(m_strTempFileName.c_str(), false); - } - else - { - AZ::IO::LocalFileIO().Remove(tempFullFileName.c_str()); - } -} - - -TempFilePakExtraction::~TempFilePakExtraction() -{ - if (HasTempFile()) - { -#if defined(AZ_PLATFORM_WINDOWS) - SetFileAttributesA(m_strTempFileName.c_str(), FILE_ATTRIBUTE_ARCHIVE); -#endif - AZ::IO::LocalFileIO().Remove(m_strTempFileName.c_str()); - } -} - - -bool TempFilePakExtraction::HasTempFile() const -{ - return (m_strOriginalFileName != m_strTempFileName); -} diff --git a/Code/Tools/CryCommonTools/TempFilePakExtraction.h b/Code/Tools/CryCommonTools/TempFilePakExtraction.h deleted file mode 100644 index c0fbb44b8a..0000000000 --- a/Code/Tools/CryCommonTools/TempFilePakExtraction.h +++ /dev/null @@ -1,50 +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 : Opens a temporary file for read only access, where the file could be -// located in a zip or pak file. Note that if the file specified -// already exists it does not delete it when finished. - - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_TEMPFILEPAKEXTRACTION_H -#define CRYINCLUDE_CRYCOMMONTOOLS_TEMPFILEPAKEXTRACTION_H -#pragma once - -#include - -struct IPakSystem; - -class TempFilePakExtraction -{ -public: - TempFilePakExtraction(const char* filename, const char* tempPath, IPakSystem* pPakSystem); - ~TempFilePakExtraction(); - - const string& GetTempName() const - { - return m_strTempFileName; - } - - const string& GetOriginalName() const - { - return m_strOriginalFileName; - } - - bool HasTempFile() const; - -private: - string m_strTempFileName; - string m_strOriginalFileName; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_TEMPFILEPAKEXTRACTION_H diff --git a/Code/Tools/CryCommonTools/ThreadUtils.cpp b/Code/Tools/CryCommonTools/ThreadUtils.cpp deleted file mode 100644 index b3dfcd6117..0000000000 --- a/Code/Tools/CryCommonTools/ThreadUtils.cpp +++ /dev/null @@ -1,171 +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 -#include "ThreadUtils.h" -#include -#include -#include -#include - -namespace ThreadUtils -{ - class SimpleWorker - { - public: - SimpleWorker(SimpleThreadPool* pool, int index, bool trace) - : m_pool(pool) - , m_index(index) - , m_trace(trace) - { - } - - void Start(int startTime) - { - m_lastStartTime = startTime; - m_handle = AZStd::thread(AZStd::bind(SimpleWorker::ThreadFunc, (void*)this)); - } - - static unsigned int __stdcall ThreadFunc(void* param) - { - SimpleWorker* self = (SimpleWorker*)(param); - self->Work(); - return 0; - } - - void ExecuteJob(Job& job) - { - job.Run(); - if (m_trace) - { - int time = (int)GetTickCount(); - - JobTrace trace; - trace.m_job = job; - trace.m_duration = time - m_lastStartTime; - m_traces.push_back(trace); - - m_lastStartTime = time; - } - } - - void Work() - { - Job job; - for (;; ) - { - if (m_pool->GetJob(job, m_index)) - { - ExecuteJob(job); - } - else - { - return; - } - } - } - - // Called from main thread - void Join(JobTraces& traces) - { - if(m_handle.joinable()) - { - m_handle.join(); - } - - if (m_trace) - { - m_traces.swap(traces); - } - } - - private: - SimpleThreadPool* m_pool; - AZStd::thread m_handle; - int m_index; - bool m_trace; - int m_lastStartTime; - JobTraces m_traces; - friend SimpleThreadPool; - }; - - // --------------------------------------------------------------------------- - - SimpleThreadPool::SimpleThreadPool(bool trace) - : m_trace(trace) - , m_started(false) - , m_numProcessedJobs(0) - { - } - - SimpleThreadPool::~SimpleThreadPool() - { - WaitAllJobs(); - } - - void SimpleThreadPool::Start(int numThreads) - { - m_workers.resize(numThreads); - for (int i = 0; i < numThreads; ++i) - { - m_workers[i] = new SimpleWorker(this, i, m_trace); - } - - m_started = true; - - int startTime = (int)GetTickCount(); - for (int i = 0; i < numThreads; ++i) - { - m_workers[i]->Start(startTime); - } - } - - - void SimpleThreadPool::WaitAllJobs() - { - size_t numThreads = m_workers.size(); - m_threadTraces.resize(numThreads); - for (size_t i = 0; i < numThreads; ++i) - { - m_workers[i]->Join(m_threadTraces[i]); - } - - for (size_t i = 0; i < numThreads; ++i) - { - delete m_workers[i]; - } - m_workers.clear(); - - m_started = false; - } - - void SimpleThreadPool::Submit(const Job& job) - { - assert(!m_started); - m_jobs.push_back(job); - } - - bool SimpleThreadPool::GetJob(Job& job, [[maybe_unused]] int threadIndex) - { - AZStd::lock_guard lock(m_lockJobs); - - if (m_numProcessedJobs >= m_jobs.size()) - { - return false; - } - - job = m_jobs[m_numProcessedJobs]; - ++m_numProcessedJobs; - return true; - } -} diff --git a/Code/Tools/CryCommonTools/ThreadUtils.h b/Code/Tools/CryCommonTools/ThreadUtils.h deleted file mode 100644 index ac60a8420e..0000000000 --- a/Code/Tools/CryCommonTools/ThreadUtils.h +++ /dev/null @@ -1,288 +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_CRYCOMMONTOOLS_THREADUTILS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_THREADUTILS_H -#pragma once - -#include - -#if defined(AZ_PLATFORM_WINDOWS) -#define WIN32_LEAN_AND_MEAN -#include // CRITICAL_SECTION -#endif - -#include -#include - -namespace ThreadUtils -{ -#if defined(AZ_PLATFORM_WINDOWS) - class CriticalSection - { - friend class ConditionVariable; - - public: - CriticalSection() - { - memset(&m_cs, 0, sizeof(m_cs)); - InitializeCriticalSection(&m_cs); - } - - ~CriticalSection() - { - DeleteCriticalSection(&m_cs); - } - - void Lock() - { - EnterCriticalSection(&m_cs); - } - void Unlock() - { - LeaveCriticalSection(&m_cs); - } - bool TryLock() - { - return TryEnterCriticalSection(&m_cs) != FALSE; - } - -#if defined(AZ_DEBUG_BUILD) - bool IsLocked() - { - return m_cs.RecursionCount > 0 && m_cs.OwningThread == GetCurrentThread(); - } -#endif - - private: - // You are not allowed to copy or move a CRITICAL_SECTION - // handle, so make this class non-copyable - CriticalSection(const CriticalSection& cs); - CriticalSection& operator=(const CriticalSection& cs); - - CRITICAL_SECTION m_cs; - }; - - class ConditionVariable - { - public: - ConditionVariable() - { - InitializeConditionVariable(&m_cv); - } - - void Wake() - { - WakeConditionVariable(&m_cv); - } - - void WakeAll() - { - WakeAllConditionVariable(&m_cv); - } - - void Sleep(CriticalSection& cs, DWORD milliseconds = INFINITE) - { - SleepConditionVariableCS(&m_cv, &cs.m_cs, milliseconds); - } - - private: - // You are not allowed to copy or move a CONDITION_VARIABLE - // handle, so make this class non-copyable - ConditionVariable(const ConditionVariable& cs); - ConditionVariable& operator=(const ConditionVariable& cs); - - CONDITION_VARIABLE m_cv; - }; -#elif AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX) - class CriticalSection - { - public: - CriticalSection() - : m_locked(false) - { - } - - ~CriticalSection() - { - } - - void Lock() - { - m_cs.lock(); - m_locked = true; - } - void Unlock() - { - m_cs.unlock(); - m_locked = false; - } - bool TryLock() - { - m_locked = m_cs.try_lock(); - return m_locked; - } - -#if defined (AZ_DEBUG_BUILD) - bool IsLocked() - { - return m_locked; - } -#endif - - private: - // You are not allowed to copy or move a CRITICAL_SECTION - // handle, so make this class non-copyable - CriticalSection(const CriticalSection& cs); - CriticalSection& operator=(const CriticalSection& cs); - - bool m_locked; - AZStd::recursive_mutex m_cs; - }; -#endif - - class AutoLock - { - private: - CriticalSection& m_lock; - - AutoLock(); - AutoLock(const AutoLock&); - AutoLock& operator = (const AutoLock&); - - public: - AutoLock(CriticalSection& lock) - : m_lock(lock) - { - m_lock.Lock(); - } - ~AutoLock() - { - m_lock.Unlock(); - } - }; - - typedef void(* JobFunc)(void*); - - struct Job - { - JobFunc m_func; - void* m_data; - int m_debugInitialThread; - - Job() - : m_func(0) - , m_data(0) - , m_debugInitialThread(0) - { - } - - Job(JobFunc func, void* data) - : m_func(func) - , m_data(data) - , m_debugInitialThread(0) - { - } - - void Run() - { - m_func(m_data); - } - }; - typedef std::deque Jobs; - - struct JobTrace - { - Job m_job; - bool m_stolen; - int m_duration; - - JobTrace() - : m_duration(0) - , m_stolen(false) - { - } - }; - typedef std::vector JobTraces; - - class SimpleWorker; - - class SimpleThreadPool - { - public: - SimpleThreadPool(bool trace); - ~SimpleThreadPool(); - - bool GetJob(Job& job, int threadIndex); - - // Submits single independent job - template - void Submit(void(* jobFunc)(T*), T* data) - { - Submit(Job((JobFunc)jobFunc, data)); - } - - void Start(int numThreads); - void WaitAllJobs(); - - private: - void Submit(const Job& job); - - bool m_started; - bool m_trace; - - std::vector m_workers; - - std::vector m_threadTraces; - - int m_numProcessedJobs; - AZStd::mutex m_lockJobs; - std::vector m_jobs; - }; - -#if defined(AZ_PLATFORM_WINDOWS) -#pragma pack(push, 8) - struct ThreadNameInfo - { - DWORD dwType; // Must be 0x1000. - LPCSTR szName; // Pointer to name (in user addr space). - DWORD dwThreadID; // Thread ID (-1=caller thread). - DWORD dwFlags; // Reserved for future use, must be zero. - }; -#pragma pack(pop) - - // Usage: SetThreadName (-1, "MainThread"); - // From http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx - inline void SetThreadName([[maybe_unused]] DWORD dwThreadID, [[maybe_unused]] const char* threadName) - { -#ifdef _DEBUG - ThreadNameInfo info; - info.dwType = 0x1000; - info.szName = threadName; - info.dwThreadID = dwThreadID; - info.dwFlags = 0; - - __try - { - const DWORD exceptionCode = 0x406D1388; - RaiseException(exceptionCode, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info); - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - } -#endif - } -#endif -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_THREADUTILS_H diff --git a/Code/Tools/CryCommonTools/UI/log_icons.bmp b/Code/Tools/CryCommonTools/UI/log_icons.bmp deleted file mode 100644 index 4080bb98ea..0000000000 --- a/Code/Tools/CryCommonTools/UI/log_icons.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1fb280a5c873225c5f2b0518964c9b7947e81c6fdb4ec19374e02043a12dd295 -size 2358 diff --git a/Code/Tools/CryCommonTools/UnitTests/PathHelpersUnitTests.cpp b/Code/Tools/CryCommonTools/UnitTests/PathHelpersUnitTests.cpp deleted file mode 100644 index 0c44aabb86..0000000000 --- a/Code/Tools/CryCommonTools/UnitTests/PathHelpersUnitTests.cpp +++ /dev/null @@ -1,807 +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 "PathHelpers.h" -#include -#include -#include - -namespace PathHelpersTest -{ - class CryCommonToolsPathHelpersTest - : public UnitTest::AllocatorsTestFixture - { - public: - void SetUp() override - { - UnitTest::AllocatorsTestFixture::SetUp(); - AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); - } - - void TearDown() - { - AZ::AllocatorInstance::Destroy(); - AZ::AllocatorInstance::Destroy(); - UnitTest::AllocatorsTestFixture::TearDown(); - } - }; - - TEST_F(CryCommonToolsPathHelpersTest, FindExtension_StringPathNoExtension_ReturnsEmptyString) - { - const char* filePath = "ext"; - string result = PathHelpers::FindExtension(filePath); - EXPECT_STREQ("", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, FindExtension_StringPath_ReturnsStringExtension) - { - const char* extension = "ext"; - const char* filePath = "foo.ext"; - string result = PathHelpers::FindExtension(filePath); - EXPECT_STREQ(extension, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, FindExtension_WStringPathNoExtension_ReturnsEmptyString) - { - const wchar_t filePath[] = L"ext"; - const wchar_t expectedResult[] = L""; - const wstring result = PathHelpers::FindExtension(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, FindExtension_WStringPath_ReturnsStringExtension) - { - const wchar_t extension[] = L"ext"; - const wchar_t filePath[] = L"foo.ext"; - const wstring result = PathHelpers::FindExtension(filePath); - EXPECT_TRUE(result == extension); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_EmptyStringPath_ReturnsEmptyString) - { - const char* filePath = ""; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringNoExtension_ReturnsStringNoExtension) - { - const char* filePath = "foo.ext"; - const char* newExtension = ""; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ("foo", result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringPathWithDoubleBackSlash_ReturnsUnalteredString) - { - const char* filePath = "foo.ext\\"; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ(filePath, result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringPathWithForwardSlash_ReturnsUnalteredString) - { - const char* filePath = "foo.ext/"; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringPathWithColon_ReturnsUnalteredString) - { - const char* filePath = "foo.ext:"; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringPathEndsWithPeriod_ReturnsUnalteredString) - { - const char* filePath = "foo.ext."; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringNewExtension_ReturnsStringWithNewExtension) - { - const char* filePath = "foo.ext"; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ("foo.new", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_EmptyWStringPath_ReturnsEmptyWString) - { - const wchar_t filePath[] = L""; - const wchar_t newExtension[] = L"new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringNoExtension_ReturnsWStringNoExtension) - { - const wchar_t filePath[] = L"foo.ext"; - const wchar_t newExtension[] = L""; - const wchar_t expectedResult[] = L"foo"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == expectedResult); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringPathWithDoubleBackSlash_ReturnsUnalteredWString) - { - const wchar_t filePath[] = L"foo.ext\\"; - const wchar_t newExtension[] = L"new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == filePath); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringPathWithForwardSlash_ReturnsUnalteredWString) - { - const wchar_t filePath[] = L"foo.ext/"; - const wchar_t newExtension[] = L"new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringPathWithColon_ReturnsUnalteredWString) - { - const wchar_t filePath[] = L"foo.ext:"; - const wchar_t newExtension[] = L"new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringPathEndsWithPeriod_ReturnsUnalteredWString) - { - const wchar_t filePath[] = L"foo.ext."; - const wchar_t newExtension[] = L"new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringNewExtension_ReturnsWStringWithNewExtension) - { - const wchar_t filePath[] = L"foo.ext"; - const wchar_t newExtension[] = L"new"; - const wchar_t expectedResult[] = L"foo.new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveExtension_StringPathNoExtension_ReturnsUnalteredString) - { - const char* filePath = "foo"; - string result = PathHelpers::RemoveExtension(filePath); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveExtension_StringPath_ReturnsStringWithoutExtension) - { - const char* filePath = "foo.bar"; - string result = PathHelpers::RemoveExtension(filePath); - EXPECT_STREQ("foo", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveExtension_WStringPathNoExtension_ReturnsUnalteredWString) - { - const wchar_t filePath[] = L"foo"; - wstring result = PathHelpers::RemoveExtension(filePath); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveExtension_WStringPath_ReturnsWStringWithoutExtension) - { - const wchar_t filePath[] = L"foo.bar"; - const wchar_t expectedResult[] = L"foo"; - wstring result = PathHelpers::RemoveExtension(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPathWithColon_RemovesCharactersAfterColon) - { - const char* filePath = "foo:bar"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ("foo:", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPathWithColonAsCharacterBeforeLastSeparator_RemovesCharactersAfterLastSeparator) - { - const char* filePath = "foo:/bar"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ("foo:/", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPathWithLastSeparatorAsFirstCharacter_ReturnsStringColon) - { - const char* filePath = ":foo"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ(":", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPathStartsWithForwardSlash_ReturnsFullString) - { - const char* filePath = "//foo"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ(filePath, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPathStartsWithDoubleBackSlash_ReturnsFullString) - { - const char* filePath = "\\\\foo"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ(filePath, result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPath_ReturnsOnlyStringPath) - { - const char* filePath = "foobar/"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ("foobar", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPathWithColon_RemovesCharactersAfterColon) - { - const wchar_t filePath[] = L"foo:bar"; - const wchar_t expectedResult[] = L"foo:"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPathWithColonAsCharacterBeforeLastSeparator_RemovesCharactersAfterLastSeparator) - { - const wchar_t filePath[] = L"foo:/bar"; - const wchar_t expectedResult[] = L"foo:/"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPathWithLastSeparatorAsFirstCharacter_ReturnsWStringColon) - { - const wchar_t filePath[] = L":foo"; - const wchar_t expectedResult[] = L":"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPathStartsWithForwardSlash_ReturnsFullWString) - { - const wchar_t filePath[] = L"//foo"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == filePath); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPathStartsWithDoubleBackSlash_ReturnsFullWString) - { - const wchar_t filePath[] = L"\\\\foo"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == filePath); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPath_ReturnsOnlyWStringPath) - { - const wchar_t filePath[] = L"foobar/"; - const wchar_t expectedResult[] = L"foobar"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_StringPathStartsWithForwardSlash_ReturnsEmptyString) - { - const char* filePath = "/:foobar"; - string result = PathHelpers::GetFilename(filePath); - EXPECT_STREQ("", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_StringPathStartsWithDoubleBackSlash_ReturnsEmptyString) - { - const char* filePath = "\\:foobar"; - string result = PathHelpers::GetFilename(filePath); - EXPECT_STREQ("", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_StringPath_ReturnsStringFilename) - { - const char* filePath = "/foo/foo/foobar"; - string result = PathHelpers::GetFilename(filePath); - EXPECT_STREQ("foobar", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_WStringPathStartsWithForwardSlash_ReturnsEmptyWString) - { - const wchar_t filePath[] = L"/:foobar"; - const wchar_t expectedResult[] = L""; - wstring result = PathHelpers::GetFilename(filePath); - EXPECT_TRUE(result == expectedResult); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_WStringPathStartsWithDoubleBackSlash_ReturnsEmptyWString) - { - const wchar_t filePath[] = L"\\:foobar"; - const wchar_t expectedResult[] = L""; - wstring result = PathHelpers::GetFilename(filePath); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_WStringPath_ReturnsWStringFilename) - { - const wchar_t filePath[] = L"/foo/foo/foobar"; - const wchar_t expectedResult[] = L"foobar"; - wstring result = PathHelpers::GetFilename(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_EmptyPath_ReturnsEmptyString) - { - const char* filePath = ""; - string result = PathHelpers::AddSeparator(filePath); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_StringPathEndsWithForwardSlash_ReturnsStringPath) - { - const char* filePath = "foo/"; - string result = PathHelpers::AddSeparator(filePath); - EXPECT_STREQ(filePath, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_StringPathEndsWithDoubleBackSlash_ReturnsStringPath) - { - const char* filePath = "foo\\"; - string result = PathHelpers::AddSeparator(filePath); - EXPECT_STREQ(filePath, result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_StringPathEndsWithColon_ReturnsStringPath) - { - const char* filePath = "foo:"; - string result = PathHelpers::AddSeparator(filePath); - EXPECT_STREQ(filePath, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_StringPath_ReturnsStringWithDoubleBackSlashAdded) - { - const char* filePath = "foo"; - string result = PathHelpers::AddSeparator(filePath); - EXPECT_STREQ("foo\\", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_EmptyPath_ReturnsEmptyWString) - { - const wchar_t filePath[] = L""; - wstring result = PathHelpers::AddSeparator(filePath); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_WStringPathEndsWithForwardSlash_ReturnsWStringPath) - { - const wchar_t filePath[] = L"foo/"; - wstring result = PathHelpers::AddSeparator(filePath); - EXPECT_TRUE(result == filePath); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_WStringPathEndsWithDoubleBackSlash_ReturnsWStringPath) - { - const wchar_t filePath[] = L"foo\\"; - wstring result = PathHelpers::AddSeparator(filePath); - EXPECT_TRUE(result == filePath); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_WStringPathEndsWithColon_ReturnsWStringPath) - { - const wchar_t filePath[] = L"foo:"; - wstring result = PathHelpers::AddSeparator(filePath); - EXPECT_TRUE(result == filePath); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_WStringPath_ReturnsWStringWithDoubleBackSlashAdded) - { - const wchar_t filePath[] = L"foo"; - const wchar_t expectedResult[] = L"foo\\"; - wstring result = PathHelpers::AddSeparator(filePath); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_EmptyStringPath_ReturnsEmptyString) - { - const char* filePath = ""; - string result = PathHelpers::RemoveSeparator(filePath); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_StringPathEndsWithForwardSlash_ReturnsStringWithoutForwardSlash) - { - const char* filePath = "foo/"; - string result = PathHelpers::RemoveSeparator(filePath); - EXPECT_STREQ("foo", result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_StringPathEndsWithDoubleBackSlash_ReturnsStringWithoutDoubleBackSlash) - { - const char* filePath = "foo\\"; - string result = PathHelpers::RemoveSeparator(filePath); - EXPECT_STREQ("foo", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_StringPath_ReturnsStringPath) - { - const char* filePath = "foo"; - string result = PathHelpers::RemoveSeparator(filePath); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_EmptyWStringPath_ReturnsEmptyWString) - { - const wchar_t filePath[] = L""; - wstring result = PathHelpers::RemoveSeparator(filePath); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_WStringPathEndsWithForwardSlash_ReturnsWStringWithoutForwardSlash) - { - const wchar_t filePath[] = L"foo/"; - const wchar_t expectedResult[] = L"foo"; - wstring result = PathHelpers::RemoveSeparator(filePath); - EXPECT_TRUE(result == expectedResult); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_WStringPathEndsWithDoubleBackSlash_ReturnsWStringWithoutDoubleBackSlash) - { - const wchar_t filePath[] = L"foo\\"; - const wchar_t expectedResult[] = L"foo"; - wstring result = PathHelpers::RemoveSeparator(filePath); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_WStringPath_ReturnsWStringPath) - { - const wchar_t filePath[] = L"foo"; - wstring result = PathHelpers::RemoveSeparator(filePath); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_StringPathLengthEqualOne_ReturnsStringPath) - { - const char* filePath = "f"; - string result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_STREQ(filePath, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_StringPathWithDuplicateBackSlashes_ReturnsStringWithoutDoubleBackSlashes) - { - const char* filePath = "foo\\\\bar"; - string result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_STREQ("foo\\bar", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_StringPathWithDuplicateForwardSlashes_ReturnsStringWithoutForwardSlashes) - { - const char* filePath = "foo//bar"; - string result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_STREQ("foo/bar", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_WStringPathLengthEqualOne_ReturnsWStringPath) - { - const wchar_t filePath[] = L"f"; - wstring result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_TRUE(result == filePath); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_WStringPathWithDuplicateBackSlashes_ReturnsWStringWithoutDoubleBackSlashes) - { - const wchar_t filePath[] = L"foo\\\\bar"; - const wchar_t expectedResult[] = L"foo\\bar"; - wstring result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_WStringPathWithDuplicateForwardSlashes_ReturnsWStringWithoutForwardSlashes) - { - const wchar_t filePath[] = L"foo//bar"; - const wchar_t expectedResult[] = L"foo/bar"; - wstring result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, Join_EmptySecondStringPath_ReturnsFirstString) - { - const char* filePath1 = "foo"; - const char* filePath2 = ""; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ(filePath1, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, Join_EmptyFirstStringPath_ReturnsSecondString) - { - const char* filePath1 = ""; - const char* filePath2 = "bar"; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ(filePath2, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, Join_StringPath_ReturnsStringAppendedWithDoubleBackSlashDivider) - { - const char* filePath1 = "foo"; - const char* filePath2 = "bar"; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ("foo\\bar", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstStringPathEndsWithForwardSlash_ReturnsAppendedString) - { - const char* filePath1 = "foo/"; - const char* filePath2 = "bar"; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ("foo/bar", result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstStringPathEndsWithDoubleBackSlash_ReturnsAppendedString) - { - const char* filePath1 = "foo\\"; - const char* filePath2 = "bar"; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ("foo\\bar", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstStringPathEndsWithColon_ReturnsAppendedString) - { - const char* filePath1 = "foo:"; - const char* filePath2 = "bar"; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ("foo:bar", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, Join_EmptySecondWStringPath_ReturnsFirstWString) - { - const wchar_t filePath1[] = L"foo"; - const wchar_t filePath2[] = L""; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == filePath1); - } - - TEST_F(CryCommonToolsPathHelpersTest, Join_EmptyFirstWStringPath_ReturnsSecondWString) - { - const wchar_t filePath1[] = L""; - const wchar_t filePath2[] = L"bar"; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == filePath2); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, Join_WStringPath_ReturnsWStringAppendedWithDoubleBackSlashDivider) - { - const wchar_t filePath1[] = L"foo"; - const wchar_t filePath2[] = L"bar"; - const wchar_t expectedResult[] = L"foo\\bar"; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstWStringPathEndsWithForwardSlash_ReturnsAppendedWString) - { - const wchar_t filePath1[] = L"foo/"; - const wchar_t filePath2[] = L"bar"; - const wchar_t expectedResult[] = L"foo/bar"; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == expectedResult); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstWStringPathEndsWithDoubleBackSlash_ReturnsAppendedWString) - { - const wchar_t filePath1[] = L"foo\\"; - const wchar_t filePath2[] = L"bar"; - const wchar_t expectedResult[] = L"foo\\bar"; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstWStringPathEndsWithColon_ReturnsAppendedWString) - { - const wchar_t filePath1[] = L"foo:"; - const wchar_t filePath2[] = L"bar"; - const wchar_t expectedResult[] = L"foo:bar"; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_EmptyStringPath_ReturnsTrue) - { - const char* filePath = ""; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_StringPath_ReturnsTrue) - { - const char* filePath = "foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_StringPathBeginsWithForwardSlash_ReturnsFalse) - { - const char* filePath = "/foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE(result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_StringPathBeginsWithDoubleBackSlash_ReturnsFalse) - { - const char* filePath = "\\foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE (result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_StringPathBeginsWithColon_ReturnsFalse) - { - const char* filePath = ":foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_EmptyWStringPath_ReturnsTrue) - { - const wchar_t filePath[] = L""; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_WStringPath_ReturnsTrue) - { - const wchar_t filePath[] = L"foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_WStringPathBeginsWithForwardSlash_ReturnsFalse) - { - const wchar_t filePath[] = L"/foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE(result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_WStringPathBeginsWithDoubleBackSlash_ReturnsFalse) - { - const wchar_t filePath[] = L"\\foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE(result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_WStringPathBeginsWithColon_ReturnsFalse) - { - const wchar_t filePath[] = L":foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ToUnixPath_StringPath_ReturnsStringWithForwardSlashes) - { - const char* filePath = "foo\\foo\\foo"; - string result = PathHelpers::ToUnixPath(filePath); - EXPECT_STREQ("foo/foo/foo", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ToUnixPath_WStringPath_ReturnsWStringWithForwardSlashes) - { - const wchar_t filePath[] = L"foo\\foo\\foo"; - const wchar_t expectedResult[] = L"foo/foo/foo"; - wstring result = PathHelpers::ToUnixPath(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, ToDosPath_StringPath_ReturnsStringWithDoubleBackSlashes) - { - const char* filePath = "foo/foo/foo"; - string result = PathHelpers::ToDosPath(filePath); - EXPECT_STREQ("foo\\foo\\foo", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ToDosPath_WStringPath_ReturnsStringWithDoubleBackSlashes) - { - const wchar_t filePath[] = L"foo/foo/foo"; - const wchar_t expectedResult[] = L"foo\\foo\\foo"; - wstring result = PathHelpers::ToDosPath(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetAsciiPath_EmptyStringPath_ReturnsEmpty) - { - const char* filePath = ""; - string result = PathHelpers::GetAsciiPath(filePath); - EXPECT_STREQ(filePath, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, GetAsciiPath_StringPath_ReturnsStringWithoutForwardSlash) - { - const char* filePath = "foo/bar/"; - string result = PathHelpers::GetAsciiPath(filePath); - EXPECT_STREQ("foo\\bar", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, GetAsciiPath_EmptyWStringPath_ReturnsEmpty) - { - const wchar_t filePath[] = L""; - string expectedResult = ""; - string result = PathHelpers::GetAsciiPath(filePath); - EXPECT_STREQ(expectedResult, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, CanonicalizePath_StringPathLengthLessThanThree_ReturnsStringWithoutForwardSlash) - { - const char* filePath = "./"; - string result = PathHelpers::CanonicalizePath(filePath); - EXPECT_STREQ(".", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, CanonicalizePath_StringPathStartsWithPeriodForwardSlash_ReturnsStringWithoutPeriodAndForwardSlash) - { - const char* filePath = "./foo"; - string result = PathHelpers::CanonicalizePath(filePath); - EXPECT_STREQ("foo", result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, CanonicalizePath_StringPathStartsWithPeriodDoubleBackSlash_ReturnsStringWithoutPeriodAndDoubleBackSlash) - { - const char* filePath = ".\\foo"; - string result = PathHelpers::CanonicalizePath(filePath); - EXPECT_STREQ("foo", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS -} - -AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); diff --git a/Code/Tools/CryCommonTools/UnitTests/StringHelpersUnitTests.cpp b/Code/Tools/CryCommonTools/UnitTests/StringHelpersUnitTests.cpp deleted file mode 100644 index 013f077528..0000000000 --- a/Code/Tools/CryCommonTools/UnitTests/StringHelpersUnitTests.cpp +++ /dev/null @@ -1,1056 +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 "StringHelpers.h" -#include -#include -#include - -namespace StringHelpersTest -{ - class CryCommonToolsStringHelpersTest - : public UnitTest::AllocatorsTestFixture - { - public: - void SetUp() override - { - UnitTest::AllocatorsTestFixture::SetUp(); - AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); - } - - void TearDown() - { - AZ::AllocatorInstance::Destroy(); - AZ::AllocatorInstance::Destroy(); - UnitTest::AllocatorsTestFixture::TearDown(); - } - }; - - TEST_F(CryCommonToolsStringHelpersTest, Compare_TwoMatchingStrings_ReturnsZero) - { - const char* string1 = "foo"; - const char* string2 = "foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_SecondStringLonger_ReturnsGreaterThanZero) - { - const char* string1 = "foo"; - const char* string2 = "foobar"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_FirstStringLonger_ReturnsLessThanZero) - { - const char* string1 = "foobar"; - const char* string2 = "foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_FirstStringCapitalized_ReturnsGreaterThanZero) - { - const char* string1 = "FOO"; - const char* string2 = "foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_SecondStringCapitalized_ReturnsLessThanZero) - { - const char* string1 = "foo"; - const char* string2 = "FOO"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_TwoMatchingWStrings_ReturnsZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_SecondWStringLonger_ReturnsGreaterThanZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foobar"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_FirstWStringLonger_ReturnsLessThanZero) - { - const wchar_t string1[] = L"foobar"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_FirstWStringCapitalized_ReturnsGreaterThanZero) - { - const wchar_t string1[] = L"FOO"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_SecondWStringCapitalized_ReturnsLessThanZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"FOO"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_TwoMatchingStrings_ReturnsZero) - { - const char* string1 = "foo"; - const char* string2 = "foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_FirstStringCapitalized_ReturnsZero) - { - const char* string1 = "FOO"; - const char* string2 = "foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_SecondStringCapitalized_ReturnsZero) - { - const char* string1 = "foo"; - const char* string2 = "FOO"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_SecondStringLonger_ReturnsGreaterThanZero) - { - const char* string1 = "foo"; - const char* string2 = "foobar"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_FirstStringLonger_ReturnsLessThanZero) - { - const char* string1 = "foobar"; - const char* string2 = "foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_TwoMatchingWStrings_ReturnsZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_FirstWStringCapitalized_ReturnsZero) - { - const wchar_t string1[] = L"FOO"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_SecondWStringCapitalized_ReturnsZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"FOO"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_SecondWStringLonger_ReturnsGreaterThanZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foobar"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_FirstWStringLonger_ReturnsLessThanZero) - { - const wchar_t string1[] = L"foobar"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_SameTwoStrings_ReturnsTrue) - { - const char* string1 = "foo"; - const char* string2 = "foo"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_SecondStringUpperCase_ReturnsFalse) - { - const char* string1 = "foo"; - const char* string2 = "FOO"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_FirstStringUpperCase_ReturnsFalse) - { - const char* string1 = "FOO"; - const char* string2 = "foo"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_DifferentStrings_ReturnsFalse) - { - const char* string1 = "foo"; - const char* string2 = "foobar"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_SameTwoWStrings_ReturnsTrue) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foo"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_SecondWStringUpperCase_ReturnsFalse) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"FOO"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_FirstWStringUpperCase_ReturnsFalse) - { - const wchar_t string1[] = L"FOO"; - const wchar_t string2[] = L"foo"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_DifferentWStrings_ReturnsFalse) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foobar"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_SameTwoStrings_ReturnsTrue) - { - const char* string1 = "foo"; - const char* string2 = "foo"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_SecondStringUpperCase_ReturnsFalse) - { - const char* string1 = "foo"; - const char* string2 = "FOO"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_FirstStringUpperCase_ReturnsFalse) - { - const char* string1 = "FOO"; - const char* string2 = "foo"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_DifferentStrings_ReturnsFalse) - { - const char* string1 = "foo"; - const char* string2 = "foobar"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_SameTwoWStrings_ReturnsTrue) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foo"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_SecondWStringUpperCase_ReturnsFalse) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"FOO"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_FirstWStringUpperCase_ReturnsFalse) - { - const wchar_t string1[] = L"FOO"; - const wchar_t string2[] = L"foo"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_DifferentWStrings_ReturnsFalse) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foobar"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_StringPathsWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "foobar"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobar"; - const char* pattern = "foo"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_StringPathCapitalized_ReturnsFalse) - { - const char* string = "FOOBAR"; - const char* pattern = "foo"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_PatternStringCapitalized_ReturnsFalse) - { - const char* string = "foobar"; - const char* pattern = "FOO"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_StringPathAndNoMatchingPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "bar"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_WStringPathsWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"foobar"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"foo"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_WStringPathCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"FOOBAR"; - const wchar_t pattern[] = L"foo"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_PatternWstringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"FOO"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_WStringPathAndNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_StringPathsWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "foobar"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobar"; - const char* pattern = "foo"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_StringPathCapitalized_ReturnsFalse) - { - const char* string = "FOOBAR"; - const char* pattern = "foo"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_PatternStringCapitalized_ReturnsFalse) - { - const char* string = "foobar"; - const char* pattern = "FOO"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_StringPathAndNoMatchingPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "bar"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_WStringPathsWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"foobar"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"foo"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_WStringPathCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"FOOBAR"; - const wchar_t pattern[] = L"foo"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_PatternWStringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"FOO"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_WStringPathAndNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_StringPathWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "foobar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobar"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_StringPathCapitalized_ReturnsFalse) - { - const char* string = "FOOBAR"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_PatternStringCapitalized_ReturnsFalse) - { - const char* string = "foobar"; - const char* pattern = "BAR"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_StringPathAndNoMatchingPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_WStringPathWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"foobar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_WStringPathCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"FOOBAR"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_PatternWStringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"BAR"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_WStringPathAndNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_StringPathWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "foobar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobar"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_StringPathCapitalized_ReturnsTrue) - { - const char* string = "FOOBAR"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_PatternStringCapitalized_ReturnsTrue) - { - const char* string = "foobar"; - const char* pattern = "BAR"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_StringPathAndNoMatchingPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_WStringPathWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"foobar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_WStringPathCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"FOOBAR"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_PatternWStringCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"BAR"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_WStringPathAndNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_StringPathWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "barbar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobarfoo"; - const char* pattern = "bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_PatternStringCapitalized_ReturnsFalse) - { - const char* string = "foobarfoo"; - const char* pattern = "BAR"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_StringPathCapitalized_ReturnsFalse) - { - const char* string = "FOOBARFOO"; - const char* pattern = "bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_StringPathNoMatchingPattern_ReturnsFalse) - { - const char* string = "foofoofoo"; - const char* pattern = "bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_WStringPathWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"barbar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobarfoo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_PatternWStringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"foobarfoo"; - const wchar_t pattern[] = L"BAR"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_WStringPathCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"FOOBARFOO"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_WStringPathNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foofoofoo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_StringPathWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "barbar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobarfoo"; - const char* pattern = "bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_PatternStringCapitalized_ReturnsTrue) - { - const char* string = "foobarfoo"; - const char* pattern = "BAR"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_StringPathCapitalized_ReturnsTrue) - { - const char* string = "FOOBARFOO"; - const char* pattern = "bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_StringPathNoMatchingPattern_ReturnsFalse) - { - const char* string = "foofoofoo"; - const char* pattern = "bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_WStringPathWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"barbar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobarfoo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_WStringPathAndPattern2_ReturnsTrue) - { - const wchar_t string[] = L"foobfobaro"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_PatternWStringCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"foobarfoo"; - const wchar_t pattern[] = L"BAR"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_WStringPathCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"FOOBARFOO"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_WStringPathNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foofoofoo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_StringMatchingPattern_ReturnsTrue) - { - const char* string = "foo"; - const char* wildcard = "f*o"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_PatternStringCapitalized_ReturnsFalse) - { - const char* string = "foo"; - const char* wildcard = "F*O"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_StringCapitalized_ReturnsFalse) - { - const char* string = "FOO"; - const char* wildcard = "f*o"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_StringNoMatchingPatternWithAsterisk_ReturnsFalse) - { - const char* string = "foo"; - const char* wildcard = "f*r"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_StringNoMatchingPattern_ReturnsFalse) - { - const char* string = "foobar"; - const char* wildcard = "foo"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_WStringMatchingPattern_ReturnsTrue) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"f*o"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_WPatternStringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"F*O"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_WStringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"FOO"; - const wchar_t wildcard[] = L"f*o"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_WStringNoMatchingPatternWithAsterisk_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"f*r"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_WStringNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foobar"; - const wchar_t wildcard[] = L"foo"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_StringMatchingPattern_ReturnsTrue) - { - const char* string = "foo"; - const char* wildcard = "f*o"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_PatternStringCapitalized_ReturnsTrue) - { - const char* string = "foo"; - const char* wildcard = "F*O"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_StringCapitalized_ReturnsTrue) - { - const char* string = "FOO"; - const char* wildcard = "f*o"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_StringNoMatchingPatternWithAsterisk_ReturnsFalse) - { - const char* string = "foo"; - const char* wildcard = "f*r"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_StringNoMatchingPattern_ReturnsFalse) - { - const char* string = "foobar"; - const char* wildcard = "foo"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_WStringMatchingPattern_ReturnsTrue) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"f*o"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_PatternWStringCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"F*O"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_WStringCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"FOO"; - const wchar_t wildcard[] = L"f*o"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_WStringNoMatchingPatternWithAsterisk_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"f*r"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_WStringNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foobar"; - const wchar_t wildcard[] = L"foo"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, TrimLeft_StringWithoutReturnOrTab_ReturnsString) - { - const char* stringInput = "foo"; - string result = StringHelpers::TrimLeft(stringInput); - EXPECT_STREQ(stringInput, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, TrimRight_StringWithoutReturnOrTab_ReturnsString) - { - const char* stringInput = "foo"; - string result = StringHelpers::TrimRight(stringInput); - EXPECT_STREQ(stringInput, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MakeLowerCase_UpperCaseString_ReturnsLowerCaseString) - { - const char* stringInput = "FOO"; - string result = StringHelpers::MakeLowerCase(stringInput); - EXPECT_STREQ("foo", result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MakeLowerCase_UpperCaseWString_ReturnsLowerCaseString) - { - const wchar_t stringInput[] = L"FOO"; - const wchar_t expectedString[] = L"foo"; - wstring result = StringHelpers::MakeLowerCase(stringInput); - EXPECT_TRUE(result == expectedString); - } - - TEST_F(CryCommonToolsStringHelpersTest, MakeUpperCase_LowerCaseString_ReturnsUpperCaseString) - { - const char* stringInput = "foo"; - string result = StringHelpers::MakeUpperCase(stringInput); - EXPECT_STREQ("FOO", result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MakeUpperCase_LowerCaseWString_ReturnsUpperCaseString) - { - const wchar_t stringInput[] = L"foo"; - const wchar_t expectedString[] = L"FOO"; - wstring result = StringHelpers::MakeUpperCase(stringInput); - EXPECT_TRUE(result == expectedString); - } - - TEST_F(CryCommonToolsStringHelpersTest, Replace_CharacterToReplace_ReturnsStringWithReplacedCharacters) - { - const char* stringInput = "foo"; - char oldChar = 'o'; - char newChar = 'i'; - string result = StringHelpers::Replace(stringInput, oldChar, newChar); - EXPECT_STREQ("fii", result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Replace_CharacterToReplace_ReturnsWStringWithReplacedCharacters) - { - const wchar_t stringInput[] = L"foo"; - wchar_t oldChar = 'o'; - wchar_t newChar = 'i'; - const wchar_t expectedString[] = L"fii"; - wstring result = StringHelpers::Replace(stringInput, oldChar, newChar); - EXPECT_TRUE(result == expectedString); - } - - TEST_F(CryCommonToolsStringHelpersTest, Replace_CharacterToReplaceNotInString_ReturnsOriginalString) - { - const char* stringInput = "foo"; - char oldChar = 'a'; - char newChar = 'i'; - string result = StringHelpers::Replace(stringInput, oldChar, newChar); - EXPECT_STREQ(stringInput, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Replace_CharacterToReplaceNotInWString_ReturnsOriginalWString) - { - const wchar_t stringInput[] = L"foo"; - wchar_t oldChar = 'a'; - wchar_t newChar = 'i'; - wstring result = StringHelpers::Replace(stringInput, oldChar, newChar); - EXPECT_TRUE(result == stringInput); - } -} diff --git a/Code/Tools/CryCommonTools/WeightFilterSet.cpp b/Code/Tools/CryCommonTools/WeightFilterSet.cpp deleted file mode 100644 index dfc5ff24d0..0000000000 --- a/Code/Tools/CryCommonTools/WeightFilterSet.cpp +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include // assert() -#include "WeightFilterSet.h" // CWeightFilterSet - - - -void CWeightFilterSet::FreeData() -{ - m_FilterKernelBlock.FreeData(); -} - - -bool CWeightFilterSet::Create(const unsigned long indwSideLength, const CSummedAreaFilterKernel& inFilter, const float infR) -{ - assert(indwSideLength >= 1); - - FreeData(); - - // 32 Baustelle - inFilter.CreateWeightFilterBlock(m_FilterKernelBlock, 1, infR * indwSideLength); - return(true); -} - diff --git a/Code/Tools/CryCommonTools/WeightFilterSet.h b/Code/Tools/CryCommonTools/WeightFilterSet.h deleted file mode 100644 index 16c8c79acd..0000000000 --- a/Code/Tools/CryCommonTools/WeightFilterSet.h +++ /dev/null @@ -1,96 +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 -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_WEIGHTFILTERSET_H -#define CRYINCLUDE_CRYCOMMONTOOLS_WEIGHTFILTERSET_H - - -#include "SimpleBitmap.h" // SimpleBitmap<> -#include // STL vector<> -#include "SummedAreaFilterKernel.h" // CSummedAreaFilterKernel - -class CWeightFilterSet -{ -public: - - //! /param indwSideLength [1,..[ e.g. 3 for 3x3 block - bool Create(const unsigned long indwSideLength, const CSummedAreaFilterKernel& inFilter, const float infR); - - //! - void FreeData(); - - //! optimizable - //! weight is 1.0 - //! /param iniX x position in inoutDest - //! /param iniY y position in inoutDest - //! /param TInputImage typically CSimpleBitmap - //! /return weight - template - float GetBlockWithFilter(const TInputImage& inSrc, const int iniX, const int iniY, TElement& outResult) - { - float fWeightSum = 0.0f; - CSimpleBitmap& rBitmap = m_FilterKernelBlock; - - int W = (int)rBitmap.GetWidth(); - int H = (int)rBitmap.GetHeight(); - - int iSrcW = (int)inSrc.GetWidth(); - int iSrcH = (int)inSrc.GetHeight(); - - float* pfWeights = rBitmap.GetPointer(0, 0); - - for (int y = 0; y < H; y++) - { - int iDestY = y + iniY - H / 2; - - // optimizable (don't use the bottom border) - // if(iDestY==iSrcH){ pfWeights+=H;continue; } - - for (int x = 0; x < W; x++, pfWeights++) - { - int iDestX = x + iniX - W / 2; - - // optimizable (don't use the right border) - // if(iDestX==iSrcW) - // continue; - - TElement Value; - - // if(inSrc.Get(iDestX,iDestY,Value)) - if (inSrc.Get((iDestX + iSrcW * 2) % iSrcW, (iDestY + iSrcH * 2) % iSrcH, Value)) // tiled - { - float fWeight = *pfWeights; - - outResult += Value * fWeight; - fWeightSum += fWeight; - } - } - } - - return fWeightSum; - } - - int GetBorderSize() - { - int W = (int)m_FilterKernelBlock.GetWidth(); - - return (W - 1) / 2; - } - -private: // ------------------------------------------------------------- - - CSimpleBitmap m_FilterKernelBlock; //!< weight = 1 -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_WEIGHTFILTERSET_H diff --git a/Code/Tools/CryCommonTools/XMLPakFileSink.cpp b/Code/Tools/CryCommonTools/XMLPakFileSink.cpp deleted file mode 100644 index 9a9590687f..0000000000 --- a/Code/Tools/CryCommonTools/XMLPakFileSink.cpp +++ /dev/null @@ -1,55 +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 -#include "XMLPakFileSink.h" -#include "StringHelpers.h" - -XMLPakFileSink::XMLPakFileSink(IPakSystem* pakSystem, const string& archivePath, const string& filePath) - : pakSystem(pakSystem) - , filePath(filePath) -{ - archive = pakSystem->OpenArchive(archivePath.c_str()); -} - -XMLPakFileSink::~XMLPakFileSink() -{ - if (archive && pakSystem) - { - SYSTEMTIME st; - GetSystemTime(&st); - - FILETIME ft; - ZeroStruct(ft); - const BOOL ok = SystemTimeToFileTime(&st, &ft); - - LARGE_INTEGER lt; - lt.HighPart = ft.dwHighDateTime; - lt.LowPart = ft.dwLowDateTime; - - const __int64 modTime = lt.QuadPart; - ; - - pakSystem->AddToArchive(archive, filePath.c_str(), &data[0], int(data.size()), modTime); - pakSystem->CloseArchive(archive); - } -} - -void XMLPakFileSink::Write(const char* text) -{ - string asciiText = text; - int len = int(asciiText.size()); - int start = int(data.size()); - data.resize(data.size() + len); - memcpy(&data[start], asciiText.c_str(), len); -} diff --git a/Code/Tools/CryCommonTools/XMLPakFileSink.h b/Code/Tools/CryCommonTools/XMLPakFileSink.h deleted file mode 100644 index 973f9a05ca..0000000000 --- a/Code/Tools/CryCommonTools/XMLPakFileSink.h +++ /dev/null @@ -1,39 +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_CRYCOMMONTOOLS_XMLPAKFILESINK_H -#define CRYINCLUDE_CRYCOMMONTOOLS_XMLPAKFILESINK_H -#pragma once - - -#include "XMLWriter.h" -#include "IPakSystem.h" - -class XMLPakFileSink - : public IXMLSink -{ -public: - XMLPakFileSink(IPakSystem* pakSystem, const string& archivePath, const string& filePath); - ~XMLPakFileSink(); - - // IXMLSink - virtual void Write(const char* text); - -private: - IPakSystem* pakSystem; - PakSystemArchive* archive; - string filePath; - std::vector data; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_XMLPAKFILESINK_H diff --git a/Code/Tools/CryCommonTools/XMLWriter.cpp b/Code/Tools/CryCommonTools/XMLWriter.cpp deleted file mode 100644 index bfaf9df429..0000000000 --- a/Code/Tools/CryCommonTools/XMLWriter.cpp +++ /dev/null @@ -1,261 +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 -#include "XMLWriter.h" -#include "StringHelpers.h" -#include - -XMLWriter::XMLWriter(IXMLSink* sink) -{ - m_indentationSize = -1; - m_sink = sink; - - WriteText("\n"); -} - -void XMLWriter::BeginElement(const string& name) -{ - // Write the indentation. - if (m_newLine) - { - for (int i = 0; i < m_indentationSize; ++i) - { - WriteText(" "); - } - } - - WriteText("<%s", name.c_str()); - m_newLine = false; -} - -void XMLWriter::EndElement(const string& name) -{ - // Write the indentation. - if (m_newLine) - { - for (int i = 0; i < m_indentationSize; ++i) - { - WriteText(" "); - } - } - - WriteText("\n", name.c_str()); - m_newLine = true; -} - -void XMLWriter::CloseElement(const string& name, bool newLine) -{ - if (newLine) - { - WriteText(">\n"); - } - else - { - WriteText(">"); - } - m_newLine = newLine; -} - -void XMLWriter::CloseLeafElement(const string& name) -{ - WriteText(" />\n"); - m_newLine = true; -} - -void XMLWriter::IncreaseIndentation() -{ - ++m_indentationSize; -} - -void XMLWriter::DecreaseIndentation() -{ - --m_indentationSize; -} - -void XMLWriter::WriteAttribute(const string& name, const string& value) -{ - WriteText(" %s=\"%s\"", name.c_str(), value.c_str()); -} - -void XMLWriter::SerializeAttribute(char* buffer, size_t bufferSize, const string& value) -{ - // TODO: Escape string. - strcpy_s(buffer, bufferSize, value.c_str()); -} - -void XMLWriter::SerializeAttribute(char* buffer, size_t bufferSize, float value) -{ - sprintf_s(buffer, bufferSize, "%.10e", value); -} - -void XMLWriter::SerializeAttribute(char* buffer, size_t bufferSize, int value) -{ - sprintf_s(buffer, bufferSize, "%d", value); -} - -void XMLWriter::SerializeArrayElement(char* buffer, size_t bufferSize, float value) -{ - sprintf_s(buffer, bufferSize, "%.10e", value); -} - -void XMLWriter::SerializeArrayElement(char* buffer, size_t bufferSize, const string& value) -{ - strcpy(buffer, value.c_str()); -} - -void XMLWriter::SerializeArrayElement(char* buffer, size_t bufferSize, int value) -{ - sprintf_s(buffer, bufferSize, "%d", value); -} - -void XMLWriter::WriteContent(const string& text) -{ - WriteText("%s", text.c_str()); -} - -void XMLWriter::WriteContentLine(const string& text) -{ - // Write the indentation. - if (m_newLine) - { - for (int i = 0; i < m_indentationSize; ++i) - { - WriteText(" "); - } - } - - WriteText("%s\n", text.c_str()); - m_newLine = true; -} - -void XMLWriter::WriteText(const char* format, ...) -{ - va_list args; - va_start(args, format); - char buffer[40000]; - azvsnprintf(buffer, sizeof(buffer), format, args); - m_sink->Write(buffer); - va_end(args); -} - -XMLWriter::Element::Element(XMLWriter& writer, const string& name, bool output) - : m_writer(writer) - , m_name(name) - , m_output(output) - , isParent(false) -{ - if (!m_writer.m_elements.empty()) - { - Element* parent = m_writer.m_elements.back(); - if (!parent->isParent) - { - parent->isParent = true; - if (parent->m_output) - { - m_writer.CloseElement(m_name, true); - } - } - } - m_writer.m_elements.push_back(this); - if (m_output) - { - m_writer.IncreaseIndentation(); - } - if (m_output) - { - m_writer.BeginElement(m_name); - } -} - -XMLWriter::Element::~Element() -{ - if (m_output) - { - if (isParent) - { - m_writer.EndElement(m_name); - } - else - { - m_writer.CloseLeafElement(m_name); - } - } - m_writer.m_elements.pop_back(); - if (m_output) - { - m_writer.DecreaseIndentation(); - } -} - -void XMLWriter::Element::Child(const string& name, const string& value) -{ - Element child(m_writer, name); - child.Content(value); -} - -void XMLWriter::Element::Content(const string& text) -{ - if (m_output) - { - assert(!isParent); - if (!isParent) - { - isParent = true; - m_writer.CloseElement(m_name, false); - } - m_writer.WriteContent(text); - } -} - -void XMLWriter::Element::ContentLine(const string& text) -{ - if (!isParent) - { - isParent = true; - if (m_output) - { - m_writer.CloseElement(m_name, true); - } - } - if (m_output) - { - m_writer.WriteContentLine(text); - } -} - -XMLFileSink::XMLFileSink(const string& filename) -{ - m_file = std::fopen(filename.c_str(), "w"); - if (!m_file) - { - throw OpenFailedError("Unable to open file."); - } -} - -XMLFileSink::~XMLFileSink() -{ - if (m_file) - { - fclose(m_file); - } -} - -void XMLFileSink::Write(const char* text) -{ - if (m_file) - { - string asciiText = StringHelpers::ConvertString(text); - fwrite(asciiText.c_str(), 1, asciiText.size(), m_file); - } -} diff --git a/Code/Tools/CryCommonTools/XMLWriter.h b/Code/Tools/CryCommonTools/XMLWriter.h deleted file mode 100644 index d98b9f3d56..0000000000 --- a/Code/Tools/CryCommonTools/XMLWriter.h +++ /dev/null @@ -1,185 +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_CRYCOMMONTOOLS_XMLWRITER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_XMLWRITER_H -#pragma once - - -#include "Exceptions.h" - -#include -#include -#include - -class IXMLSink -{ -public: - // Define an exception type to throw when file opening fails. - struct OpenFailedErrorTag {}; - typedef Exception OpenFailedError; - - virtual void Write(const char* text) = 0; -}; - -class XMLFileSink - : public IXMLSink -{ -public: - XMLFileSink(const string& name); - ~XMLFileSink(); - - virtual void Write(const char* text); - -private: - FILE* m_file; -}; - -class XMLWriter -{ -public: - XMLWriter(IXMLSink* sink); - - class Element - { - public: - Element(XMLWriter& writer, const string& name, bool output = true); - ~Element(); - - template - void Attribute(const string& name, const T& value); - void Child(const string& name, const string& value); - void Content(const string& text); - void ContentLine(const string& text); - template - void ContentArrayElement(const T& value); - void ContentArrayFloat24(const float floatBuffer[24], const int entryCount); - - void WriteDirectText(const char* text) - { - if (!isParent) - { - isParent = true; - if (m_output) - { - m_writer.CloseElement(m_name, false); - } - } - m_writer.WriteDirectText(text); - } - - private: - XMLWriter& m_writer; - string m_name; - bool isParent; - bool m_output; - }; - - void WriteDirectText(const char* text) - { - m_sink->Write(text); - } - -private: - void IncreaseIndentation(); - void DecreaseIndentation(); - - void BeginElement(const string& name); - void EndElement(const string& name); - void CloseElement(const string& name, bool newLine); - void CloseLeafElement(const string& name); - - void WriteAttribute(const string& name, const string& value); - static void SerializeAttribute(char* buffer, size_t bufferSize, const string& value); - static void SerializeAttribute(char* buffer, size_t bufferSize, float value); - static void SerializeAttribute(char* buffer, size_t bufferSize, int value); - static void SerializeArrayElement(char* buffer, size_t bufferSize, float value); - static void SerializeArrayElement(char* buffer, size_t bufferSize, const string& value); - static void SerializeArrayElement(char* buffer, size_t bufferSize, int value); - void WriteContent(const string& text); - void WriteContentLine(const string& text); - - void WriteText(const char* format, ...); - - IXMLSink* m_sink; - int m_indentationSize; - - std::vector m_elements; - bool m_newLine; -}; - -template -void XMLWriter::Element::Attribute(const string& name, const T& value) -{ - assert(!isParent); - char buffer[1024]; - XMLWriter::SerializeAttribute(buffer, sizeof(buffer), value); - if (m_output) - { - m_writer.WriteAttribute(name, buffer); - } -} - -template -void XMLWriter::Element::ContentArrayElement(const T& value) -{ - if (!m_output) - { - return; - } - - if (!isParent) - { - isParent = true; - m_writer.CloseElement(m_name, false); - } - - char buffer[1024] = {' ', 0}; - XMLWriter::SerializeArrayElement(buffer + 1, sizeof(buffer) - 1, value); - - m_writer.WriteDirectText(buffer); -} - -inline void XMLWriter::Element::ContentArrayFloat24(const float floatBuffer[24], const int entryCount) -{ - if (!m_output) - { - return; - } - if (!isParent) - { - isParent = true; - m_writer.CloseElement(m_name, false); - } - - char buffer[2048]; - if (entryCount == 24) - { - sprintf_s(buffer, " %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e", - floatBuffer[0], floatBuffer[1], floatBuffer[2], floatBuffer[3], floatBuffer[4], floatBuffer[5], floatBuffer[6], floatBuffer[7], - floatBuffer[8], floatBuffer[9], floatBuffer[10], floatBuffer[11], floatBuffer[12], floatBuffer[13], floatBuffer[14], floatBuffer[15], - floatBuffer[16], floatBuffer[17], floatBuffer[18], floatBuffer[19], floatBuffer[20], floatBuffer[21], floatBuffer[22], floatBuffer[23]); - m_writer.WriteDirectText(buffer); - } - else - { - for (int i = 0; i < entryCount; i++) - { - char buffer[1024]; - sprintf_s(buffer, " %.10e", floatBuffer[i]); - m_writer.WriteDirectText(buffer); - } - } -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_XMLWRITER_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDir.h b/Code/Tools/CryCommonTools/ZipDir/ZipDir.h deleted file mode 100644 index c9954ce5dc..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDir.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_CRYCOMMONTOOLS_ZIPDIR_ZIPDIR_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIR_H -#pragma once - -#include "smartptr.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "smartptr.h" -#include "ZipDirTree.h" -#include "ZipDirList.h" -#include "ZipDirCache.h" -#include "ZipDirCacheRW.h" -#include "ZipDirCacheFactory.h" -#include "ZipDirFind.h" -#include "ZipDirFindRW.h" - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIR_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.cpp deleted file mode 100644 index 1f5d4a9286..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.cpp +++ /dev/null @@ -1,298 +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 -#include "FileUtil.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirTree.h" -#include "ZipDirCache.h" -#include "ZipDirFind.h" -#include "ZipDirCacheFactory.h" -#include -#include -#include "PathHelpers.h" -#include - -using namespace ZipFile; - -// initializes the instance structure -void ZipDir::Cache::Construct(FILE* fNew, size_t nDataSizeIn, const EncryptionKey& key) -{ - m_nRefCount = 0; - m_pFile = fNew; - m_nDataSize = nDataSizeIn; - m_nZipPathOffset = nDataSizeIn; - m_bEncryptHeaders = false; - m_encryptionKey = key; -} - -// self-destruct when ref count drops to 0 -void ZipDir::Cache::Delete() -{ - if (m_pFile) - { - fclose (m_pFile); - } - free(this); -} - -// looks for the given file record in the Central Directory. If there's none, returns NULL. -// if there is some, returns the pointer to it. -// the Path must be the relative path to the file inside the Zip -// if the file handle is passed, it will be used to find the file data offset, if one hasn't been initialized yet -ZipDir::FileEntry* ZipDir::Cache::FindFile (const char* szPath, [[maybe_unused]] bool bRefresh) -{ - ZipDir::FindFile fd (this); - if (!fd.FindExact(szPath)) - { - assert (!fd.GetFileEntry()); - return NULL; - } - assert (fd.GetFileEntry()); - return fd.GetFileEntry(); -} - -// loads the given file into the pCompressed buffer (the actual compressed data) -// if the pUncompressed buffer is supplied, uncompresses the data there -// buffers must have enough memory allocated, according to the info in the FileEntry -// NOTE: there's no need to decompress if the method is 0 (store) -// returns 0 if successful or error code if couldn't do something -ZipDir::ErrorEnum ZipDir::Cache::ReadFile (FileEntry* pFileEntry, void* pCompressed, void* pUncompressed) -{ - if (!pFileEntry) - { - return ZD_ERROR_INVALID_CALL; - } - - if (pFileEntry->desc.lSizeUncompressed == 0) - { - assert (pFileEntry->desc.lSizeCompressed == 0); - return ZD_ERROR_SUCCESS; - } - - assert (pFileEntry->desc.lSizeCompressed > 0); - - ErrorEnum nError = Refresh(pFileEntry); - if (nError != ZD_ERROR_SUCCESS) - { - return nError; - } - - if (AZ_TRAIT_CRYCOMMONTOOLS_FSEEK(m_pFile, pFileEntry->nFileDataOffset, SEEK_SET)) - { - return ZD_ERROR_IO_FAILED; - } - - SmartPtr pBufferDestroyer; - - void* pBuffer = pCompressed; // the buffer where the compressed data will go - - if (pFileEntry->nMethod == 0 && pUncompressed) - { - // we can directly read into the uncompress buffer - pBuffer = pUncompressed; - } - - if (!pBuffer) - { - if (!pUncompressed) - { - // what's the sense of it - no buffers at all? - return ZD_ERROR_INVALID_CALL; - } - - pBuffer = malloc(pFileEntry->desc.lSizeCompressed); - pBufferDestroyer.Attach(pBuffer); // we want it auto-freed once we return - } - - - if (fread (pBuffer, pFileEntry->desc.lSizeCompressed, 1, m_pFile) != 1) - { - return ZD_ERROR_IO_FAILED; - } - - if (pFileEntry->nMethod == METHOD_DEFLATE_AND_ENCRYPT) - { - ZipDir::Decrypt((char*)pBuffer, pFileEntry->desc.lSizeCompressed, m_encryptionKey); - } - - // if there's a buffer for uncompressed data, uncompress it to that buffer - if (pUncompressed) - { - if (pFileEntry->nMethod == 0) - { - assert (pBuffer == pUncompressed); - //assert (pFileEntry->desc.lSizeCompressed == pFileEntry->nSizeUncompressed); - //memcpy (pUncompressed, pBuffer, pFileEntry->desc.lSizeCompressed); - } - else - { - unsigned long nSizeUncompressed = pFileEntry->desc.lSizeUncompressed; - if (Z_OK != ZipRawUncompress(pUncompressed, &nSizeUncompressed, pBuffer, pFileEntry->desc.lSizeCompressed)) - { - return ZD_ERROR_CORRUPTED_DATA; - } - } - } - - return ZD_ERROR_SUCCESS; -} - -// loads and unpacks the file into a newly created buffer (that must be subsequently freed with -// Free()) Returns NULL if failed -void* ZipDir::Cache::AllocAndReadFile (FileEntry* pFileEntry) -{ - if (!pFileEntry) - { - return NULL; - } - - void* pData = malloc(pFileEntry->desc.lSizeUncompressed); - if (pData) - { - if (ZD_ERROR_SUCCESS != ReadFile (pFileEntry, NULL, pData)) - { - free(pData); - pData = NULL; - } - } - return pData; -} - -// frees the memory block that was previously allocated by AllocAndReadFile -void ZipDir::Cache::Free (void* pData) -{ - free(pData); -} - -// refreshes information about the given file entry into this file entry -ZipDir::ErrorEnum ZipDir::Cache::Refresh (FileEntry* pFileEntry) -{ - if (!pFileEntry) - { - return ZD_ERROR_INVALID_CALL; - } - - if (pFileEntry->nFileDataOffset != pFileEntry->INVALID_DATA_OFFSET) - { - return ZD_ERROR_SUCCESS; // the data offset has been successfully read.. - } - - return ZipDir::Refresh(m_pFile, pFileEntry, m_bEncryptHeaders); -} - -////////////////////////////////////////////////////////////////////////// -uint32 ZipDir::Cache::GetFileDataOffset(FileEntry* pFileEntry) -{ - if (pFileEntry->nFileDataOffset == pFileEntry->INVALID_DATA_OFFSET) - { - ZipDir::Refresh (m_pFile, pFileEntry, m_bEncryptHeaders); - } - return pFileEntry->nFileDataOffset; -} - -// returns the size of memory occupied by the instance referred to by this cache -// must be exact, because it's used by CacheRW to reallocate this cache -size_t ZipDir::Cache::GetSize() const -{ - return m_nDataSize + sizeof(Cache) + strlen(GetFilePath()); -} - - -// QUICK check to determine whether the file entry belongs to this object -bool ZipDir::Cache::IsOwnerOf (const FileEntry* pFileEntry) const -{ - // just check whether the pointer is within the memory block of this cache instance - return ((ULONG_PTR)pFileEntry >= (ULONG_PTR)(GetRoot() + 1) - && (ULONG_PTR)pFileEntry <= ((ULONG_PTR)GetRoot()) + m_nDataSize - sizeof(FileEntry)); -} - -bool ZipDir::Cache::UnpakToDisk(const string& destFolder) -{ - return UnpakToDiskInternal(GetRoot(), destFolder); -} - -bool ZipDir::Cache::UnpakToDiskInternal(ZipDir::DirHeader* folder, const string& destFolder) -{ - if (!folder) - { - return false; - } - - if (!FileUtil::EnsureDirectoryExists(destFolder.c_str())) - { - return false; - } - - bool result = true; - for (ZipFile::ushort fileNum = 0; fileNum < folder->numFiles; ++fileNum) - { - ZipDir::FileEntry* fileEntry = folder->GetFileEntry(fileNum); - if (!fileEntry) - { - result = false; - continue; - } - - string filePath = PathHelpers::Join(destFolder, fileEntry->GetName(folder->GetNamePool())); - AZ::IO::SystemFile file; - if (!file.Open(filePath.c_str(), AZ::IO::SystemFile::SF_OPEN_READ_WRITE | AZ::IO::SystemFile::SF_OPEN_CREATE)) - { - result = false; - continue; - } - - if (!fileEntry->desc.lSizeUncompressed) - { - // Nothing to write. Just close the file. - file.Close(); - continue; - } - - AZStd::vector buffer(fileEntry->desc.lSizeUncompressed); - if (ReadFile(fileEntry, nullptr, buffer.data()) == ZD_ERROR_SUCCESS) - { - file.Write(buffer.data(), buffer.size()); - file.Close(); - } - else - { - file.Close(); - AZ::IO::SystemFile::Delete(filePath.c_str()); - result = false; - continue; - } - } - - for (ZipFile::ushort dirNum = 0; dirNum < folder->numDirs; ++dirNum) - { - ZipDir::DirEntry* entry = folder->GetSubdirEntry(dirNum); - if (!entry) - { - result = false; - continue; - } - - string newPath = PathHelpers::Join(destFolder, entry->GetName(folder->GetNamePool())); - if (!UnpakToDiskInternal(entry->GetDirectory(), newPath)) - { - result = false; - continue; - } - } - - return result; -} - diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.h deleted file mode 100644 index 958c77efc3..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.h +++ /dev/null @@ -1,140 +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. - -// Declarations of the class used to parse and cache Zipped directory. -// This class is actually an auto-pointer to the instance of the cache, so it can -// be easily passed by value. -// The cache instance contains the optimized for memory usage and fast search tree -// of the files/directories inside the zip; each file has a descriptor with the -// info about where its compressed data lies within the file - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHE_H -#pragma once - - - -///////////////////////////////////////////////////////////// -// THe Zip Dir uses a special memory layout for keeping the structure of zip file. -// This layout is optimized for small memory footprint (for big zip files) -// and quick binary-search access to the individual files. -// -// The serialized layout consists of a number of directory records. -// Each directory record starts with the DirHeader structure, then -// it has an array of DirEntry structures (sorted by name), -// array of FileEntry structures (sorted by name) and then -// the pool of names, followed by pad bytes to align the whole directory -// record on 4-byte boundray. - -namespace ZipDir -{ - // this is the header of the instance data allocated dynamically - // it contains the FILE* : it owns it and closes upon destruction - struct Cache - { - void AddRef() { ++m_nRefCount; } - void Release() - { - if (--m_nRefCount <= 0) - { - Delete(); - } - } - int NumRefs() const { return m_nRefCount; } - - // looks for the given file record in the Central Directory. If there's none, returns NULL. - // if there is some, returns the pointer to it. - // the Path must be the relative path to the file inside the Zip - // if the file handle is passed, it will be used to find the file data offset, if one hasn't been initialized yet - // if bFull is true, then the full information about the file is returned (the offset to the data may be unknown at this point)- - // if needed, the file is accessed and the information is loaded - FileEntry* FindFile (const char* szPath, bool bFullInfo = false); - - // loads the given file into the pCompressed buffer (the actual compressed data) - // if the pUncompressed buffer is supplied, uncompresses the data there - // buffers must have enough memory allocated, according to the info in the FileEntry - // NOTE: there's no need to decompress if the method is 0 (store) - // returns 0 if successful or error code if couldn't do something - ErrorEnum ReadFile (FileEntry* pFileEntry, void* pCompressed, void* pUncompressed); - - // loads and unpacks the file into a newly created buffer (that must be subsequently freed with - // Free()) Returns NULL if failed - void* AllocAndReadFile (FileEntry* pFileEntry); - - // frees the memory block that was previously allocated by AllocAndReadFile - void Free (void*); - - // refreshes information about the given file entry into this file entry - ErrorEnum Refresh (FileEntry* pFileEntry); - - // Return FileEntity data offset inside zip file. - uint32 GetFileDataOffset(FileEntry* pFileEntry); - - - // returns the root directory record; - // through this directory record, user can traverse the whole tree - DirHeader* GetRoot() const - { - return (DirHeader*)(this + 1); - } - - // returns the size of memory occupied by the instance referred to by this cache - // must be exact, because it's used by CacheRW to reallocate this cache - size_t GetSize() const; - - // QUICK check to determine whether the file entry belongs to this object - bool IsOwnerOf (const FileEntry* pFileEntry) const; - - // returns the string - path to the zip file from which this object was constructed. - // this will be "" if the object was constructed with a factory that wasn't created with FLAGS_MEMORIZE_ZIP_PATH - const char* GetFilePath() const - { - return ((const char*)(this + 1)) + m_nZipPathOffset; - } - - // Unpak the file into a destination folder - bool UnpakToDisk(const string& destFolder); - - friend class CacheFactory; // the factory class creates instances of this class - friend class CacheRW; // the Read-Write 2-way cache can modify this cache directly during write operations - protected: - volatile signed int m_nRefCount; // the reference count - FILE* m_pFile; // the opened file - - // the size of the serialized data following this instance (not including the extra fields after the serialized tree data) - size_t m_nDataSize; - // the offset to the path/name of the zip file relative to (char*)(this+1) pointer in bytes - size_t m_nZipPathOffset; - - // tells if encryption used for zip-file - EncryptionKey m_encryptionKey; - bool m_bEncryptHeaders; - public: - // initializes the instance structure - void Construct(FILE* fNew, size_t nDataSize, const EncryptionKey& key); - void Delete(); - private: - bool ReadCompressedData(char* data, size_t size); - bool UnpakToDiskInternal(ZipDir::DirHeader* dirHeader, const string& destFolder); - - // the constructor/destructor cannot be called at all - everything will go through the factory class - Cache() { m_nRefCount = 0; } - ~Cache(){} - }; - - TYPEDEF_AUTOPTR(Cache); - - typedef Cache_AutoPtr CachePtr; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHE_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.cpp deleted file mode 100644 index 9d64f60b63..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.cpp +++ /dev/null @@ -1,804 +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 -#include "smartptr.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirTree.h" -#include "ZipDirCache.h" -#include "ZipDirCacheRW.h" -#include "ZipDirCacheFactory.h" -#include "ZipDirList.h" -#include - -static uint32 g_defaultEncryptionKey[4] = { 0xc968fb67, 0x8f9b4267, 0x85399e84, 0xf9b99dc4 }; - -ZipDir::CacheFactory::CacheFactory (InitMethodEnum nInitMethod, unsigned nFlags) -{ - m_nCDREndPos = 0; - m_f = NULL; - m_bBuildFileEntryMap = false; // we only need it for validation/debugging - m_bBuildFileEntryTree = true; // we need it to actually build the optimized structure of directories - m_bEncryptedHeaders = false; - - m_nInitMethod = nInitMethod; - m_nFlags = nFlags; -} - -ZipDir::CacheFactory::~CacheFactory() -{ - Clear(); -} - -ZipDir::CachePtr ZipDir::CacheFactory::New (const char* szFile, const uint32 key[4]) -{ - m_encryptionKey = EncryptionKey(g_defaultEncryptionKey); - if (key) - { - m_encryptionKey = EncryptionKey(key); - } - - Clear(); - m_f = nullptr; - azfopen(&m_f, szFile, "rb"); - if (m_f) - { - return MakeCache (szFile); - } - Clear(); - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Cannot open file in binary mode for reading, probably missing file"); - return 0; - /* - if (!m_f) - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED,"Cannot open file in binary mode for reading, probably missing file"); - try - { - return MakeCache (szFile); - } - catch(Error) - { - Clear(); - throw; - } - */ -} - - -ZipDir::CacheRWPtr ZipDir::CacheFactory::NewRW(const char* szFileName, size_t fileAlignment, bool encrypted, const uint32* key) -{ - m_encryptionKey = EncryptionKey(g_defaultEncryptionKey); - if (key) - { - m_encryptionKey = EncryptionKey(key); - } - - CacheRWPtr pCache = new CacheRW(encrypted, m_encryptionKey); - - // opens the given zip file and connects to it. Creates a new file if no such file exists - // if successful, returns true. - if (!(m_nFlags & FLAGS_DONT_MEMORIZE_ZIP_PATH)) - { - pCache->m_strFilePath = szFileName; - } - - if (m_nFlags & FLAGS_DONT_COMPACT) - { - pCache->m_nFlags |= CacheRW::FLAGS_DONT_COMPACT; - } - - // first, try to open the file for reading or reading/writing - if (m_nFlags & FLAGS_READ_ONLY) - { - m_f = nullptr; - azfopen(&m_f, szFileName, "rb"); - pCache->m_nFlags |= CacheRW::FLAGS_CDR_DIRTY | CacheRW::FLAGS_READ_ONLY; - - if (!m_f) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not open file in binary mode for reading"); - return 0; - } - } - else - { - m_f = NULL; - if (!(m_nFlags & FLAGS_CREATE_NEW)) - { - m_f = nullptr; - azfopen(&m_f, szFileName, "r+b"); - } - - bool bOpenForWriting = true; - - if (m_f) - { - // get file size - fseek(m_f, 0, SEEK_END); - size_t nFileSize = AZ_TRAIT_CRYCOMMONTOOLS_FTELL(m_f); - fseek(m_f, 0, SEEK_SET); - - if (nFileSize) - { - if (!ReadCacheRW(*pCache)) - { - fclose(m_f); - m_f = NULL; - - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not read archive"); - return 0; - } - bOpenForWriting = false; - } - else - { - // if file has 0 bytes (e.g. crash during saving) we don't want to open it - assert(0); // you can ignore, the system shold handle this gracefully - } - } - - if (bOpenForWriting) - { - m_f = nullptr; - azfopen(&m_f, szFileName, "w+b"); - if (m_f) - { - // there's no such file, but we'll create one. We'll need to write out the CDR here - pCache->m_lCDROffset = 0; - pCache->m_nFlags |= CacheRW::FLAGS_CDR_DIRTY; - } - pCache->m_fileAlignment = fileAlignment; - } - - if (!m_f) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not open file in binary mode for appending (read/write)"); - return 0; - } - } - - - // give the cache the file handle: - pCache->m_pFile = m_f; - // the factory doesn't own it after that - m_f = NULL; - - return pCache; -} - -bool ZipDir::CacheFactory::ReadCacheRW (CacheRW& rwCache) -{ - m_bBuildFileEntryTree = true; - if (!Prepare()) - { - return false; - } - - // since it's open for R/W, we need to know exactly how much space - // we have for each file to use the gaps efficiently - FileEntryList Adjuster (&m_treeFileEntries, m_CDREnd.lCDROffset); - Adjuster.RefreshEOFOffsets(); - - m_treeFileEntries.Swap(rwCache.m_treeDir); - m_CDR_buffer.swap(rwCache.m_CDR_buffer); // CDR Buffer contain actually the string pool for the tree directory. - m_unifiedNameBuffer.swap(rwCache.m_unifiedNameBuffer); // string pool for unified names - - // very important: we need this offset to be able to add to the zip file - rwCache.m_lCDROffset = m_CDREnd.lCDROffset; - - if (m_bEncryptedHeaders != rwCache.m_bEncryptedHeaders) - { - // force to relink and update all headers on close - rwCache.m_nFlags |= ZipDir::CacheRW::FLAGS_UNCOMPACTED; - rwCache.m_bHeadersEncryptedOnClose = rwCache.m_bEncryptedHeaders; - rwCache.m_bEncryptedHeaders = m_bEncryptedHeaders; - } - return true; -} - -// reads everything and prepares the maps -bool ZipDir::CacheFactory::Prepare () -{ - if (!FindCDREnd()) - { - return false; - } - - m_bEncryptedHeaders = (m_CDREnd.nDisk & (1 << 15)) != 0; - m_CDREnd.nDisk = m_CDREnd.nDisk & 0x7fff; - - // we don't support multivolume archives - if (m_CDREnd.nDisk != 0 - || m_CDREnd.nCDRStartDisk != 0 - || m_CDREnd.numEntriesOnDisk != m_CDREnd.numEntriesTotal) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_UNSUPPORTED, "Multivolume archive detected. Current version of ZipDir does not support multivolume archives"); - return false; - } - - // if the central directory offset or size are out of range, - // the CDREnd record is probably corrupt - if (m_CDREnd.lCDROffset > m_nCDREndPos - || m_CDREnd.lCDRSize > m_nCDREndPos - || m_CDREnd.lCDROffset + m_CDREnd.lCDRSize > m_nCDREndPos) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_DATA_IS_CORRUPT, "The central directory offset or size are out of range, the pak is probably corrupt, try to repair or delete the file"); - return false; - } - - if (!BuildFileEntryMap()) - { - return false; - } - - // the number of parsed files MUST be the declared number of entries - // in the central directory - if (m_bBuildFileEntryMap && m_CDREnd.numEntriesTotal != m_mapFileEntries.size()) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CDR_IS_CORRUPT, "The number of parsed files does not match the declared number of entries in the central directory, the pak is probably corrupt, try to repair or delete the file"); - } - - const size_t numFilesFound = m_treeFileEntries.NumFilesTotal(); - if (m_bBuildFileEntryTree && m_CDREnd.numEntriesTotal != numFilesFound) - { - const size_t numDirsFound = m_treeFileEntries.NumDirsTotal(); - - // Other zip tools create entries for directories. - // These entires don't have representation in our tree. - // FIXME: Proper calculation of entry count should be implemented. - if (m_CDREnd.numEntriesTotal != numFilesFound + numDirsFound) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CDR_IS_CORRUPT, "The number of parsed files does not match the declared number of entries in the central directory. The pak does not appear to be corrupt, but perhaps there are some duplicated or missing file entries, try to repair the file"); - } - } - - return true; -} - -ZipDir::CachePtr ZipDir::CacheFactory::MakeCache (const char* szFile) -{ - if (!Prepare()) - { - return CachePtr(); - } - - // initializes this object from the given tree, which is a convenient representation of the file tree - size_t nSizeRequired = m_treeFileEntries.GetSizeSerialized(); - size_t nSizeZipPath = 1; // we need to remember the terminating 0 - if (!(m_nFlags & FLAGS_DONT_MEMORIZE_ZIP_PATH)) - { - nSizeZipPath += strlen(szFile); - } - // allocate and initialize the memory that'll be the root now - size_t nCacheInstanceSize = sizeof(Cache) + nSizeRequired + nSizeZipPath; - - Cache* pCacheInstance = (Cache*)malloc(nCacheInstanceSize); // Do not use pools for this allocation - pCacheInstance->Construct(m_f, nSizeRequired, m_encryptionKey); - CachePtr cache = pCacheInstance; - m_f = NULL; // we don't own the file anymore - it's in possession of the cache instance - - // try to serialize into the memory -#if !defined(NDEBUG) - size_t nSizeSerialized = -#endif - m_treeFileEntries.Serialize (cache->GetRoot()); - - assert (nSizeSerialized == nSizeRequired); - - char* pZipPath = ((char*)(pCacheInstance + 1)) + nSizeRequired; - - if (!(m_nFlags & FLAGS_DONT_MEMORIZE_ZIP_PATH)) - { - memcpy (pZipPath, szFile, nSizeZipPath); - } - else - { - pZipPath[0] = '\0'; - } - - Clear(); - - return cache; -} - -void ZipDir::CacheFactory::Clear() -{ - if (m_f) - { - fclose (m_f); - } - m_nCDREndPos = 0; - memset (&m_CDREnd, 0, sizeof(m_CDREnd)); - m_mapFileEntries.clear(); - m_treeFileEntries.Clear(); - m_bEncryptedHeaders = false; -} - - -////////////////////////////////////////////////////////////////////////// -// searches for CDREnd record in the given file -bool ZipDir::CacheFactory::FindCDREnd() -{ - // this buffer will be used to find the CDR End record - // the additional bytes are required to store the potential tail of the CDREnd structure - // when moving the window to the next position in the file - char pReservedBuffer[g_nCDRSearchWindowSize + sizeof(ZipFile::CDREnd) - 1]; - - Seek (0, SEEK_END); - unsigned long nFileSize = Tell(); - - if (nFileSize < sizeof(ZipFile::CDREnd)) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_NO_CDR, "The file is too small, it doesn't even contain the CDREnd structure. Please check and delete the file. Truncated files are not deleted automatically"); - return false; - } - - // this will point to the place where the buffer was loaded - unsigned int nOldBufPos = nFileSize; - // start scanning well before the end of the file to avoid reading beyond the end - - unsigned int nScanPos = nFileSize - sizeof(ZipFile::CDREnd); - - m_CDREnd.lSignature = 0; // invalid signature as the flag of not-found CDR End structure - while (true) - { - unsigned int nNewBufPos; // the new buf pos - char* pWindow = pReservedBuffer; // the window pointer into which data will be read (takes into account the possible tail-of-CDREnd) - if (nOldBufPos <= g_nCDRSearchWindowSize) - { - // the old buffer position doesn't let us read the full search window size - // therefore the new buffer pos will be 0 (instead of negative beyond the start of the file) - // and the window pointer will be closer tot he end of the buffer because the end of the buffer - // contains the data from the previous iteration (possibly) - nNewBufPos = 0; - pWindow = pReservedBuffer + g_nCDRSearchWindowSize - (nOldBufPos - nNewBufPos); - } - else - { - nNewBufPos = nOldBufPos - g_nCDRSearchWindowSize; - assert (nNewBufPos > 0); - } - - // since dealing with 32bit unsigned, check that filesize is bigger than - // CDREnd plus comment before the following check occurs. - if (nFileSize > (sizeof(ZipFile::CDREnd) + 0xFFFF)) - { - // if the new buffer pos is beyond 64k limit for the comment size - if (nNewBufPos < (unsigned int)(nFileSize - sizeof(ZipFile::CDREnd) - 0xFFFF)) - { - nNewBufPos = nFileSize - sizeof(ZipFile::CDREnd) - 0xFFFF; - } - } - - // if there's nothing to search - if (nNewBufPos >= nOldBufPos) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_NO_CDR, "Cannot find Central Directory Record in pak. This is either not a pak file, or a pak file without Central Directory. It does not mean that the data is permanently lost, but it may be severely damaged. Please repair the file with external tools, there may be enough information left to recover the file completely"); // we didn't find anything - return false; - } - - // seek to the start of the new window and read it - Seek (nNewBufPos); - Read (pWindow, nOldBufPos - nNewBufPos); - - while (nScanPos >= nNewBufPos) - { - ZipFile::CDREnd* pEnd = (ZipFile::CDREnd*)(pWindow + nScanPos - nNewBufPos); - if (pEnd->lSignature == pEnd->SIGNATURE) - { - if (pEnd->nCommentLength == nFileSize - nScanPos - sizeof(ZipFile::CDREnd)) - { - // the comment length is exactly what we expected - m_CDREnd = *pEnd; - m_nCDREndPos = nScanPos; - break; - } - else - { - THROW_ZIPDIR_ERROR (ZD_ERROR_DATA_IS_CORRUPT, "Central Directory Record is followed by a comment of inconsistent length. This might be a minor misconsistency, please try to repair the file. However, it is dangerous to open the file because I will have to guess some structure offsets, which can lead to permanent unrecoverable damage of the archive content"); - return false; - } - } - if (nScanPos == 0) - { - break; - } - --nScanPos; - } - - if (m_CDREnd.lSignature == m_CDREnd.SIGNATURE) - { - return true; // we've found it - } - - nOldBufPos = nNewBufPos; - memmove (pReservedBuffer + g_nCDRSearchWindowSize, pWindow, sizeof(ZipFile::CDREnd) - 1); - } - THROW_ZIPDIR_ERROR (ZD_ERROR_UNEXPECTED, "The program flow may not have possibly lead here. This error is unexplainable"); // we shouldn't be here - return false; -} - - -////////////////////////////////////////////////////////////////////////// -// uses the found CDREnd to scan the CDR and probably the Zip file itself -// builds up the m_mapFileEntries -bool ZipDir::CacheFactory::BuildFileEntryMap() -{ - Seek (m_CDREnd.lCDROffset); - - if (m_CDREnd.lCDRSize == 0) - { - return true; - } - - DynArray& pBuffer = m_CDR_buffer; // Use persistent buffer. - - pBuffer.resize(m_CDREnd.lCDRSize + 1); // Allocate one more because we use this memory as a strings pool. - - if (pBuffer.empty()) // couldn't allocate enough memory for temporary copy of CDR - { - THROW_ZIPDIR_ERROR (ZD_ERROR_NO_MEMORY, "Not enough memory to cache Central Directory record for fast initialization. This error may not happen on non-console systems"); - return false; - } - - // Calculate buffer size for unified filenames - const size_t headersSize = sizeof(ZipFile::CDRFileHeader) * m_CDREnd.numEntriesTotal; - const size_t terminatingZeros = m_CDREnd.numEntriesTotal; - if (headersSize > m_CDREnd.lCDRSize + terminatingZeros) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CORRUPTED_DATA, "Number of entries in Central Directory seems to be wrong"); - return false; - } - const size_t nameBufferSize = m_CDREnd.lCDRSize + terminatingZeros - headersSize; // numEntriesTotal for terminating zeroes - - // Allocate buffer for unified filenames - m_unifiedNameBuffer.resize(nameBufferSize); - if (m_unifiedNameBuffer.empty() && nameBufferSize != 0) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_NO_MEMORY, "Not enough memory to allocate unified names buffer"); - return false; - } - char* pUnifiedName = m_unifiedNameBuffer.empty() ? 0 : &m_unifiedNameBuffer[0]; - const char* const pUnifiedNameEnd = pUnifiedName + m_unifiedNameBuffer.size(); - - ReadHeaderData(&pBuffer[0], m_CDREnd.lCDRSize); - - // now we've read the complete CDR - parse it. - ZipFile::CDRFileHeader* pFile = (ZipFile::CDRFileHeader*)(&pBuffer[0]); - const char* const pEndOfData = &pBuffer[0] + m_CDREnd.lCDRSize; - const char* const pEndOfBuffer = &pBuffer[0] + pBuffer.size(); - char* pFileName; - - // check signature of first entry - if ((const char*)(pFile + 1) <= pEndOfData) - { - if (pFile->lSignature != pFile->SIGNATURE) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CDR_IS_CORRUPT, m_bEncryptedHeaders - ? "Signature of CDR entry is corrupt. Wrong decryption key was used or archive is corrupt." - : "Signature of CDR entry is corrupt. Archive is corrupt."); - return false; - } - } - - while ((pFileName = (char*)(pFile + 1)) <= pEndOfData) - { - // Hacky way to use CDR memory block as a string pool. - pFile->lSignature = 0; // Force signature to always be 0 (First byte of signature maybe a zero termination of the previous file filename). - - if (pFile->nVersionNeeded > 20) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_UNSUPPORTED, "Reading file header with unsupported version (nVersionNeeded > 20)."); - return false; - } - //if (pFile->lSignature != pFile->SIGNATURE) // Timur, Dont compare signatures as signatue in memory can be overwritten by the code below - //break; - // the end of this file record - const char* pEndOfRecord = (pFileName + pFile->nFileNameLength + pFile->nExtraFieldLength + pFile->nFileCommentLength); - // if the record overlaps with the End Of CDR structure, something is wrong - if (pEndOfRecord > pEndOfData) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CDR_IS_CORRUPT, "Central Directory record is either corrupt, or truncated, or missing. Cannot read the archive directory"); - return false; - } - - ////////////////////////////////////////////////////////////////////////// - // Analyze advanced section. - ////////////////////////////////////////////////////////////////////////// - SExtraZipFileData extra; - const char* pExtraField = (pFileName + pFile->nFileNameLength); - const char* pExtraEnd = pExtraField + pFile->nExtraFieldLength; - while (pExtraField < pExtraEnd) - { - const char* pAttrData = pExtraField + sizeof(ZipFile::ExtraFieldHeader); - ZipFile::ExtraFieldHeader& hdr = *(ZipFile::ExtraFieldHeader*)pExtraField; - switch (hdr.headerID) - { - case ZipFile::EXTRA_NTFS: - { - extra.nLastModifyTime = *(uint64*)(pAttrData + sizeof(ZipFile::ExtraNTFSHeader)); - //uint64 accTime = *(uint64*)(pAttrData + sizeof(ZipFile::ExtraNTFSHeader) + 8); - //uint64 crtTime = *(uint64*)(pAttrData + sizeof(ZipFile::ExtraNTFSHeader) + 16); - } - break; - } - pExtraField += sizeof(ZipFile::ExtraFieldHeader) + hdr.dataSize; - } - - bool bDirectory = false; - if (pFile->nFileNameLength > 0 && (pFileName[pFile->nFileNameLength - 1] == '/' || pFileName[pFile->nFileNameLength - 1] == '\\')) - { - bDirectory = true; - } - - if (!bDirectory) - { - const size_t fileNameLen = pFile->nFileNameLength; - pFileName[fileNameLen] = 0; // Not standard!, may overwrite signature of the next memory record data in zip. - - // generate unified name - if (pFileName + fileNameLen + 1 > pEndOfBuffer || - pUnifiedName + fileNameLen + 1 > pUnifiedNameEnd) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CORRUPTED_DATA, "Filename length exceeds estimated size. Try to repair the archive."); - return false; - } - - for (int i = 0; i < fileNameLen + 1; i++) - { - pUnifiedName[i] = ::tolower(pFileName[i]); - } - - // put this entry into the map - AddFileEntry (pFileName, pUnifiedName, pFile, extra); - - pUnifiedName += fileNameLen + 1; - } - - // move to the next file - pFile = (ZipFile::CDRFileHeader*)pEndOfRecord; - } - - // finished reading CDR - return true; -} - - -////////////////////////////////////////////////////////////////////////// -// give the CDR File Header entry, reads the local file header to validate -// and determine where the actual file lies -void ZipDir::CacheFactory::AddFileEntry (char* strFilePath, char* strUnifiedPath, const ZipFile::CDRFileHeader* pFileHeader, const SExtraZipFileData& extra) -{ - if (pFileHeader->lLocalHeaderOffset > m_CDREnd.lCDROffset) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CDR_IS_CORRUPT, "Central Directory contains file descriptors pointing outside the archive file boundaries. The archive file is either truncated or damaged. Please try to repair the file"); // the file offset is beyond the CDR: impossible - return; - } - - if (pFileHeader->nMethod == ZipFile::METHOD_STORE && pFileHeader->desc.lSizeUncompressed != pFileHeader->desc.lSizeCompressed) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_VALIDATION_FAILED, "File with STORE compression method declares its compressed size not matching its uncompressed size. File descriptor is inconsistent, archive content may be damaged, please try to repair the archive"); - return; - } - - FileEntry fileEntry (*pFileHeader, extra); - - if ((m_bEncryptedHeaders || m_nInitMethod >= ZD_INIT_FULL) && pFileHeader->desc.lSizeCompressed) - { - InitDataOffset(fileEntry, pFileHeader); - } - - if (m_bBuildFileEntryMap) - { - m_mapFileEntries.insert (FileEntryMap::value_type(strFilePath, fileEntry)); - } - - if (m_bBuildFileEntryTree) - { - m_treeFileEntries.Add(strFilePath, strUnifiedPath, fileEntry); - } -} - - -////////////////////////////////////////////////////////////////////////// -// initializes the actual data offset in the file in the fileEntry structure -// searches to the local file header, reads it and calculates the actual offset in the file -void ZipDir::CacheFactory::InitDataOffset (FileEntry& fileEntry, const ZipFile::CDRFileHeader* pFileHeader) -{ - // make sure it's the same file and the fileEntry structure is properly initialized - assert (fileEntry.nFileHeaderOffset == pFileHeader->lLocalHeaderOffset); - - /* - // without validation, it would be like this: - ErrorEnum nError = Refresh(&fileEntry); - if (nError != ZD_ERROR_SUCCESS) - THROW_ZIPDIR_ERROR(nError,"Cannot refresh file entry. Probably corrupted file header inside zip file"); - */ - - - if (m_bEncryptedHeaders) - { - // ignore local header - fileEntry.nFileDataOffset = pFileHeader->lLocalHeaderOffset + sizeof(ZipFile::LocalFileHeader) + pFileHeader->nFileNameLength + pFileHeader->nExtraFieldLength; - } - else - { - Seek(pFileHeader->lLocalHeaderOffset); - // read the local file header and the name (for validation) into the buffer - DynArraypBuffer; - unsigned nBufferLength = sizeof(ZipFile::LocalFileHeader) + pFileHeader->nFileNameLength; - pBuffer.resize(nBufferLength); - Read (&pBuffer[0], nBufferLength); - - // validate the local file header (compare with the CDR file header - they should contain basically the same information) - const ZipFile::LocalFileHeader* pLocalFileHeader = (const ZipFile::LocalFileHeader*)&pBuffer[0]; - if (pFileHeader->desc != pLocalFileHeader->desc - || pFileHeader->nMethod != pLocalFileHeader->nMethod - || pFileHeader->nFileNameLength != pLocalFileHeader->nFileNameLength - // for a tough validation, we can compare the timestamps of the local and central directory entries - // but we won't do that for backward compatibility with ZipDir - //|| pFileHeader->nLastModDate != pLocalFileHeader->nLastModDate - //|| pFileHeader->nLastModTime != pLocalFileHeader->nLastModTime - ) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_VALIDATION_FAILED, "The local file header descriptor doesn't match the basic parameters declared in the global file header in the file. The archive content is misconsistent and may be damaged. Please try to repair the archive"); - return; - } - - // now compare the local file name with the one recorded in CDR: they must match. - if (azmemicmp((const char*)&pBuffer[sizeof(ZipFile::LocalFileHeader)], (const char*)pFileHeader + 1, pFileHeader->nFileNameLength)) - { - // either file name, or the extra field do not match - THROW_ZIPDIR_ERROR(ZD_ERROR_VALIDATION_FAILED, "The local file header contains file name which does not match the file name of the global file header. The archive content is misconsistent with its directory. Please repair the archive"); - return; - } - - fileEntry.nFileDataOffset = pFileHeader->lLocalHeaderOffset + sizeof(ZipFile::LocalFileHeader) + pLocalFileHeader->nFileNameLength + pLocalFileHeader->nExtraFieldLength; - } - - if (fileEntry.nFileDataOffset >= m_nCDREndPos) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_VALIDATION_FAILED, "The global file header declares the file which crosses the boundaries of the archive. The archive is either corrupted or truncated, please try to repair it"); - return; - } - - if (m_nInitMethod >= ZD_INIT_VALIDATE) - { - Validate (fileEntry); - } -} - -////////////////////////////////////////////////////////////////////////// -// reads the file pointed by the given header and entry (they must be coherent) -// and decompresses it; then calculates and validates its CRC32 -void ZipDir::CacheFactory::Validate(const FileEntry& fileEntry) -{ - DynArray pBuffer; - // validate the file contents - // allocate memory for both the compressed data and uncompressed data - pBuffer.resize(fileEntry.desc.lSizeCompressed + fileEntry.desc.lSizeUncompressed); - char* pUncompressed = &pBuffer[fileEntry.desc.lSizeCompressed]; - char* pCompressed = &pBuffer[0]; - - assert (fileEntry.nFileDataOffset != FileEntry::INVALID_DATA_OFFSET); - Seek(fileEntry.nFileDataOffset); - - Read(pCompressed, fileEntry.desc.lSizeCompressed); - - if (fileEntry.nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT) - { - ZipDir::Decrypt(pCompressed, fileEntry.desc.lSizeCompressed, m_encryptionKey); - } - - unsigned long nDestSize = fileEntry.desc.lSizeUncompressed; - int nError = Z_OK; - if (fileEntry.nMethod) - { - nError = ZipRawUncompress (pUncompressed, &nDestSize, pCompressed, fileEntry.desc.lSizeCompressed); - } - else - { - assert (fileEntry.desc.lSizeCompressed == fileEntry.desc.lSizeUncompressed); - memcpy (pUncompressed, pCompressed, fileEntry.desc.lSizeUncompressed); - } - switch (nError) - { - case Z_OK: - break; - case Z_MEM_ERROR: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_NO_MEMORY, "ZLib reported out-of-memory error"); - return; - case Z_BUF_ERROR: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_CORRUPTED_DATA, "ZLib reported compressed stream buffer error"); - return; - case Z_DATA_ERROR: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_CORRUPTED_DATA, "ZLib reported compressed stream data error"); - return; - default: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_FAILED, "ZLib reported an unexpected unknown error"); - return; - } - - if (nDestSize != fileEntry.desc.lSizeUncompressed) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_CORRUPTED_DATA, "Uncompressed stream doesn't match the size of uncompressed file stored in the archive file headers"); - return; - } - - uLong uCRC32 = crc32(0L, Z_NULL, 0); - uCRC32 = crc32(uCRC32, (Bytef*)pUncompressed, nDestSize); - if (uCRC32 != fileEntry.desc.lCRC32) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_CRC32_CHECK, "Uncompressed stream CRC32 check failed"); - return; - } -} - - -////////////////////////////////////////////////////////////////////////// -// extracts the file path from the file header with subsequent information -// may, or may not, put all letters to lower-case (depending on whether the system is to be case-sensitive or not) -// it's the responsibility of the caller to ensure that the file name is in readable valid memory -char* ZipDir::CacheFactory::GetFilePath (const char* pFileName, ZipFile::ushort nFileNameLength) -{ - static char strResult[_MAX_PATH]; - assert(nFileNameLength < _MAX_PATH); - memcpy(strResult, pFileName, nFileNameLength); - strResult[nFileNameLength] = 0; - for (int i = 0; i < nFileNameLength; i++) - { - strResult[i] = ::tolower(strResult[i]); - } - - return strResult; -} - -// seeks in the file relative to the starting position -void ZipDir::CacheFactory::Seek (ZipFile::ulong nPos, int nOrigin) // throw -{ - if (AZ_TRAIT_CRYCOMMONTOOLS_FSEEK(m_f, nPos, nOrigin)) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Cannot fseek() to the new position in the file. This is unexpected error and should not happen under any circumstances. Perhaps some network or disk failure error has caused this"); - return; - } -} - -unsigned long ZipDir::CacheFactory::Tell () // throw -{ - AZ::s64 nPos = AZ_TRAIT_CRYCOMMONTOOLS_FTELL(m_f); - if (nPos == -1) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Cannot ftell() position in the archive. This is unexpected error and should not happen under any circumstances. Perhaps some network or disk failure error has caused this"); - return 0; - } - return (unsigned long)nPos; -} - -void ZipDir::CacheFactory::Read (void* pDest, unsigned nSize) // throw -{ - if (fread (pDest, nSize, 1, m_f) != 1) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Cannot fread() a portion of data from archive"); - } -} - -void ZipDir::CacheFactory::ReadHeaderData (void* pDest, unsigned nSize) // throw -{ - Read(pDest, nSize); - - if (m_bEncryptedHeaders) - { - ZipDir::Decrypt((char*)pDest, nSize, m_encryptionKey); - } -} - diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.h deleted file mode 100644 index caf947e1af..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.h +++ /dev/null @@ -1,143 +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. - -// This is the class that can read the directory from Zip file, -// and store it into the directory cache - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHEFACTORY_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHEFACTORY_H -#pragma once - - -namespace ZipDir -{ - class CacheRW; - TYPEDEF_AUTOPTR(CacheRW); - typedef CacheRW_AutoPtr CacheRWPtr; - - // an instance of this class is temporarily created on stack to initialize the CZipFile instance - class CacheFactory - { - public: - enum - { - // open RW cache in read-only mode - FLAGS_READ_ONLY = 1, - // do not compact RW-cached zip upon destruction - FLAGS_DONT_COMPACT = 1 << 1, - // if this is set, then the zip paths won't be memorized in the cache objects - FLAGS_DONT_MEMORIZE_ZIP_PATH = 1 << 2, - // if this is set, the archive will be created anew (the existing file will be overwritten) - FLAGS_CREATE_NEW = 1 << 3 - }; - - // initializes the internal structures - // nFlags can have FLAGS_READ_ONLY flag, in this case the object will be opened only for reading - CacheFactory (InitMethodEnum nInitMethod, unsigned nFlags = 0); - ~CacheFactory(); - - // the new function creates a new cache - CachePtr New(const char* szFileName, const uint32 decryptionKey[4]);// throw (ErrorEnum); - - CacheRWPtr NewRW(const char* szFileName, size_t fileAlignment, bool encrypted, const uint32 encryptionKey[4]); - - protected: - // reads the zip file into the file entry tree. - bool ReadCacheRW (CacheRW& rwCache); - - // creates from the m_f file - // reserves the given number of bytes for future expansion of the object - // upon return, pReserve contains the actual number of bytes that were allocated (more might have been allocated) - CachePtr MakeCache (const char* szFile); - - // this sets the window size of the blocks of data read from the end of the file to find the Central Directory Record - // since normally there are no - enum - { - g_nCDRSearchWindowSize = 0x100 - }; - - void Clear(); - - // reads everything and prepares the maps - bool Prepare(); - - // searches for CDREnd record in the given file - bool FindCDREnd();// throw(ErrorEnum); - - // uses the found CDREnd to scan the CDR and probably the Zip file itself - // builds up the m_mapFileEntries - bool BuildFileEntryMap();// throw (ErrorEnum); - - // give the CDR File Header entry, reads the local file header to validate and determine where - // the actual file lies - // This function can actually modify strFilePath and strUnifiedPath variables, make sure you use copies of real paths. - void AddFileEntry (char* strFilePath, char* strUnifiedPath, const ZipFile::CDRFileHeader* pFileHeader, const SExtraZipFileData& extra);// throw (ErrorEnum); - - // extracts the file path from the file header with subsequent information - // may, or may not, put all letters to lower-case (depending on whether the system is to be case-sensitive or not) - // it's the responsibility of the caller to ensure that the file name is in readable valid memory - char* GetFilePath (const ZipFile::CDRFileHeader* pFileHeader) - { - return GetFilePath((const char*)(pFileHeader + 1), pFileHeader->nFileNameLength); - } - // extracts the file path from the file header with subsequent information - // may, or may not, put all letters to lower-case (depending on whether the system is to be case-sensitive or not) - // it's the responsibility of the caller to ensure that the file name is in readable valid memory - char* GetFilePath (const ZipFile::LocalFileHeader* pFileHeader) - { - return GetFilePath((const char*)(pFileHeader + 1), pFileHeader->nFileNameLength); - } - // extracts the file path from the file header with subsequent information - // may, or may not, put all letters to lower-case (depending on whether the system is to be case-sensitive or not) - // it's the responsibility of the caller to ensure that the file name is in readable valid memory - char* GetFilePath (const char* pFileName, ZipFile::ushort nFileNameLength); - - // validates (if the init method has the corresponding value) the given file/header - void Validate(const FileEntry& fileEntry); - - // initializes the actual data offset in the file in the fileEntry structure - // searches to the local file header, reads it and calculates the actual offset in the file - void InitDataOffset (FileEntry& fileEntry, const ZipFile::CDRFileHeader* pFileHeader); - - // seeks in the file relative to the starting position - void Seek (ZipFile::ulong nPos, int nOrigin = SEEK_SET); // throw - unsigned long Tell (); // throw - void Read (void* pDest, unsigned nSize); // throw - void ReadHeaderData (void* pDest, unsigned nSize);// throw - protected: - - FILE* m_f; - InitMethodEnum m_nInitMethod; - unsigned m_nFlags; - ZipFile::CDREnd m_CDREnd; - - unsigned m_nCDREndPos; // position of the CDR End in the file - - // Map: Relative file path => file entry info - typedef std::map FileEntryMap; - FileEntryMap m_mapFileEntries; - - FileEntryTree m_treeFileEntries; - - DynArray m_CDR_buffer; - DynArray m_unifiedNameBuffer; - - EncryptionKey m_encryptionKey; - bool m_bEncryptedHeaders; - bool m_bBuildFileEntryMap; - bool m_bBuildFileEntryTree; - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHEFACTORY_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.cpp deleted file mode 100644 index 6e47aec5d4..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.cpp +++ /dev/null @@ -1,2100 +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 -#include "Util.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirTree.h" -#include "ZipDirList.h" -#include "ZipDirCache.h" -#include "ZipDirCacheRW.h" -#include "ZipDirCacheFactory.h" -#include "ZipDirFindRW.h" - -#include "ThreadUtils.h" - -#include // declaration of Z_OK for ZipRawDecompress -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum PackFileStatus -{ - PACKFILE_COMPRESSED, - - PACKFILE_ADDED, - PACKFILE_UPTODATE, - PACKFILE_SKIPPED, - PACKFILE_MISSING, - PACKFILE_FAILED -}; - -enum PackFileCompressionPolicy -{ - PACKFILE_USE_REQUESTED_COMPRESSOR, - PACKFILE_USE_FASTEST_DECOMPRESSING_CODEC -}; - -class PackFilePool; -struct PackFileBatch -{ - PackFilePool* pool; - - int zipMaxSize; - int sourceMinSize; - int sourceMaxSize; - int compressionMethod; - int compressionLevel; - - PackFileBatch() - : pool(0) - , sourceMinSize(0) - , sourceMaxSize(0) - , zipMaxSize(0) - , compressionMethod(0) - , compressionLevel(0) - { - } -}; - -class PackFilePool; -struct PackFileJob -{ - int index; - int key; - PackFileBatch* batch; - const char* relativePathSrc; - const char* realFilename; - - unsigned int existingCRC; - - void* compressedData; - unsigned long compressedSize; - unsigned long compressedSizePreviously; - - void* uncompressedData; - unsigned long uncompressedSize; - unsigned long uncompressedSizePreviously; - - int64 modTime; - ZipDir::ErrorEnum zdError; - PackFileStatus status; - PackFileCompressionPolicy compressionPolicy; - - PackFileJob() - : index(0) - , key(0) - , batch(0) - , realFilename(0) - , relativePathSrc(0) - , existingCRC(0) - , compressedData(0) - , compressedSize(0) - , compressedSizePreviously(0) - , uncompressedData(0) - , uncompressedSize(0) - , uncompressedSizePreviously(0) - , modTime(0) - , zdError(ZipDir::ZD_ERROR_NOT_IMPLEMENTED) - , status(PACKFILE_FAILED) - , compressionPolicy(PACKFILE_USE_REQUESTED_COMPRESSOR) - { - } - - void DetachUncompressedData() - { - if (uncompressedData && uncompressedData == compressedData) - { - compressedData = 0; - compressedSize = 0; - } - - uncompressedData = 0; - uncompressedSize = 0; - } - - ~PackFileJob() - { - if (compressedData && compressedData != uncompressedData) - { - azfree(compressedData); - compressedData = 0; - } - - if (uncompressedData) - { - azfree(uncompressedData); - uncompressedData = 0; - } - } -}; - - -// --------------------------------------------------------------------------- -static void PackFileFromDisc(PackFileJob* job); -class PackFilePool -{ -public: - PackFilePool(int numFiles, size_t memoryLimit) - : m_pool(false) - , m_skip(false) - , m_awaitedFile(0) - , m_memoryLimit(memoryLimit) - , m_allocatedMemory(0) - { - m_files.reserve(numFiles); - } - - ~PackFilePool() - { - } - - void Submit(int key, const PackFileJob& job) - { - PackFileJob* newJob = new PackFileJob(job); - - // index in queue, and custom key for identification - newJob->index = int(m_files.size()); - newJob->key = key; - - m_files.push_back(newJob); - } - - PackFileJob* WaitForFile(int index) - { - while (true) - { - { - AZStd::lock_guard lock(m_filesLock); - m_awaitedFile = index; - if (size_t(index) >= m_files.size()) - { - return 0; - } - if (m_files[index]) - { - return m_files[index]; - } - } - Sleep(0); - } - - assert(0); - return 0; - } - - void Start(unsigned numExtraThreads) - { - if (numExtraThreads == 0) - { - for (PackFileJob* job : m_files) - { - PackFileFromDisc(job); - } - } - else - { - for (size_t i = 0; i < m_files.size(); ++i) - { - PackFileJob* job = m_files[i]; - m_files[i] = 0; - m_pool.Submit(&ProcessFile, job); - } - - m_pool.Start(numExtraThreads); - } - } - - size_t GetJobCount() const - { - return m_files.size(); - } - - void SkipPendingFiles() - { - m_skip = true; - } - - void ReleaseFile(int index) - { - assert(m_files[index] != 0); - if (m_files[index]) - { - if (m_memoryLimit != 0) - { - AZStd::lock_guard lock(m_filesLock); - - m_allocatedMemory -= m_files[index]->uncompressedSize; - m_allocatedMemory -= m_files[index]->compressedSize; - } - - delete m_files[index]; - m_files[index] = 0; - } - } - -private: - - // called from non-main thread - static void ProcessFile(PackFileJob* job) - { - PackFilePool* self = job->batch->pool; - - if (!self->m_skip) - { - if (self->m_memoryLimit != 0) - { - while (true) - { - size_t allocatedMemory = 0; - int awaitedFile = 0; - { - AZStd::lock_guard lock(self->m_filesLock); - allocatedMemory = self->m_allocatedMemory; - awaitedFile = self->m_awaitedFile; - } - - if (allocatedMemory > self->m_memoryLimit && job->index > awaitedFile + 1) - { - Sleep(10); // give time to main thread to write data to file - } - else - { - break; - } - } - } - - PackFileFromDisc(job); - } - - self->FileCompleted(job); - } - - // called from non-main thread - void FileCompleted(PackFileJob* job) - { - AZStd::lock_guard lock(m_filesLock); - - assert(job); - assert(job->index < m_files.size()); - assert(m_files[job->index] == 0); - m_files[job->index] = job; - - if (m_memoryLimit != 0) - { - m_allocatedMemory += job->uncompressedSize; - m_allocatedMemory += job->compressedSize; - } - } - - size_t m_memoryLimit; - - AZStd::mutex m_filesLock; - std::vector m_files; - int m_awaitedFile; - size_t m_allocatedMemory; - bool m_skip; - - ThreadUtils::SimpleThreadPool m_pool; -}; - -////////////////////////////////////////////////////////////////////////// -static size_t AlignTo(size_t offset, size_t alignment) -{ - const size_t remainder = offset % alignment; - return remainder ? offset + alignment - remainder : offset; -} -////////////////////////////////////////////////////////////////////////// -// Calculates new offset of the header to make sure that following data are -// aligned properly -static size_t CalculateAlignedHeaderOffset(const char* fileName, size_t currentOffset, size_t alignment) -{ - // Since file should start from header - if (currentOffset == 0) - { - return 0; - } - - // Local header is followed by filename - const size_t totalHeaderSize = sizeof(ZipFile::LocalFileHeader) + strlen(fileName); - - // Align end of the header - const size_t dataOffset = AlignTo(currentOffset + totalHeaderSize, alignment); - - return dataOffset - totalHeaderSize; -} - -////////////////////////////////////////////////////////////////////////// -ZipDir::CacheRW::CacheRW(bool encryptHeaders, const EncryptionKey& encryptionKey) - : m_pFile (NULL) - , m_nFlags (0) - , m_lCDROffset (0) - , m_fileAlignment (1) - , m_bEncryptedHeaders(encryptHeaders) - , m_bHeadersEncryptedOnClose(encryptHeaders) - , m_encryptionKey(encryptionKey) -{ - m_nRefCount = 0; -} -////////////////////////////////////////////////////////////////////////// -ZipDir::CacheRW::~CacheRW() -{ - Close(); -} -////////////////////////////////////////////////////////////////////////// -void ZipDir::CacheRW::AddRef() -{ - ++m_nRefCount; -} - -////////////////////////////////////////////////////////////////////////// -void ZipDir::CacheRW::Release() -{ - if (--m_nRefCount <= 0) - { - delete this; - } -} - -void ZipDir::CacheRW::Close() -{ - if (m_pFile) - { - if (!(m_nFlags & FLAGS_READ_ONLY)) - { - if ((m_nFlags & FLAGS_UNCOMPACTED) && !(m_nFlags & FLAGS_DONT_COMPACT)) - { - if (!RelinkZip()) - { - WriteCDR(); - } - } - else - if (m_nFlags & FLAGS_CDR_DIRTY) - { - WriteCDR(); - } - } - - if (m_pFile) // RelinkZip() might have closed the file - { - fclose (m_pFile); - } - - m_pFile = NULL; - } - m_treeDir.Clear(); -} - -////////////////////////////////////////////////////////////////////////// -char* ZipDir::CacheRW::UnifyPath(char* const str, const char* pPath) -{ - assert(str); - const char* src = pPath; - char* trg = str; - while (*src) - { - if (*src != '/') - { - *trg++ = ::tolower(*src++); - } - else - { - *trg++ = '\\'; - src++; - } - } - *trg = 0; - return str; -} - -////////////////////////////////////////////////////////////////////////// -char* ZipDir::CacheRW::ToUnixPath(char* const str, const char* pPath) -{ - assert(str); - const char* src = pPath; - char* trg = str; - while (*src) - { - if (*src != '/') - { - *trg++ = *src++; - } - else - { - *trg++ = '\\'; - src++; - } - } - *trg = 0; - return str; -} - -////////////////////////////////////////////////////////////////////////// -char* ZipDir::CacheRW::AllocPath(const char* pPath) -{ - char str[_MAX_PATH]; - char* temp = ToUnixPath(str, pPath); - temp = m_tempStringPool.Append(temp, strlen(temp)); - return temp; -} - -static bool UseZlibForFileType(const char* filename) -{ - AZStd::string f(filename); - - //some files types are forced to use zlib - bool found = AzFramework::StringFunc::Path::IsExtension(filename, ".dds") || f.find("cover.ctc") != string::npos || AzFramework::StringFunc::Path::IsExtension(filename, ".uicanvas"); - - return found; -} - -#ifdef AZ_DEBUG_BUILD -static const char* CodecAsString(CompressionCodec::Codec codec) -{ - switch (codec) - { - case CompressionCodec::Codec::ZLIB: - return "ZLIB"; - case CompressionCodec::Codec::ZSTD: - return "ZSTD"; - case CompressionCodec::Codec::LZ4: - return "LZ4"; - } - return "ERROR"; -} -#endif - -static bool CompressData(PackFileJob *job) -{ - bool bUseZlib = UseZlibForFileType(job->relativePathSrc) || (job->compressionPolicy == PACKFILE_USE_REQUESTED_COMPRESSOR); - - bool compressionSuccessful = true; - - if (bUseZlib) - { - job->compressedSize = ZipDir::GetCompressedSizeEstimate(job->uncompressedSize,CompressionCodec::Codec::ZLIB); - job->compressedData = azmalloc(job->compressedSize); - int error = ZipDir::ZipRawCompress(job->uncompressedData, &job->compressedSize, job->compressedData, job->uncompressedSize, job->batch->compressionLevel); - if (error == Z_OK) - { - job->status = PACKFILE_COMPRESSED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - } - else - { - compressionSuccessful = false; - } - } - else - { - unsigned long compressedSize[static_cast(CompressionCodec::Codec::NUM_CODECS)]; - void* compressedData[static_cast(CompressionCodec::Codec::NUM_CODECS)]; - std::chrono::milliseconds decompressionTime[static_cast(CompressionCodec::Codec::NUM_CODECS)]; - bool compressionCodecWasSuccessful[static_cast(CompressionCodec::Codec::NUM_CODECS)]; - - std::chrono::time_point start; - - //do compression - for (CompressionCodec::Codec codec : CompressionCodec::s_AllCodecs) - { - unsigned int index = static_cast(codec); - compressedSize[index] = ZipDir::GetCompressedSizeEstimate(job->uncompressedSize, codec); - compressedData[index] = azmalloc(compressedSize[index]); - AZStd::unique_ptr tempBuffer; - unsigned long tempSize = 0; - - //some files decompress so fast they are beyond our ability to measure so we need to do it a few times to get a reading - int numTimesToDecompress = 1 + ZipDir::TARGET_MIN_TEST_COMPRESS_BYTES / job->uncompressedSize; - - auto testDecompressionTime = [&tempSize, job, &tempBuffer, &start, &compressionCodecWasSuccessful, index, numTimesToDecompress, &compressedData, &compressedSize, &decompressionTime]() { - tempSize = job->uncompressedSize; - tempBuffer = AZStd::make_unique(tempSize); - start = std::chrono::high_resolution_clock::now(); - - //start by assuming the decompression test is never going to result in an error - compressionCodecWasSuccessful[index] = true; - - for (int i = 0; i < numTimesToDecompress; i++) - { - int zerror = ZipDir::ZipRawUncompress(tempBuffer.get(), &tempSize, compressedData[index], compressedSize[index]); - if (zerror != Z_OK) - { - compressionCodecWasSuccessful[index] = false; - break; - } - } - decompressionTime[index] = std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - start); - }; - - switch (codec) - { - case CompressionCodec::Codec::ZLIB: - if (ZipDir::ZipRawCompress(job->uncompressedData, &compressedSize[index], compressedData[index], job->uncompressedSize, job->batch->compressionLevel) == Z_OK) - { - testDecompressionTime(); - } - else - { - compressionCodecWasSuccessful[index] = false; - } - break; - - case CompressionCodec::Codec::ZSTD: - if (ZipDir::ZipRawCompressZSTD(job->uncompressedData, &compressedSize[index], compressedData[index], job->uncompressedSize, 1) == Z_OK) - { - testDecompressionTime(); - } - else - { - compressionCodecWasSuccessful[index] = false; - } - break; - - case CompressionCodec::Codec::LZ4: - if (ZipDir::ZipRawCompressLZ4(job->uncompressedData, &compressedSize[index], compressedData[index], job->uncompressedSize, job->batch->compressionLevel) == Z_OK) - { - testDecompressionTime(); - } - else - { - compressionCodecWasSuccessful[index] = false; - } - - break; - - default: - break; - } - } - - //check decompression speed - int bestTimeIndex = -1; - int numberOfSuccessfulCodecs = 0; - for (CompressionCodec::Codec codec : CompressionCodec::s_AllCodecs) - { - int index = static_cast(codec); - if (compressionCodecWasSuccessful[index]) - { - numberOfSuccessfulCodecs++; - if (bestTimeIndex == -1) - { - bestTimeIndex = index; - continue; - } - if ((decompressionTime[index] < decompressionTime[bestTimeIndex])) - { - bestTimeIndex = index; - } - } - } - - if (!numberOfSuccessfulCodecs) - { - AZ_Error("ZipDirCacheRW", false, "None of the available codecs were able to compress the file: %s", job->relativePathSrc); - compressionSuccessful = false; - } - else - { -#ifdef AZ_DEBUG_BUILD - AZ_Printf("ZipDirCacheRW", "Winner for %s is %s with: %d ms ", job->realFilename, CodecAsString(static_cast(bestTimeIndex)), decompressionTime[bestTimeIndex]); -#endif - } - - //get rid of losing data - for (CompressionCodec::Codec codec : CompressionCodec::s_AllCodecs) - { - int index = static_cast(codec); - if (index != bestTimeIndex) - { - azfree(compressedData[index]); - compressedData[index] = nullptr; - } - } - - if (compressionSuccessful) - { - job->compressedSize = compressedSize[bestTimeIndex]; - job->compressedData = compressedData[bestTimeIndex]; - } - } - - //if there was a problem with the compression so just store the file - if (!compressionSuccessful) - { - azfree(job->compressedData); - job->compressedData = job->uncompressedData; - job->compressedSize = job->uncompressedSize; - } - job->status = PACKFILE_COMPRESSED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - return true; -} - -static void PackFileFromMemory(PackFileJob* job) -{ - if (job->existingCRC != 0) - { - unsigned int crcCode = (unsigned int)crc32(0, (unsigned char*)job->uncompressedData, job->uncompressedSize); - if (crcCode == job->existingCRC) - { - job->compressedData = 0; - job->compressedSize = 0; - job->status = PACKFILE_UPTODATE; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - // This file with same data already in pak, skip it. - return; - } - } - - switch (job->batch->compressionMethod) - { - case ZipFile::METHOD_DEFLATE_AND_ENCRYPT: - case ZipFile::METHOD_DEFLATE: - { - // allocate memory for compression. Min is nSize * 1.001 + 12 - if (job->uncompressedSize > 0) - { - CompressData(job); - } - else - { - job->status = PACKFILE_COMPRESSED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - - job->compressedSize = 0; - job->compressedData = 0; - } - break; - } - case ZipFile::METHOD_STORE: - job->compressedData = job->uncompressedData; - job->compressedSize = job->uncompressedSize; - job->status = PACKFILE_COMPRESSED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - break; - - default: - job->status = PACKFILE_FAILED; - job->zdError = ZipDir::ZD_ERROR_UNSUPPORTED; - break; - } -} - -bool ZipDir::CacheRW::WriteCompressedData(const char* data, size_t size, bool encrypt, FILE* file) -{ - if (size <= 0) - { - return true; - } - - std::vector buffer; - if (encrypt) - { - buffer.resize(size); - memcpy(&buffer[0], data, size); - ZipDir::Encrypt(&buffer[0], size, m_encryptionKey); - data = &buffer[0]; - } - - // Danny - writing a single large chunk (more than 6MB?) causes - // Windows fwrite to (silently?!) fail. So we're writing data - // in small chunks. - while (size > 0) - { - const size_t sizeToWrite = Util::getMin(size, size_t(1024 * 1024)); - if (fwrite(data, sizeToWrite, 1, file) != 1) - { - return false; - } - data += sizeToWrite; - size -= sizeToWrite; - } - - return true; -} - -static bool WriteRandomData(FILE* file, size_t size) -{ - if (size <= 0) - { - return true; - } - - const size_t bufferSize = Util::getMin(size, size_t(1024 * 1024)); - std::vector buffer(bufferSize); - - while (size > 0) - { - const size_t sizeToWrite = Util::getMin(size, bufferSize); - - for (size_t i = 0; i < sizeToWrite; ++i) - { - buffer[i] = rand() & 0xff; - } - - if (fwrite(&buffer[0], sizeToWrite, 1, file) != 1) - { - return false; - } - - size -= sizeToWrite; - } - - return true; -} - -bool ZipDir::CacheRW::WriteNullData(size_t size) -{ - if (size <= 0) - { - return true; - } - - const size_t bufferSize = Util::getMin(size, size_t(1024 * 1024)); - std::vector buffer(bufferSize, 0); - - while (size > 0) - { - const size_t sizeToWrite = Util::getMin(size, bufferSize); - - if (fwrite(&buffer[0], sizeToWrite, 1, m_pFile) != 1) - { - return false; - } - - size -= sizeToWrite; - } - - return true; -} - -void ZipDir::CacheRW::StorePackedFile(PackFileJob* job) -{ - if (job->batch->zipMaxSize > 0 && GetTotalFileSize() > job->batch->zipMaxSize) - { - job->status = PACKFILE_SKIPPED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - return; - } - - job->status = PACKFILE_FAILED; - - char str[_MAX_PATH]; - char* relativePath = UnifyPath(str, job->relativePathSrc); - - // create or find the file entry.. this object will rollback (delete the object - // if the operation fails) if needed. - FileEntryTransactionAdd pFileEntry(this, AllocPath(job->relativePathSrc), AllocPath(relativePath)); - - if (!pFileEntry) - { - job->zdError = ZipDir::ZD_ERROR_INVALID_PATH; - return; - } - - pFileEntry->OnNewFileData(job->uncompressedData, job->uncompressedSize, - job->compressedSize, job->batch->compressionMethod, false); - pFileEntry->SetFromFileTimeNTFS(job->modTime); - - // since we changed the time, we'll have to update CDR - m_nFlags |= FLAGS_CDR_DIRTY; - - // the new CDR position, if the operation completes successfully - unsigned lNewCDROffset = m_lCDROffset; - - if (pFileEntry->IsInitialized()) - { - // this file entry is already allocated in CDR - - // check if the new compressed data fits into the old place - unsigned nFreeSpace = pFileEntry->nEOFOffset - pFileEntry->nFileHeaderOffset - (unsigned)sizeof(ZipFile::LocalFileHeader) - (unsigned)strlen(relativePath); - - if (nFreeSpace != job->compressedSize) - { - m_nFlags |= FLAGS_UNCOMPACTED; - } - - if (nFreeSpace >= job->compressedSize) - { - // and we can just override the compressed data in the file - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, job->relativePathSrc, m_bEncryptedHeaders); - if (e != ZipDir::ZD_ERROR_SUCCESS) - { - job->zdError = e; - return; - } - } - else - { - // we need to write the file anew - in place of current CDR - pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset(job->relativePathSrc, m_lCDROffset, m_fileAlignment); - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, job->relativePathSrc, m_bEncryptedHeaders); - lNewCDROffset = pFileEntry->nEOFOffset; - if (e != ZipDir::ZD_ERROR_SUCCESS) - { - job->zdError = e; - return; - } - } - } - else - { - pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset(job->relativePathSrc, m_lCDROffset, m_fileAlignment); - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, job->relativePathSrc, m_bEncryptedHeaders); - if (e != ZipDir::ZD_ERROR_SUCCESS) - { - job->zdError = e; - return; - } - - lNewCDROffset = pFileEntry->nFileDataOffset + job->compressedSize; - - m_nFlags |= FLAGS_CDR_DIRTY; - } - - // now we have the fresh local header and data offset - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileDataOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, pFileEntry->nFileDataOffset, SEEK_SET) != 0) -#endif - { - job->zdError = ZD_ERROR_IO_FAILED; - return; - } - - const bool encrypt = pFileEntry->nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT; - - if (!WriteCompressedData((char*)job->compressedData, job->compressedSize, encrypt, m_pFile)) - { - job->zdError = ZD_ERROR_IO_FAILED; - return; - } - - // since we wrote the file successfully, update the new CDR position - m_lCDROffset = lNewCDROffset; - pFileEntry.Commit(); - - job->status = PACKFILE_ADDED; - job->zdError = ZD_ERROR_SUCCESS; -} - -// Adds a new file to the zip or update an existing one -// adds a directory (creates several nested directories if needed) -ZipDir::ErrorEnum ZipDir::CacheRW::UpdateFile (const char* szRelativePathSrc, void* pUncompressed, unsigned nSize, - unsigned nCompressionMethod, int nCompressionLevel, int64 modTime) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - - PackFileBatch batch; - batch.compressionMethod = nCompressionMethod; - batch.compressionLevel = nCompressionLevel; - - PackFileJob job; - job.relativePathSrc = szRelativePathSrc; - job.modTime = modTime; - job.uncompressedData = pUncompressed; - job.uncompressedSize = nSize; - job.batch = &batch; - - // crc will be used to check if this file need to be updated at all - ZipDir::FileEntry* entry = FindFile(szRelativePath); - if (entry) - { - job.existingCRC = entry->desc.lCRC32; - } - - PackFileFromMemory(&job); - - switch (job.status) - { - case PACKFILE_SKIPPED: - case PACKFILE_MISSING: - case PACKFILE_FAILED: - return ZD_ERROR_IO_FAILED; - } - - StorePackedFile(&job); - job.DetachUncompressedData(); - return job.zdError; -} - -static FILETIME GetFileWriteTimeAndSize(uint64* fileSize, const char* filename) -{ - // Warning: FindFirstFile on NTFS may report file size that - // is not up-to-date with the actual file content. - // http://blogs.msdn.com/b/oldnewthing/archive/2011/12/26/10251026.aspx - - FILETIME fileTime; - -#if defined(AZ_PLATFORM_WINDOWS) - WIN32_FIND_DATAA FindFileData; - HANDLE hFind = FindFirstFileA(filename, &FindFileData); - - if (hFind == INVALID_HANDLE_VALUE) - { - fileTime.dwLowDateTime = 0; - fileTime.dwHighDateTime = 0; - if (fileSize) - { - *fileSize = 0; - } - } - else - { - fileTime.dwLowDateTime = FindFileData.ftLastWriteTime.dwLowDateTime; - fileTime.dwHighDateTime = FindFileData.ftLastWriteTime.dwHighDateTime; - if (fileSize) - { - *fileSize = (uint64(FindFileData.nFileSizeHigh) << 32) + FindFileData.nFileSizeLow; - } - FindClose(hFind); - } -#elif AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX) - //We cant use this implmentation for the windows version because ModificationTime - //returns the time filename was changed(ChangeTime) not last written into(LastWriteTime). - //If LocalFileIO ever adds support for LastWriteTime we can have a common implementation. - AZ::IO::LocalFileIO localFileIO; - AZ::u64 modTime = 0; - modTime = localFileIO.ModificationTime(filename); - if(modTime != 0) - { - fileTime.dwHighDateTime = modTime >> 32; - fileTime.dwLowDateTime = modTime & 0xFFFFFFFF; - if (fileSize) - { - localFileIO.Size(filename, *fileSize); - } - } -#else -#error Needs implmentation! -#endif - return fileTime; -} -static void PackFileFromDisc(PackFileJob* job) -{ - const FILETIME ft = GetFileWriteTimeAndSize(0, job->realFilename); - LARGE_INTEGER lt; - lt.HighPart = ft.dwHighDateTime; - lt.LowPart = ft.dwLowDateTime; - job->modTime = lt.QuadPart; - - FILE* f = nullptr; - azfopen(&f, job->realFilename, "rb"); - if (!f) - { - job->status = PACKFILE_FAILED; - job->zdError = ZipDir::ZD_ERROR_FILE_NOT_FOUND; - return; - } - - fseek(f, 0, SEEK_END); - size_t fileSize = (size_t)ftell(f); - - if ((fileSize < job->batch->sourceMinSize) || (job->batch->sourceMaxSize > 0 && fileSize > job->batch->sourceMaxSize)) - { - fclose(f); - - job->status = PACKFILE_SKIPPED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - return; - } - - if (!fileSize) - { - //Allow 0-Bytes long files. - job->uncompressedData = nullptr; - } - else - { - job->uncompressedData = azmalloc(fileSize); - - fseek(f, 0, SEEK_SET); - if (fread(job->uncompressedData, 1, fileSize, f) != fileSize) - { - azfree(job->uncompressedData); - job->uncompressedData = 0; - fclose(f); - - job->status = PACKFILE_FAILED; - job->zdError = ZipDir::ZD_ERROR_IO_FAILED; - return; - } - } - fclose(f); - job->uncompressedSize = fileSize; - - PackFileFromMemory(job); -} - -bool ZipDir::CacheRW::UpdateMultipleFiles(const char** realFilenames, const char** filenamesInZip, size_t fileCount, - int compressionLevel, bool encryptContent, size_t zipMaxSize, int sourceMinSize, int sourceMaxSize, - unsigned numExtraThreads, ZipDir::IReporter* reporter, ZipDir::ISplitter* splitter, bool useFastestDecompressionCodec) -{ - int compressionMethod = ZipFile::METHOD_DEFLATE; - if (encryptContent) - { - compressionMethod = ZipFile::METHOD_DEFLATE_AND_ENCRYPT; - } - else if (compressionLevel == 0) - { - compressionMethod = ZipFile::METHOD_STORE; - } - - uint64 totalSize = 0; - - clock_t startTime = clock(); - - PackFileBatch batch; - batch.compressionLevel = compressionLevel; - batch.compressionMethod = compressionMethod; - batch.sourceMinSize = sourceMinSize; - batch.sourceMaxSize = sourceMaxSize; - batch.zipMaxSize = zipMaxSize; - - const size_t memoryLimit = 1024 * 1024 * 1024; // prevents threads from generating more than 1GB of data - PackFilePool pool(fileCount, memoryLimit); - batch.pool = &pool; - - for (int i = 0; i < fileCount; ++i) - { - const char* realFilename = realFilenames[i]; - const char* filenameInZip = filenamesInZip[i]; - - PackFileJob job; - - job.relativePathSrc = filenameInZip; - job.realFilename = realFilename; - job.batch = &batch; - job.compressionPolicy = useFastestDecompressionCodec ? PACKFILE_USE_FASTEST_DECOMPRESSING_CODEC : PACKFILE_USE_REQUESTED_COMPRESSOR; - - { - // crc will be used to check if this file need to be updated at all - ZipDir::FileEntry* entry = FindFile(filenameInZip); - if (entry) - { - uint64 fileSize = 0; - - const FILETIME ft = GetFileWriteTimeAndSize(&fileSize, realFilename); - LARGE_INTEGER lt; - - lt.HighPart = ft.dwHighDateTime; - lt.LowPart = ft.dwLowDateTime; - job.modTime = lt.QuadPart; - job.existingCRC = entry->desc.lCRC32; - job.compressedSizePreviously = entry->desc.lSizeCompressed; - job.uncompressedSizePreviously = entry->desc.lSizeUncompressed; - - // Check if file with the same name, timestamp and size already exists in pak. - if (entry->CompareFileTimeNTFS(job.modTime) && fileSize == entry->desc.lSizeUncompressed) - { - if (reporter) - { - reporter->ReportUpToDate(filenameInZip); - } - continue; - } - } - } - - pool.Submit(i, job); - } - - // Get the number of submitted jobs, which is at most - // as large as the largest successfully submitted file-index. - // Any number of files can be skipped for submission. - const int jobCount = pool.GetJobCount(); - if (jobCount == 0) - { - return true; - } - - pool.Start(numExtraThreads); - - for (int i = 0; i < jobCount; ++i) - { - PackFileJob* job = pool.WaitForFile(i); - if (!job) - { - assert(job); - continue; - } - - if (job->status == PACKFILE_COMPRESSED) - { - if (splitter) - { - size_t dsk = GetTotalFileSizeOnDiskSoFar(); - size_t bse = 0; - size_t add = 0; - size_t sub = 0; - - bse += sizeof(ZipFile::CDRFileHeader) + strlen(job->relativePathSrc); - bse += sizeof(ZipFile::LocalFileHeader) + strlen(job->relativePathSrc); - - if (job->compressedSize) - { - add += bse + job->compressedSize; - } - if (job->compressedSizePreviously) - { - sub += bse + job->compressedSizePreviously; - } - - if (splitter->CheckWriteLimit(dsk, add, sub)) - { - splitter->SetLastFile(dsk, add, sub, job->key - 1); - - // deplete the pool before leaving the loop - pool.SkipPendingFiles(); - for (; i < jobCount; ++i) - { - pool.WaitForFile(i); - pool.ReleaseFile(i); - } - - break; - } - } - - StorePackedFile(job); - } - - switch (job->status) - { - case PACKFILE_ADDED: - if (reporter) - { - reporter->ReportAdded(job->relativePathSrc); - } - - totalSize += job->uncompressedSize; - break; - case PACKFILE_MISSING: - if (reporter) - { - reporter->ReportMissing(job->realFilename); - } - break; - case PACKFILE_UPTODATE: - if (reporter) - { - reporter->ReportUpToDate(job->realFilename); - } - break; - case PACKFILE_SKIPPED: - if (reporter) - { - reporter->ReportSkipped(job->realFilename); - } - break; - default: - if (reporter) - { - reporter->ReportFailed(job->realFilename, ""); // TODO reason - } - break; - } - - pool.ReleaseFile(i); - } - - clock_t endTime = clock(); - double timeSeconds = double(endTime - startTime) / CLOCKS_PER_SEC; - double speed = (endTime - startTime) == 0 ? 0.0 : double(totalSize) / timeSeconds; - - if (reporter) - { - reporter->ReportSpeed(speed); - } - - return true; -} - - -// Adds a new file to the zip or update an existing one if it is not compressed - just stored - start a big file -ZipDir::ErrorEnum ZipDir::CacheRW::StartContinuousFileUpdate(const char* szRelativePathSrc, unsigned nSize) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - SmartPtr pBufferDestroyer; - - // create or find the file entry.. this object will rollback (delete the object - // if the operation fails) if needed. - FileEntryTransactionAdd pFileEntry(this, AllocPath(szRelativePathSrc), AllocPath(szRelativePath)); - - if (!pFileEntry) - { - return ZD_ERROR_INVALID_PATH; - } - - pFileEntry->OnNewFileData (NULL, nSize, nSize, ZipFile::METHOD_STORE, false); - // since we changed the time, we'll have to update CDR - m_nFlags |= FLAGS_CDR_DIRTY; - - // the new CDR position, if the operation completes successfully - unsigned lNewCDROffset = m_lCDROffset; - if (pFileEntry->IsInitialized()) - { - // check if the new compressed data fits into the old place - unsigned nFreeSpace = pFileEntry->nEOFOffset - pFileEntry->nFileHeaderOffset - (unsigned)sizeof(ZipFile::LocalFileHeader) - (unsigned)strlen(szRelativePath); - - if (nFreeSpace != nSize) - { - m_nFlags |= FLAGS_UNCOMPACTED; - } - - if (nFreeSpace >= nSize) - { - // and we can just override the compressed data in the file - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePathSrc, m_bEncryptedHeaders); - if (e != ZD_ERROR_SUCCESS) - { - return e; - } - } - else - { - // we need to write the file anew - in place of current CDR - pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset(szRelativePathSrc, m_lCDROffset, m_fileAlignment); - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePathSrc, m_bEncryptedHeaders); - lNewCDROffset = pFileEntry->nEOFOffset; - if (e != ZD_ERROR_SUCCESS) - { - return e; - } - } - } - else - { - pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset(szRelativePathSrc, m_lCDROffset, m_fileAlignment); - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePathSrc, m_bEncryptedHeaders); - if (e != ZD_ERROR_SUCCESS) - { - return e; - } - - lNewCDROffset = pFileEntry->nFileDataOffset + nSize; - - m_nFlags |= FLAGS_CDR_DIRTY; - } - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileDataOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, pFileEntry->nFileDataOffset, SEEK_SET) != 0) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - if (!WriteNullData(nSize)) - { - return ZD_ERROR_IO_FAILED; - } - - pFileEntry->nEOFOffset = pFileEntry->nFileDataOffset; - - // since we wrote the file successfully, update the new CDR position - m_lCDROffset = lNewCDROffset; - pFileEntry.Commit(); - - return ZD_ERROR_SUCCESS; -} - -// Adds a new file to the zip or update an existing's segment if it is not compressed - just stored -// adds a directory (creates several nested directories if needed) -ZipDir::ErrorEnum ZipDir::CacheRW::UpdateFileContinuousSegment (const char* szRelativePathSrc, [[maybe_unused]] unsigned nSize, void* pUncompressed, unsigned nSegmentSize, unsigned nOverwriteSeekPos) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - SmartPtr pBufferDestroyer; - - // create or find the file entry.. this object will rollback (delete the object - // if the operation fails) if needed. - FileEntryTransactionAdd pFileEntry(this, AllocPath(szRelativePathSrc), AllocPath(szRelativePath)); - - if (!pFileEntry) - { - return ZD_ERROR_INVALID_PATH; - } - - pFileEntry->OnNewFileData (pUncompressed, nSegmentSize, nSegmentSize, ZipFile::METHOD_STORE, true); - // since we changed the time, we'll have to update CDR - m_nFlags |= FLAGS_CDR_DIRTY; - - // this file entry is already allocated in CDR - unsigned lSegmentOffset = pFileEntry->nEOFOffset; - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileHeaderOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, pFileEntry->nFileHeaderOffset, SEEK_SET) != 0) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - // and we can just override the compressed data in the file - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePath, m_bEncryptedHeaders); - if (e != ZD_ERROR_SUCCESS) - { - return e; - } - - if (nOverwriteSeekPos != 0xffffffff) - { - lSegmentOffset = pFileEntry->nFileDataOffset + nOverwriteSeekPos; - } - - // now we have the fresh local header and data offset -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)lSegmentOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, lSegmentOffset, SEEK_SET) != 0) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - const bool encrypt = false; // encryption is not supported for continous updates - if (!WriteCompressedData((char*)pUncompressed, nSegmentSize, encrypt, m_pFile)) - { - return ZD_ERROR_IO_FAILED; - } - - if (nOverwriteSeekPos == 0xffffffff) - { - pFileEntry->nEOFOffset = lSegmentOffset + nSegmentSize; - } - - // since we wrote the file successfully, update CDR - pFileEntry.Commit(); - return ZD_ERROR_SUCCESS; -} - - -ZipDir::ErrorEnum ZipDir::CacheRW::UpdateFileCRC (const char* szRelativePathSrc, unsigned dwCRC32) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - SmartPtr pBufferDestroyer; - - // create or find the file entry.. this object will rollback (delete the object - // if the operation fails) if needed. - FileEntryTransactionAdd pFileEntry(this, AllocPath(szRelativePathSrc), AllocPath(szRelativePath)); - - if (!pFileEntry) - { - return ZD_ERROR_INVALID_PATH; - } - - // since we changed the time, we'll have to update CDR - m_nFlags |= FLAGS_CDR_DIRTY; - - pFileEntry->desc.lCRC32 = dwCRC32; - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileHeaderOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, pFileEntry->nFileHeaderOffset, SEEK_SET) != 0) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - // and we can just override the compressed data in the file - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePath, m_bEncryptedHeaders); - if (e != ZD_ERROR_SUCCESS) - { - return e; - } - - // since we wrote the file successfully, update - pFileEntry.Commit(); - return ZD_ERROR_SUCCESS; -} - - -// deletes the file from the archive -ZipDir::ErrorEnum ZipDir::CacheRW::RemoveFile (const char* szRelativePathSrc) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - // find the last slash in the path - const char* pSlash = (std::max)(strrchr(szRelativePath, '/'), strrchr(szRelativePath, '\\')); - - const char* pFileName; // the name of the file to delete - - FileEntryTree* pDir; // the dir from which the subdir will be deleted - - if (pSlash) - { - FindDirRW fd (GetRoot()); - // the directory to remove - pDir = fd.FindExact(string (szRelativePath, pSlash - szRelativePath).c_str()); - if (!pDir) - { - return ZD_ERROR_DIR_NOT_FOUND;// there is no such directory - } - pFileName = pSlash + 1; - } - else - { - pDir = GetRoot(); - pFileName = szRelativePath; - } - - ErrorEnum e = pDir->RemoveFile (pFileName); - if (e == ZD_ERROR_SUCCESS) - { - m_nFlags |= FLAGS_UNCOMPACTED | FLAGS_CDR_DIRTY; - } - return e; -} - - -// deletes the directory, with all its descendants (files and subdirs) -ZipDir::ErrorEnum ZipDir::CacheRW::RemoveDir (const char* szRelativePathSrc) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - // find the last slash in the path - const char* pSlash = (std::max)(strrchr(szRelativePath, '/'), strrchr(szRelativePath, '\\')); - - const char* pDirName; // the name of the dir to delete - - FileEntryTree* pDir; // the dir from which the subdir will be deleted - - if (pSlash) - { - FindDirRW fd (GetRoot()); - // the directory to remove - pDir = fd.FindExact(string (szRelativePath, pSlash - szRelativePath).c_str()); - if (!pDir) - { - return ZD_ERROR_DIR_NOT_FOUND;// there is no such directory - } - pDirName = pSlash + 1; - } - else - { - pDir = GetRoot(); - pDirName = szRelativePath; - } - - ErrorEnum e = pDir->RemoveDir (pDirName); - if (e == ZD_ERROR_SUCCESS) - { - m_nFlags |= FLAGS_UNCOMPACTED | FLAGS_CDR_DIRTY; - } - return e; -} - -// deletes all files and directories in this archive -ZipDir::ErrorEnum ZipDir::CacheRW::RemoveAll() -{ - ErrorEnum e = m_treeDir.RemoveAll(); - if (e == ZD_ERROR_SUCCESS) - { - m_nFlags |= FLAGS_UNCOMPACTED | FLAGS_CDR_DIRTY; - } - return e; -} - -ZipDir::ErrorEnum ZipDir::CacheRW::ReadFile (FileEntry* pFileEntry, void* pCompressed, void* pUncompressed) -{ - if (!pFileEntry) - { - return ZD_ERROR_INVALID_CALL; - } - - if (pFileEntry->desc.lSizeUncompressed == 0) - { - assert (pFileEntry->desc.lSizeCompressed == 0); - return ZD_ERROR_SUCCESS; - } - - assert (pFileEntry->desc.lSizeCompressed > 0); - - ErrorEnum nError = Refresh(pFileEntry); - if (nError != ZD_ERROR_SUCCESS) - { - return nError; - } - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileDataOffset, SEEK_SET)) -#else - if (fseek (m_pFile, pFileEntry->nFileDataOffset, SEEK_SET)) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - SmartPtr pBufferDestroyer; - - void* pBuffer = pCompressed; // the buffer where the compressed data will go - - if (pFileEntry->nMethod == 0 && pUncompressed) - { - // we can directly read into the uncompress buffer - pBuffer = pUncompressed; - } - - if (!pBuffer) - { - if (!pUncompressed) - { - // what's the sense of it - no buffers at all? - return ZD_ERROR_INVALID_CALL; - } - - pBuffer = azmalloc(pFileEntry->desc.lSizeCompressed); - pBufferDestroyer.Attach(pBuffer); // we want it auto-freed once we return - } - - if (fread((char*)pBuffer, pFileEntry->desc.lSizeCompressed, 1, m_pFile) != 1) - { - return ZD_ERROR_IO_FAILED; - } - - if (pFileEntry->nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT) - { - ZipDir::Decrypt((char*)pBuffer, pFileEntry->desc.lSizeCompressed, m_encryptionKey); - } - - // if there's a buffer for uncompressed data, uncompress it to that buffer - if (pUncompressed) - { - if (pFileEntry->nMethod == 0) - { - assert (pBuffer == pUncompressed); - //assert (pFileEntry->nSizeCompressed == pFileEntry->nSizeUncompressed); - //memcpy (pUncompressed, pBuffer, pFileEntry->nSizeCompressed); - } - else - { - unsigned long nSizeUncompressed = pFileEntry->desc.lSizeUncompressed; - if (nSizeUncompressed > 0) - { - if (Z_OK != ZipRawUncompress(pUncompressed, &nSizeUncompressed, pBuffer, pFileEntry->desc.lSizeCompressed)) - { - return ZD_ERROR_CORRUPTED_DATA; - } - } - } - } - - return ZD_ERROR_SUCCESS; -} - - -////////////////////////////////////////////////////////////////////////// -// finds the file by exact path -ZipDir::FileEntry* ZipDir::CacheRW::FindFile (const char* szPathSrc, [[maybe_unused]] bool bFullInfo) -{ - char str[_MAX_PATH]; - char* szPath = UnifyPath(str, szPathSrc); - - ZipDir::FindFileRW fd (GetRoot()); - if (!fd.FindExact(szPath)) - { - assert (!fd.GetFileEntry()); - return NULL; - } - assert (fd.GetFileEntry()); - return fd.GetFileEntry(); -} - -// returns the size of memory occupied by the instance referred to by this cache -size_t ZipDir::CacheRW::GetSize() const -{ - return sizeof(*this) + m_strFilePath.capacity() + m_treeDir.GetSize() - sizeof(m_treeDir); -} - -// returns the compressed size of all the entries -size_t ZipDir::CacheRW::GetCompressedSize() const -{ - return m_treeDir.GetCompressedFileSize(); -} - -// returns the total size of memory occupied by the instance of this cache and all the compressed files -size_t ZipDir::CacheRW::GetTotalFileSize() const -{ - return GetSize() + GetCompressedSize(); -} - -// returns the total size of space occupied on disk by the instance of this cache and all the compressed files -size_t ZipDir::CacheRW::GetTotalFileSizeOnDiskSoFar() -{ - FileRecordList arrFiles(GetRoot()); - FileRecordList::ZipStats statFiles = arrFiles.GetStats(); - - return m_lCDROffset + statFiles.nSizeCDR; -} - -// refreshes information about the given file entry into this file entry -ZipDir::ErrorEnum ZipDir::CacheRW::Refresh (FileEntry* pFileEntry) -{ - if (!pFileEntry) - { - return ZD_ERROR_INVALID_CALL; - } - - if (pFileEntry->nFileDataOffset != pFileEntry->INVALID_DATA_OFFSET) - { - return ZD_ERROR_SUCCESS; // the data offset has been successfully read.. - } - - return ZipDir::Refresh(m_pFile, pFileEntry, m_bEncryptedHeaders); -} - - -// writes the CDR to the disk -bool ZipDir::CacheRW::WriteCDR(FILE* fTarget, bool encryptCDR) -{ - if (!fTarget) - { - return false; - } - -#ifdef WIN32 - if (_fseeki64(fTarget, (__int64)m_lCDROffset, SEEK_SET)) -#else - if (fseek(fTarget, m_lCDROffset, SEEK_SET)) -#endif - { - return false; - } - - FileRecordList arrFiles(GetRoot()); - //arrFiles.SortByFileOffset(); - size_t nSizeCDR = arrFiles.GetStats().nSizeCDR; - void* pCDR = malloc(nSizeCDR); -#if !defined(NDEBUG) - size_t nSizeCDRSerialized = -#endif - arrFiles.MakeZipCDR(m_lCDROffset, pCDR, encryptCDR); - assert (nSizeCDRSerialized == nSizeCDR); - - if (encryptCDR) - { - // We do not encrypt CDREnd, so we could find it by signature - ZipDir::Encrypt((char*)pCDR, nSizeCDR - sizeof(ZipFile::CDREnd), m_encryptionKey); - } - - size_t nWriteRes = fwrite (pCDR, nSizeCDR, 1, fTarget); - free(pCDR); - return nWriteRes == 1; -} - -// generates random file name -string ZipDir::CacheRW::GetRandomName(int nAttempt) -{ - if (nAttempt) - { - char szBuf[8]; - int i; - for (i = 0; i < sizeof(szBuf) - 1; ++i) - { - int r = rand() % (10 + 'z' - 'a' + 1); - szBuf[i] = r > 9 ? (r - 10) + 'a' : '0' + r; - } - szBuf[i] = '\0'; - return szBuf; - } - else - { - return string(); - } -} - -bool ZipDir::CacheRW::RelinkZip() -{ - AZ::IO::LocalFileIO localFileIO; - for (int nAttempt = 0; nAttempt < 32; ++nAttempt) - { - string strNewFilePath = m_strFilePath + "$" + GetRandomName(nAttempt); - - FILE* f = nullptr; - azfopen(&f, strNewFilePath.c_str(), "wb"); - if (f) - { - bool bOk = RelinkZip(f); - fclose (f); // we don't need the temporary file handle anyway - - if (!bOk) - { - // we don't need the temporary file - localFileIO.Remove(strNewFilePath.c_str()); - return false; - } - - // we successfully relinked, now copy the temporary file to the original file - fclose (m_pFile); - m_pFile = NULL; - - localFileIO.Remove(m_strFilePath.c_str()); - if (localFileIO.Rename(strNewFilePath.c_str(), m_strFilePath.c_str()) == 0) - { - // successfully renamed - reopen - m_pFile = nullptr; - azfopen(&m_pFile, m_strFilePath.c_str(), "r+b"); - return m_pFile == NULL; - } - else - { - // could not rename - - //m_pFile = fopen (strNewFilePath.c_str(), "r+b"); - return false; - } - } - } - - // couldn't open temp file - return false; -} - -bool ZipDir::CacheRW::RelinkZip(FILE* fTmp) -{ - FileRecordList arrFiles(GetRoot()); - arrFiles.SortByFileOffset(); - FileRecordList::ZipStats Stats = arrFiles.GetStats(); - - // we back up our file entries, because we'll need to restore them - // in case the operation fails - std::vector arrFileEntryBackup; - arrFiles.Backup (arrFileEntryBackup); - - // this is the set of files that are to be written out - compressed data and the file record iterator - std::vector queFiles; - queFiles.reserve (g_nMaxItemsRelinkBuffer); - - // the total size of data in the queue - unsigned nQueueSize = 0; - - for (FileRecordList::iterator it = arrFiles.begin(); it != arrFiles.end(); ++it) - { - FileEntry* entry = it->pFileEntry; - // find the file data offset - if (ZD_ERROR_SUCCESS != Refresh(entry)) - { - return false; - } - - // go to the file data -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)entry->nFileDataOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, entry->nFileDataOffset, SEEK_SET) != 0) -#endif - { - return false; - } - - // allocate memory for the file compressed data - FileDataRecordPtr pFile = FileDataRecord::New (*it); - - if (!pFile) - { - return false; - } - - // read the compressed data - if (entry->desc.lSizeCompressed && fread (pFile->GetData(), entry->desc.lSizeCompressed, 1, m_pFile) != 1) - { - return false; - } - - if (entry->nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT) - { - ZipDir::Decrypt((char*)pFile->GetData(), entry->desc.lSizeCompressed, m_encryptionKey); - } - - // put the file into the queue for copying (writing) - queFiles.push_back(pFile); - nQueueSize += entry->desc.lSizeCompressed; - - // if the queue is big enough, write it out - if (nQueueSize > g_nSizeRelinkBuffer || queFiles.size() >= g_nMaxItemsRelinkBuffer) - { - nQueueSize = 0; - if (!WriteZipFiles(queFiles, fTmp)) - { - return false; - } - } - } - - if (!WriteZipFiles(queFiles, fTmp)) - { - return false; - } - - ZipFile::ulong lOldCDROffset = m_lCDROffset; - // the file data has now been written out. Now write the CDR -#ifdef WIN32 - m_lCDROffset = (ZipFile::ulong)_ftelli64(fTmp); -#else - m_lCDROffset = ftell(fTmp); -#endif - if (m_lCDROffset >= 0 && WriteCDR(fTmp, m_bHeadersEncryptedOnClose) && 0 == fflush (fTmp)) - { - // the new file positions are already there - just discard the backup and return - return true; - } - // recover from backup - arrFiles.Restore (arrFileEntryBackup); - m_lCDROffset = lOldCDROffset; - m_bEncryptedHeaders = m_bHeadersEncryptedOnClose; - return false; -} - -// writes out the file data in the queue into the given file. Empties the queue -bool ZipDir::CacheRW::WriteZipFiles(std::vector& queFiles, FILE* fTmp) -{ - for (std::vector::iterator it = queFiles.begin(); it != queFiles.end(); ++it) - { - // set the new header offset to the file entry - we won't need it -#ifdef WIN32 - const unsigned long currentPos = (unsigned long)_ftelli64 (fTmp); -#else - const unsigned long currentPos = ftell (fTmp); -#endif - (*it)->pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset((*it)->strPath.c_str(), currentPos, m_fileAlignment); - - // while writing the local header, the data offset will also be calculated - if (ZD_ERROR_SUCCESS != WriteLocalHeader(fTmp, (*it)->pFileEntry, (*it)->strPath.c_str(), m_bHeadersEncryptedOnClose)) - { - return false; - } - ; - - // write the compressed file data - const bool encrypt = (*it)->pFileEntry->nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT; - if (!WriteCompressedData((char*)(*it)->GetData(), (*it)->pFileEntry->desc.lSizeCompressed, encrypt, fTmp)) - { - return false; - } - -#ifdef WIN32 - assert ((*it)->pFileEntry->nEOFOffset == (unsigned long)_ftelli64 (fTmp)); -#else - assert ((*it)->pFileEntry->nEOFOffset == ftell (fTmp)); -#endif - } - queFiles.clear(); - queFiles.reserve (g_nMaxItemsRelinkBuffer); - return true; -} - -void TruncateFile(FILE* file, size_t newLength) -{ -#if defined(AZ_PLATFORM_WINDOWS) - int filedes = _fileno(file); - _chsize_s(filedes, newLength); -#elif AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX) - ftruncate(fileno(file), newLength); -#else -#error Not implemented! -#endif -} - -bool ZipDir::CacheRW::EncryptArchive(EncryptionChange change, IEncryptPredicate* encryptContentPredicate, int* numChanged, int* numSkipped) -{ - FileRecordList arrFiles(GetRoot()); - arrFiles.SortByFileOffset(); - - size_t unusedSpace = 0; - size_t lastDataEnd = 0; - - for (FileRecordList::iterator it = arrFiles.begin(); it != arrFiles.end(); ++it) - { - FileEntry* entry = it->pFileEntry; - - if (entry->nFileHeaderOffset > lastDataEnd) - { - fseek(m_pFile, lastDataEnd, SEEK_SET); - size_t gapLength = entry->nFileHeaderOffset - lastDataEnd; - unusedSpace += gapLength; - if (change == ENCRYPT) - { - if (!WriteRandomData(m_pFile, gapLength)) - { - return false; - } - } - else - { - if (!WriteNullData(gapLength)) - { - return false; - } - } - } - lastDataEnd = entry->nEOFOffset; - - if (numSkipped) - { - ++(*numSkipped); - } - - // find the file data offset - if (ZD_ERROR_SUCCESS != Refresh (entry)) - { - return false; - } - - ZipFile::ushort oldMethod = entry->nMethod; - ZipFile::ushort newMethod = oldMethod; - if (change == ENCRYPT) - { - if (entry->nMethod == ZipFile::METHOD_DEFLATE) - { - newMethod = ZipFile::METHOD_DEFLATE_AND_ENCRYPT; - } - } - else - { - if (entry->nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT) - { - newMethod = ZipFile::METHOD_DEFLATE; - } - } - - // allow encryption only for matching files - if (newMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT && - (!encryptContentPredicate || !encryptContentPredicate->Match(it->strPath.c_str()))) - { - newMethod = ZipFile::METHOD_DEFLATE; - } - - entry->nMethod = newMethod; - - const bool encryptHeaders = change == ENCRYPT; - // encryption is toggled or compression method changed... - if (newMethod != oldMethod || encryptHeaders != m_bEncryptedHeaders) - { - // ... update header - if (ZipDir::WriteLocalHeader(m_pFile, entry, it->strPath.c_str(), encryptHeaders) != ZD_ERROR_SUCCESS) - { - return false; - } - } - - if (newMethod == oldMethod) - { - // no need to update file content - continue; - } - - // go to the file data -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)entry->nFileDataOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, entry->nFileDataOffset, SEEK_SET) != 0) -#endif - { - return false; - } - - // allocate memory for the file compressed data - FileDataRecordPtr pFile = FileDataRecord::New(*it); - if (!pFile) - { - return false; - } - - // read the compressed data - if (entry->desc.lSizeCompressed && fread (pFile->GetData(), entry->desc.lSizeCompressed, 1, m_pFile) != 1) - { - return false; - } - - if (oldMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT) - { - ZipDir::Decrypt((char*)pFile->GetData(), entry->desc.lSizeCompressed, m_encryptionKey); - } - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)entry->nFileDataOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, entry->nFileDataOffset, SEEK_SET) != 0) -#endif - { - return false; - } - - const bool encryptContent = newMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT; - if (!WriteCompressedData((const char*)pFile->GetData(), entry->desc.lSizeCompressed, encryptContent, m_pFile)) - { - return false; - } - - if (numSkipped) - { - --(*numSkipped); - } - if (numChanged) - { - ++(*numChanged); - } - } - - m_bEncryptedHeaders = change == ENCRYPT; - m_bHeadersEncryptedOnClose = m_bEncryptedHeaders; - - if (!WriteCDR(m_pFile, m_bEncryptedHeaders)) - { - return false; - } - - if (fflush (m_pFile) != 0) - { - return false; - } - - size_t endOfCDR = (size_t)ftell(m_pFile); - - fseek(m_pFile, 0, SEEK_END); - size_t fileSize = (size_t)ftell(m_pFile); - - if (fileSize != endOfCDR) - { - TruncateFile(m_pFile, endOfCDR); - } - - fclose(m_pFile); - m_pFile = 0; - m_treeDir.Clear(); - return true; -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.h deleted file mode 100644 index 6c02d34bf3..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.h +++ /dev/null @@ -1,283 +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. - -////////////////////////////////////////////////////////////////////////// -// Declaration of the class that will keep the ZipDir Cache object -// and will provide all its services to access Zip file, plus it will -// provide services to write to the zip file efficiently -// Time to time, the contained Cache object will be recreated during -// an archive add operation - -#pragma once - -#include "SimpleStringPool.h" -#include "StringUtils.h" - -struct PackFileJob; -namespace ZipDir -{ - struct FileDataRecord; - TYPEDEF_AUTOPTR(FileDataRecord); - typedef FileDataRecord_AutoPtr FileDataRecordPtr; - - static constexpr int TARGET_MIN_TEST_COMPRESS_BYTES = 128 * 1024; - - struct IReporter - { - virtual void ReportAdded(const char* filename) = 0; - virtual void ReportMissing(const char* filename) = 0; - virtual void ReportUpToDate(const char* filename) = 0; - virtual void ReportSkipped(const char* filename) = 0; - virtual void ReportFailed(const char* filename, const char* error) = 0; - virtual void ReportSpeed(double bytesPerSecond) = 0; - }; - - struct ISplitter - { - // Arguments: - // total - the current size of the pak - // add - the size of the file to add - // sub - the size of the old version of the file which will be removed from the pak - // Return: - // true if adding the current file to the current pak is still permitted. - virtual bool CheckWriteLimit(size_t total, size_t add, size_t sub) const = 0; - - // Arguments: - // total - the current size of the pak - // add - the size of the file to add - // sub - the size of the old version of the file which will be removed from the pak - // offset - the position of the first file which has not been added to the pak - // in the array passed to "UpdateMultipleFiles()" - virtual void SetLastFile(size_t total, size_t add, size_t sub, int offset) = 0; - }; - - struct IEncryptPredicate - { - virtual ~IEncryptPredicate() = default; - virtual bool Match(const char* filename) = 0; - }; - - class CacheRW - { - public: - enum EncryptionChange - { - ENCRYPT, - DECRYPT - }; - // the size of the buffer that's using during re-linking the zip file - enum - { - g_nSizeRelinkBuffer = 128 * 1024 * 1024, // 128 Mbytes - g_nMaxItemsRelinkBuffer = 1024 // max number of files to read before (without) writing - }; - - void AddRef(); - void Release(); - - - CacheRW(bool encryptHeaders, const EncryptionKey& encryptionKey); - ~CacheRW(); - - bool IsValid () const - { - return m_pFile != NULL; - } - - static char* UnifyPath(char* const str, const char* pPath); - static char* ToUnixPath(char* const str, const char* pPath); - char* AllocPath(const char* pPath); - - // opens the given zip file and connects to it. Creates a new file if no such file exists - // if successful, returns true. - //ErrorEnum Open (CMTSafeHeap* pHeap, InitMethodEnum nInitMethod, unsigned nFlags, const char* szFile); - - // Adds a new file to the zip or update an existing one - // adds a directory (creates several nested directories if needed) - ErrorEnum UpdateFile(const char* szRelativePath, void* pUncompressed, unsigned nSize, unsigned nCompressionMethod, int nCompressionLevel, int64 modTime); - - // Sets if Archive should be encrypted or decrypted on close. - bool EncryptArchive(EncryptionChange change, IEncryptPredicate* encryptContentPredicate, int* numChanged, int* numSkipped); - - // Adds or updates a bunch of files. Creates directories if needed. Multithreaded when numExtraThreads > 0 - bool UpdateMultipleFiles(const char** realFilenames, const char** filenamesInZip, size_t fileCount, - int compressionLevel, bool encryptContent, size_t zipMaxSize, int sourceMinSize, int sourceMaxSize, - unsigned numExtraThreads, ZipDir::IReporter* reporter, ZipDir::ISplitter* splitter = nullptr, bool useFastestDecompressionCodec = false); - - // Adds a new file to the zip or update an existing one if it is not compressed - just stored - start a big file - ErrorEnum StartContinuousFileUpdate(const char* szRelativePath, unsigned nSize); - - // Adds a new file to the zip or update an existing's segment if it is not compressed - just stored - // adds a directory (creates several nested directories if needed) - // Arguments: - // nOverwriteSeekPos - 0xffffffff means the seek pos should not be overwritten - ErrorEnum UpdateFileContinuousSegment (const char* szRelativePath, unsigned nSize, void* pUncompressed, unsigned nSegmentSize, unsigned nOverwriteSeekPos); - - ErrorEnum UpdateFileCRC(const char* szRelativePath, unsigned dwCRC32); - - // deletes the file from the archive - ErrorEnum RemoveFile(const char* szRelativePath); - - // deletes the directory, with all its descendants (files and subdirs) - ErrorEnum RemoveDir(const char* szRelativePath); - - // deletes all files and directories in this archive - ErrorEnum RemoveAll(); - - // closes the current zip file - void Close(); - - FileEntry* FindFile(const char* szPath, bool bFullInfo = false); - - ErrorEnum ReadFile(FileEntry* pFileEntry, void* pCompressed, void* pUncompressed); - - void* AllocAndReadFile (FileEntry* pFileEntry); - - void Free (void* p) - { - free(p); - } - - // refreshes information about the given file entry into this file entry - ErrorEnum Refresh (FileEntry* pFileEntry); - - // returns the size of memory occupied by the instance of this cache - size_t GetSize() const; - - // returns the compressed size of all the entries - size_t GetCompressedSize() const; - - // returns the total size of memory occupied by the instance of this cache and all the compressed files - size_t GetTotalFileSize() const; - - // returns the total size of space occupied on disk by the instance of this cache and all the compressed files - size_t GetTotalFileSizeOnDiskSoFar(); - - // QUICK check to determine whether the file entry belongs to this object - bool IsOwnerOf (const FileEntry* pFileEntry) const - { - return m_treeDir.IsOwnerOf(pFileEntry); - } - - // returns the string - path to the zip file from which this object was constructed. - // this will be "" if the object was constructed with a factory that wasn't created with FLAGS_MEMORIZE_ZIP_PATH - const char* GetFilePath() const - { - return m_strFilePath.c_str(); - } - - FileEntryTree* GetRoot() - { - return &m_treeDir; - } - - const FileEntryTree* GetRoot() const - { - return &m_treeDir; - } - - // writes the CDR to the disk - bool WriteCDR() {return WriteCDR(m_pFile, m_bEncryptedHeaders); } - bool WriteCDR(FILE* fTarget, bool encryptHeaders); - - bool RelinkZip(); - protected: - bool RelinkZip(FILE* fTmp); - // writes out the file data in the queue into the given file. Empties the queue - bool WriteZipFiles(std::vector& queFiles, FILE* fTmp); - // generates random file name - string GetRandomName(int nAttempt); - - bool ReadCompressedData(char* data, size_t size); - bool WriteCompressedData(const char* data, size_t size, bool encrypt, FILE* file); - bool WriteNullData(size_t size); - - void StorePackedFile(PackFileJob* job); - protected: - - friend class CacheFactory; - volatile signed int m_nRefCount; // the reference count - FileEntryTree m_treeDir; - FILE* m_pFile; - string m_strFilePath; - - // offset to the start of CDR in the file,even if there's no CDR there currently - // when a new file is added, it can start from here, but this value will need to be updated then - ZipFile::ulong m_lCDROffset; - - CSimpleStringPool m_tempStringPool; - - enum - { - // if this is set, the file needs to be compacted before it can be used by - // all standard zip tools, because gaps between file datas can be present - FLAGS_UNCOMPACTED = 1 << 0, - // if this is set, the CDR needs to be written to the file - FLAGS_CDR_DIRTY = 1 << 1, - // if this is set, the file is opened in read-only mode. no write operations are to be performed - FLAGS_READ_ONLY = 1 << 2, - // when this is set, compact operation is not performed - FLAGS_DONT_COMPACT = 1 << 3 - }; - unsigned m_nFlags; - size_t m_fileAlignment; - - // CDR buffer. - DynArray m_CDR_buffer; - // unified names buffer - DynArray m_unifiedNameBuffer; - - EncryptionKey m_encryptionKey; - bool m_bEncryptedHeaders; - bool m_bHeadersEncryptedOnClose; - }; - - TYPEDEF_AUTOPTR(CacheRW); - typedef CacheRW_AutoPtr CacheRWPtr; - - // creates and if needed automatically destroys the file entry - class FileEntryTransactionAdd - { - class CacheRW* m_pCache; - char m_szPath[_MAX_PATH]; - FileEntry* m_pFileEntry; - bool m_bComitted; - public: - operator FileEntry* () { - return m_pFileEntry; - } - operator bool() const{ - return m_pFileEntry != NULL; - } - FileEntry* operator -> () {return m_pFileEntry; } - FileEntryTransactionAdd(class CacheRW* pCache, char* szPath, char* szUnifiedPath) - : m_pCache(pCache) - , m_bComitted (false) - { - // we need to copy path, because original one will be destroyed by FileEntryTree::Add call - cry_strcpy(m_szPath, szUnifiedPath); - m_pFileEntry = m_pCache->GetRoot()->Add(szPath, szUnifiedPath); - } - ~FileEntryTransactionAdd() - { - if (m_pFileEntry && !m_bComitted) - { - m_pCache->RemoveFile(m_szPath); - } - } - void Commit() - { - m_bComitted = true; - } - }; -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.cpp deleted file mode 100644 index c62428f0b1..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.cpp +++ /dev/null @@ -1,246 +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 "smartptr.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirCache.h" -#include "ZipDirFind.h" -#include "StringHelpers.h" - -bool ZipDir::FindFile::FindFirst (const char* szWildcard) -{ - if (!PreFind (szWildcard)) - { - return false; - } - - // finally, this is the name of the file - m_nFileEntry = 0; - return SkipNonMatchingFiles(); -} - -bool ZipDir::FindDir::FindFirst (const char* szWildcard) -{ - if (!PreFind (szWildcard)) - { - return false; - } - - // finally, this is the name of the file - m_nDirEntry = 0; - return SkipNonMatchingDirs(); -} - -// matches the file wilcard in the m_szWildcard to the given file/dir name -// this takes into account the fact that xxx. is the alias name for xxx -bool ZipDir::FindData::MatchWildcard(const char* szName) -{ - if (StringHelpers::MatchesWildcards(szName, m_szWildcard)) - { - return true; - } - - // check if the file object name contains extension sign (.) - const char* p; - for (p = szName; *p && *p != '.'; ++p) - { - continue; - } - - if (*p) - { - // there's an extension sign in the object, but it wasn't matched.. - assert (*p == '.'); - return false; - } - - // no extension sign - add it - char szAlias[_MAX_PATH + 2]; - size_t nLength = p - szName; - if (nLength > _MAX_PATH) - { - nLength = _MAX_PATH; - } - memcpy (szAlias, szName, nLength); - szAlias[nLength] = '.'; // add the alias - szAlias[nLength + 1] = '\0'; // terminate the string - return StringHelpers::MatchesWildcards(szAlias, m_szWildcard); -} - - -ZipDir::FileEntry* ZipDir::FindFile::FindExact (const char* szPath) -{ - if (!PreFind (szPath)) - { - return NULL; - } - - FileEntry* pFileEntry = m_pDirHeader->FindFileEntry(m_szWildcard); - if (pFileEntry) - { - m_nFileEntry = (unsigned)(pFileEntry - m_pDirHeader->GetFileEntry(0)); - } - else - { - m_pDirHeader = NULL; // we didn't find it, fail the search - } - return pFileEntry; -} - -////////////////////////////////////////////////////////////////////////// -// after this call returns successfully (with true returned), the m_szWildcard -// contains the file name/wildcard and m_pDirHeader contains the directory where -// the file (s) are to be found -bool ZipDir::FindData::PreFind (const char* szWildcard) -{ - if (!m_pRoot) - { - return false; - } - - // start the search from the root - m_pDirHeader = m_pRoot; - - // for each path dir name, copy it into the buffer and try to find the subdirectory - const char* pPath = szWildcard; - for (;; ) - { - char* pName = m_szWildcard; - - // at first we'll use the wildcard memory to save the directory names - for (; *pPath && *pPath != '/' && *pPath != '\\' && pName < m_szWildcard + sizeof(m_szWildcard) - 1; ++pPath, ++pName) - { - *pName = ::tolower(*pPath); - } - *pName = '\0'; - - if (*pPath) - { - if (*pPath != '/' && *pPath != '\\') - { - return false;//ZD_ERROR_NAME_TOO_LONG; - } - // this is the name of the directory - DirEntry* pDirEntry = m_pDirHeader->FindSubdirEntry(m_szWildcard); - if (!pDirEntry) - { - m_pDirHeader = NULL; // finish the search - return false; - } - m_pDirHeader = pDirEntry->GetDirectory(); - ++pPath; - assert(m_pDirHeader); - } - else - { - // finally, this is the name of the file (or directory) - return true; - } - } -} - -// goes on to the next entry -bool ZipDir::FindFile::FindNext () -{ - if (m_pDirHeader && m_nFileEntry < m_pDirHeader->numFiles) - { - ++m_nFileEntry; - return SkipNonMatchingFiles(); - } - else - { - return false; - } -} - -// goes on to the next entry -bool ZipDir::FindDir::FindNext () -{ - if (m_pDirHeader && m_nDirEntry < m_pDirHeader->numDirs) - { - ++m_nDirEntry; - return SkipNonMatchingDirs(); - } - else - { - return false; - } -} - -bool ZipDir::FindFile::SkipNonMatchingFiles() -{ - assert(m_pDirHeader && m_nFileEntry <= m_pDirHeader->numFiles); - - for (; m_nFileEntry < m_pDirHeader->numFiles; ++m_nFileEntry) - { - if (MatchWildcard(GetFileName())) - { - return true; - } - } - // we didn't find anything other file else - return false; -} - -bool ZipDir::FindDir::SkipNonMatchingDirs() -{ - assert(m_pDirHeader && m_nDirEntry <= m_pDirHeader->numDirs); - - for (; m_nDirEntry < m_pDirHeader->numDirs; ++m_nDirEntry) - { - if (MatchWildcard(GetDirName())) - { - return true; - } - } - // we didn't find anything other file else - return false; -} - - -ZipDir::FileEntry* ZipDir::FindFile::GetFileEntry() -{ - return m_pDirHeader && m_nFileEntry < m_pDirHeader->numFiles ? m_pDirHeader->GetFileEntry(m_nFileEntry) : NULL; -} -ZipDir::DirEntry* ZipDir::FindDir::GetDirEntry() -{ - return m_pDirHeader && m_nDirEntry < m_pDirHeader->numDirs ? m_pDirHeader->GetSubdirEntry(m_nDirEntry) : NULL; -} - -const char* ZipDir::FindFile::GetFileName () -{ - if (m_pDirHeader && m_nFileEntry < m_pDirHeader->numFiles) - { - const char* pNamePool = m_pDirHeader->GetNamePool(); - return m_pDirHeader->GetFileEntry(m_nFileEntry)->GetName(pNamePool); - } - else - { - return ""; // default name - } -} - -const char* ZipDir::FindDir::GetDirName () -{ - if (m_pDirHeader && m_nDirEntry < m_pDirHeader->numDirs) - { - const char* pNamePool = m_pDirHeader->GetNamePool(); - return m_pDirHeader->GetSubdirEntry(m_nDirEntry)->GetName(pNamePool); - } - else - { - return ""; // default name - } -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.h deleted file mode 100644 index 99e95607c1..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.h +++ /dev/null @@ -1,109 +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_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFIND_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFIND_H -#pragma once - - -namespace ZipDir -{ - // create this structure and loop: - // FindData fd (pZip); - // for (fd.FindFirst("*.cgf"); fd.GetFileEntry(); fd.FindNext()) - // {} // inside the loop, use GetFileEntry() and GetFileName() to get the file entry and name records - class FindData - { - public: - - FindData (DirHeader* pRoot) - : m_pRoot (pRoot) - , m_pDirHeader (NULL) - { - } - - protected: - // initializes everything until the point where the file must be searched for - // after this call returns successfully (with true returned), the m_szWildcard - // contains the file name/wildcard and m_pDirHeader contains the directory where - // the file (s) are to be found - bool PreFind (const char* szWildcard); - - // matches the file wilcard in the m_szWildcard to the given file/dir name - // this takes into account the fact that xxx. is the alias name for xxx - bool MatchWildcard(const char* szName); - - DirHeader* m_pRoot; // the zip file inwhich the search is performed - DirHeader* m_pDirHeader; // the header of the directory in which the files reside - //unsigned m_nDirEntry; // the current directory entry inside the parent directory - - // the actual wildcard being used in the current scan - the file name wildcard only! - char m_szWildcard[_MAX_PATH]; - }; - - class FindFile - : public FindData - { - public: - FindFile (Cache* pCache) - : FindData(pCache->GetRoot()) - { - } - FindFile (DirHeader* pRoot) - : FindData(pRoot) - { - } - // if bExactFile is passed, only the file is searched, and besides with the exact name as passed (no wildcards) - bool FindFirst (const char* szWildcard); - - FileEntry* FindExact (const char* szPath); - - // goes on to the next file entry - bool FindNext (); - - FileEntry* GetFileEntry(); - const char* GetFileName (); - - protected: - bool SkipNonMatchingFiles(); - unsigned m_nFileEntry; // the current file index inside the parent directory - }; - - class FindDir - : public FindData - { - public: - FindDir (Cache* pCache) - : FindData(pCache->GetRoot()) - { - } - FindDir (DirHeader* pRoot) - : FindData(pRoot) - { - } - // if bExactFile is passed, only the file is searched, and besides with the exact name as passed (no wildcards) - bool FindFirst (const char* szWildcard); - - // goes on to the next file entry - bool FindNext (); - - DirEntry* GetDirEntry(); - const char* GetDirName (); - - protected: - bool SkipNonMatchingDirs(); - unsigned m_nDirEntry; // the current dir index inside the parent directory - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFIND_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.cpp deleted file mode 100644 index a44f8dd45e..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.cpp +++ /dev/null @@ -1,253 +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 "smartptr.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirTree.h" -#include "ZipDirCacheRW.h" -#include "ZipDirFindRW.h" -#include "StringHelpers.h" - -bool ZipDir::FindFileRW::FindFirst (const char* szWildcard) -{ - if (!PreFind (szWildcard)) - { - return false; - } - - // finally, this is the name of the file - m_itFile = m_pDirHeader->GetFileBegin(); - return SkipNonMatchingFiles(); -} - -bool ZipDir::FindDirRW::FindFirst (const char* szWildcard) -{ - if (!PreFind (szWildcard)) - { - return false; - } - - // finally, this is the name of the file - m_itDir = m_pDirHeader->GetDirBegin(); - return SkipNonMatchingDirs(); -} - -// matches the file wilcard in the m_szWildcard to the given file/dir name -// this takes into account the fact that xxx. is the alias name for xxx -bool ZipDir::FindDataRW::MatchWildcard(const char* szName) -{ - if (StringHelpers::MatchesWildcards(szName, m_szWildcard)) - { - return true; - } - - // check if the file object name contains extension sign (.) - const char* p; - for (p = szName; *p && *p != '.'; ++p) - { - continue; - } - - if (*p) - { - // there's an extension sign in the object, but it wasn't matched.. - assert (*p == '.'); - return false; - } - - // no extension sign - add it - char szAlias[_MAX_PATH + 2]; - size_t nLength = p - szName; - if (nLength > _MAX_PATH) - { - nLength = _MAX_PATH; - } - memcpy (szAlias, szName, nLength); - szAlias[nLength] = '.'; // add the alias - szAlias[nLength + 1] = '\0'; // terminate the string - return StringHelpers::MatchesWildcards(szAlias, m_szWildcard); -} - - -ZipDir::FileEntry* ZipDir::FindFileRW::FindExact (const char* szPath) -{ - if (!PreFind (szPath)) - { - return NULL; - } - - FileEntryTree::FileMap::iterator itFile = m_pDirHeader->FindFile(m_szWildcard); - if (itFile != m_pDirHeader->GetFileEnd()) - { - m_itFile = itFile; - } - else - { - m_pDirHeader = NULL; // we didn't find it, fail the search - } - return m_pDirHeader ? m_pDirHeader->GetFileEntry(itFile) : NULL; -} - -ZipDir::FileEntryTree* ZipDir::FindDirRW::FindExact (const char* szPath) -{ - if (!PreFind(szPath)) - { - return NULL; - } - - // the wildcard will contain the target directory name - return m_pDirHeader->FindDir(m_szWildcard); -} - -////////////////////////////////////////////////////////////////////////// -// initializes everything until the point where the file must be searched for -// after this call returns successfully (with true returned), the m_szWildcard -// contains the file name/wildcard and m_pDirHeader contains the directory where -// the file (s) are to be found -bool ZipDir::FindDataRW::PreFind (const char* szWildcard) -{ - if (!m_pRoot) - { - return false; - } - - // start the search from the root - m_pDirHeader = m_pRoot; - - // for each path dir name, copy it into the buffer and try to find the subdirectory - const char* pPath = szWildcard; - for (;; ) - { - char* pName = m_szWildcard; - - // at first we'll use the wildcard memory to save the directory names - for (; *pPath && *pPath != '/' && *pPath != '\\' && pName < m_szWildcard + sizeof(m_szWildcard) - 1; ++pPath, ++pName) - { - *pName = ::tolower(*pPath); - } - *pName = '\0'; - - if (*pPath) - { - // this is the name of the directory - FileEntryTree* pDirEntry = m_pDirHeader->FindDir(m_szWildcard); - if (!pDirEntry) - { - m_pDirHeader = NULL; // finish the search - return false; - } - m_pDirHeader = pDirEntry->GetDirectory(); - ++pPath; - assert(m_pDirHeader); - } - else - { - // finally, this is the name of the file (or directory) - return true; - } - } -} - -// goes on to the next entry -bool ZipDir::FindFileRW::FindNext () -{ - if (m_pDirHeader && m_itFile != m_pDirHeader->GetFileEnd()) - { - ++m_itFile; - return SkipNonMatchingFiles(); - } - else - { - return false; - } -} - -// goes on to the next entry -bool ZipDir::FindDirRW::FindNext () -{ - if (m_pDirHeader && m_itDir != m_pDirHeader->GetDirEnd()) - { - ++m_itDir; - return SkipNonMatchingDirs(); - } - else - { - return false; - } -} - -bool ZipDir::FindFileRW::SkipNonMatchingFiles() -{ - assert(m_pDirHeader); - - for (; m_itFile != m_pDirHeader->GetFileEnd(); ++m_itFile) - { - if (MatchWildcard(GetFileName())) - { - return true; - } - } - // we didn't find anything other file else - return false; -} - -bool ZipDir::FindDirRW::SkipNonMatchingDirs() -{ - assert(m_pDirHeader); - - for (; m_itDir != m_pDirHeader->GetDirEnd(); ++m_itDir) - { - if (MatchWildcard(GetDirName())) - { - return true; - } - } - // we didn't find anything other file else - return false; -} - - -ZipDir::FileEntry* ZipDir::FindFileRW::GetFileEntry() -{ - return m_pDirHeader && m_itFile != m_pDirHeader->GetFileEnd() ? m_pDirHeader->GetFileEntry(m_itFile) : NULL; -} -ZipDir::FileEntryTree* ZipDir::FindDirRW::GetDirEntry() -{ - return m_pDirHeader && m_itDir != m_pDirHeader->GetDirEnd() ? m_pDirHeader->GetDirEntry(m_itDir) : NULL; -} - -const char* ZipDir::FindFileRW::GetFileName () -{ - if (m_pDirHeader && m_itFile != m_pDirHeader->GetFileEnd()) - { - return m_pDirHeader->GetFileName(m_itFile); - } - else - { - return ""; // default name - } -} - -const char* ZipDir::FindDirRW::GetDirName () -{ - if (m_pDirHeader && m_itDir != m_pDirHeader->GetDirEnd()) - { - return m_pDirHeader->GetDirName(m_itDir); - } - else - { - return ""; // default name - } -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.h deleted file mode 100644 index 3085b5f8ba..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.h +++ /dev/null @@ -1,110 +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 the class that can be used to search for the entries -// in a zip dir cache - - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFINDRW_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFINDRW_H -#pragma once - - -namespace ZipDir -{ - // create this structure and loop: - // FindData fd (pZip); - // for (fd.FindFirst("*.cgf"); fd.GetFileEntry(); fd.FindNext()) - // {} // inside the loop, use GetFileEntry() and GetFileName() to get the file entry and name records - class FindDataRW - { - public: - FindDataRW (FileEntryTree* pRoot) - : m_pRoot (pRoot) - , m_pDirHeader (NULL) - { - } - - // returns the directory to which the current object belongs - FileEntryTree* GetParentDir() {return m_pDirHeader; } - protected: - // initializes everything until the point where the file must be searched for - // after this call returns successfully (with true returned), the m_szWildcard - // contains the file name/wildcard and m_pDirHeader contains the directory where - // the file (s) are to be found - bool PreFind (const char* szWildcard); - - // matches the file wilcard in the m_szWildcard to the given file/dir name - // this takes into account the fact that xxx. is the alias name for xxx - bool MatchWildcard(const char* szName); - - // the directory inside which the current object (file or directory) is being searched - FileEntryTree* m_pDirHeader; - - FileEntryTree* m_pRoot; // the root of the zip file in which to search - - // the actual wildcard being used in the current scan - the file name wildcard only! - char m_szWildcard[_MAX_PATH]; - }; - - - class FindFileRW - : public FindDataRW - { - public: - FindFileRW (FileEntryTree* pRoot) - : FindDataRW(pRoot) - { - } - // if bExactFile is passed, only the file is searched, and besides with the exact name as passed (no wildcards) - bool FindFirst (const char* szWildcard); - - FileEntry* FindExact (const char* szPath); - - // goes on to the next file entry - bool FindNext (); - - FileEntry* GetFileEntry(); - const char* GetFileName (); - - protected: - bool SkipNonMatchingFiles(); - FileEntryTree::FileMap::iterator m_itFile; // the current file iterator inside the parent directory - }; - - class FindDirRW - : public FindDataRW - { - public: - FindDirRW (FileEntryTree* pRoot) - : FindDataRW(pRoot) - { - } - // if bExactFile is passed, only the file is searched, and besides with the exact name as passed (no wildcards) - bool FindFirst (const char* szWildcard); - - FileEntryTree* FindExact (const char* szPath); - - // goes on to the next file entry - bool FindNext (); - - FileEntryTree* GetDirEntry(); - const char* GetDirName (); - - protected: - bool SkipNonMatchingDirs(); - FileEntryTree::SubdirMap::iterator m_itDir; // the current dir index inside the parent directory - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFINDRW_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirList.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirList.cpp deleted file mode 100644 index 36b0dd6ba8..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirList.cpp +++ /dev/null @@ -1,174 +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. - - -#undef max -#include -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirList.h" -#include "ZipDirTree.h" - -ZipDir::FileRecordList::FileRecordList(FileEntryTree* pTree) -{ - clear(); - reserve(pTree->NumFilesTotal()); - AddAllFiles(pTree); -} - -//recursively adds the files from this directory and subdirectories -// the strRoot contains the trailing slash -void ZipDir::FileRecordList::AddAllFiles(FileEntryTree* pTree, string strRoot) -{ - for (FileEntryTree::SubdirMap::iterator it = pTree->GetDirBegin(); it != pTree->GetDirEnd(); ++it) - { - AddAllFiles (it->second, strRoot + it->second->GetOriginalName() + "/"); - } - - for (FileEntryTree::FileMap::iterator it = pTree->GetFileBegin(); it != pTree->GetFileEnd(); ++it) - { - FileRecord rec; - rec.pFileEntry = pTree->GetFileEntry(it); - const char* filename = rec.pFileEntry->szOriginalFileName ? rec.pFileEntry->szOriginalFileName : it->first; - rec.strPath = strRoot + filename; - push_back(rec); - } -} - - -// sorts the files by the physical offset in the zip file -void ZipDir::FileRecordList::SortByFileOffset() -{ - std::sort (begin(), end(), FileRecordFileOffsetOrder()); -} - -// returns the size of CDR in the zip file -ZipDir::FileRecordList::ZipStats ZipDir::FileRecordList::GetStats() const -{ - ZipStats Stats; - Stats.nSizeCDR = sizeof(ZipFile::CDREnd); - Stats.nSizeCompactData = 0; - // for each file, we'll need to store only its CDR header and the name - for (const_iterator it = begin(); it != end(); ++it) - { - Stats.nSizeCDR += sizeof(ZipFile::CDRFileHeader) + it->strPath.length(); - Stats.nSizeCompactData += sizeof(ZipFile::LocalFileHeader) + it->strPath.length() + it->pFileEntry->desc.lSizeCompressed; - } - - return Stats; -} - -// puts the CDR into the given block of mem -size_t ZipDir::FileRecordList::MakeZipCDR(ZipFile::ulong lCDROffset, void* pBuffer, bool encryptedFlag) const -{ - const ZipFile::ushort nBaseVersion = std::max(encryptedFlag ? ZipFile::VERSION_ENCRYPTION_PKWARE : ZipFile::VERSION_DEFAULT, ZipFile::VERSION_COMPRESSION_DEFLATE); - - char* pCur = (char*)pBuffer; - for (const_iterator it = begin(); it != end(); ++it) - { - ZipFile::CDRFileHeader& h = *(ZipFile::CDRFileHeader*)pCur; - pCur = (char*)(&h + 1); - h.lSignature = h.SIGNATURE; - h.nVersionMadeBy = nBaseVersion + (ZipFile::CREATOR_MSDOS << 8); - h.nVersionNeeded = nBaseVersion; - h.nFlags = 0; - h.nMethod = it->pFileEntry->nMethod; - h.nLastModTime = it->pFileEntry->nLastModTime; - h.nLastModDate = it->pFileEntry->nLastModDate; - h.desc = it->pFileEntry->desc; - h.nFileNameLength = (ZipFile::ushort)it->strPath.length(); - h.nExtraFieldLength = 0; - h.nFileCommentLength = 0; - h.nDiskNumberStart = 0; - h.nAttrInternal = 0; - h.lAttrExternal = 0; - h.lLocalHeaderOffset = it->pFileEntry->nFileHeaderOffset; - - memcpy (pCur, it->strPath.c_str(), it->strPath.length()); - pCur += it->strPath.length(); - } - - ZipFile::CDREnd& e = *(ZipFile::CDREnd*)pCur; - e.lSignature = e.SIGNATURE; - e.nDisk = encryptedFlag ? (1 << 15) : 0; - e.nCDRStartDisk = 0; - e.numEntriesOnDisk = (ZipFile::ushort)this->size(); - e.numEntriesTotal = (ZipFile::ushort)this->size(); - e.lCDRSize = (ZipFile::ulong)(pCur - (char*)pBuffer); - e.lCDROffset = lCDROffset; - e.nCommentLength = 0; - - pCur = (char*)(&e + 1); - - return pCur - (char*)pBuffer; -} - - -ZipDir::FileEntryList::FileEntryList (FileEntryTree* pTree, unsigned lCDROffset) - : m_lCDROffset (lCDROffset) -{ - Add (pTree); -} - -void ZipDir::FileEntryList::Add(FileEntryTree* pTree) -{ - for (FileEntryTree::SubdirMap::iterator itDir = pTree->GetDirBegin(); itDir != pTree->GetDirEnd(); ++itDir) - { - Add(pTree->GetDirEntry(itDir)); - } - for (FileEntryTree::FileMap::iterator itFile = pTree->GetFileBegin(); itFile != pTree->GetFileEnd(); ++itFile) - { - insert(pTree->GetFileEntry(itFile)); - } -} - -// updates each file entry's info about the next file entry -void ZipDir::FileEntryList::RefreshEOFOffsets() -{ - iterator it, itNext = begin(); - - if (itNext != end()) - { - while ((it = itNext, ++itNext) != end()) - { - // start scan - (*it)->nEOFOffset = (*itNext)->nFileHeaderOffset; - } - // it is the last one.. - (*it)->nEOFOffset = m_lCDROffset; - } -} - - -void ZipDir::FileRecordList::Backup(std::vector& arrFiles) const -{ - arrFiles.resize (size()); - std::vector::iterator itTgt = arrFiles.begin(); - - for (const_iterator it = begin(); it != end(); ++it, ++itTgt) - { - *itTgt = *it->pFileEntry; - } -} - -void ZipDir::FileRecordList::Restore(const std::vector& arrFiles) -{ - if (arrFiles.size() == size()) - { - std::vector::const_iterator itTgt = arrFiles.begin(); - for (iterator it = begin(); it != end(); ++it, ++itTgt) - { - *it->pFileEntry = *itTgt; - } - } -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirList.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirList.h deleted file mode 100644 index 58ce7312ae..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirList.h +++ /dev/null @@ -1,138 +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_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRLIST_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRLIST_H -#pragma once - -#include - -namespace ZipDir -{ - // this is the array of file entries that's convenient to use to construct CDR - struct FileRecord - { - string strPath; // relative path to the file inside zip - FileEntry* pFileEntry; // the file entry itself - - void ConstructFileRecord() - { - new (&strPath)string(); - } - }; - - struct FileDataRecord - : public FileRecord - { - FileDataRecord() { m_nRefCount = 0; } - void AddRef() { ++m_nRefCount; } - void Release() - { - if (--m_nRefCount <= 0) - { - Delete(); - } - } - - void Delete() - { - free (this); - } - - static FileDataRecord* New(const FileRecord& rThat) - { - FileDataRecord* pThis = (FileDataRecord*)malloc(sizeof(FileDataRecord) + rThat.pFileEntry->desc.lSizeCompressed); - - if (pThis) - { - pThis->m_nRefCount = 0; - pThis->ConstructFileRecord(); - *static_cast(pThis) = rThat; - } - return pThis; - } - - void* GetData() {return this + 1; } - - volatile signed int m_nRefCount; // the reference count - }; - - TYPEDEF_AUTOPTR(FileDataRecord); - typedef FileDataRecord_AutoPtr FileDataRecordPtr; - - struct FileRecordFileOffsetOrder - { - bool operator () (const FileRecord& left, const FileRecord& right) - { - return left.pFileEntry->nFileHeaderOffset < right.pFileEntry->nFileHeaderOffset; - } - }; - - // this is used for construction of CDR - class FileRecordList - : public std::vector - { - public: - FileRecordList(class FileEntryTree* pTree); - - struct ZipStats - { - // the size of the CDR in the file - size_t nSizeCDR; - // the size of the file data part (local file descriptors and file datas) - // if it's compacted - size_t nSizeCompactData; - }; - - // sorts the files by the physical offset in the zip file - void SortByFileOffset (); - - // returns the size of CDR in the zip file - ZipStats GetStats() const; - - // puts the CDR into the given block of mem - size_t MakeZipCDR(ZipFile::ulong lCDROffset, void* p, bool encryptedFlag) const; - - void Backup(std::vector& arrFiles) const; - void Restore(const std::vector& arrFiles); - - protected: - // recursively adds the files from this directory and subdirectories - // the strRoot contains the trailing slash - void AddAllFiles(class FileEntryTree* pTree, string strRoot = string()); - }; - - - struct FileEntryFileOffsetOrder - { - bool operator () (FileEntry* pLeft, FileEntry* pRight) const - { - return pLeft->nFileHeaderOffset < pRight->nFileHeaderOffset; - } - }; - - // this is used for refreshing EOFOffsets - class FileEntryList - : public std::set - { - public: - FileEntryList (class FileEntryTree* pTree, unsigned lCDROffset); - // updates each file entry's info about the next file entry - void RefreshEOFOffsets(); - protected: - void Add (class FileEntryTree* pTree); - unsigned m_lCDROffset; - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRLIST_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirStructures.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirStructures.cpp deleted file mode 100644 index 3d404ad62b..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirStructures.cpp +++ /dev/null @@ -1,670 +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 "smartptr.h" -#include -#include -#include -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include -#include -#include -#include - -using namespace ZipFile; - -ZipDir::FileEntry::FileEntry(const CDRFileHeader& header, const SExtraZipFileData& extra) -{ - this->desc = header.desc; - this->nFileHeaderOffset = header.lLocalHeaderOffset; - this->nFileDataOffset = INVALID_DATA_OFFSET; // we don't know yet - this->nMethod = header.nMethod; - this->nNameOffset = 0; // we don't know yet -#if defined(AZ_PLATFORM_WINDOWS) - this->nLastModTime = header.nLastModTime; - this->nLastModDate = header.nLastModDate; -#endif - this->nNTFS_LastModifyTime = extra.nLastModifyTime; - this->szOriginalFileName = 0; - - // make an estimation (at least this offset should be there), but we don't actually know yet - this->nEOFOffset = header.lLocalHeaderOffset + sizeof (ZipFile::LocalFileHeader) + header.nFileNameLength + header.desc.lSizeCompressed; -} - - - -// Uncompresses raw (without wrapping) data that is compressed with method 8 (deflated) in the Zip file -// returns one of the Z_* errors (Z_OK upon success) -// This function just mimics the standard uncompress (with modification taken from unzReadCurrentFile) -// with 2 differences: there are no 16-bit checks, and -// it initializes the inflation to start without waiting for compression method byte, as this is the -// way it's stored into zip file -int ZipDir::ZipRawUncompress (void* pUncompressed, unsigned long* pDestSize, const void* pCompressed, unsigned long nSrcSize) -{ - int nReturnCode = Z_OK; - - //check first 4 bytes to see what compression codec was used - if (CompressionCodec::TestForZSTDMagic(pCompressed)) - { - - size_t result = ZSTD_decompress(pUncompressed, *pDestSize, pCompressed, nSrcSize); - - if (ZSTD_isError(result)) - { - AZ_Error("ZipDirStructures", false, "Error decompressing using zstd: %s", ZSTD_getErrorName(result)); - nReturnCode = Z_BUF_ERROR; - } - else - { - *pDestSize = result; - } - return nReturnCode; - } - else if (CompressionCodec::TestForLZ4Magic(pCompressed)) - { - size_t result; - LZ4F_decompressionContext_t dctx; - result = LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION); - if (LZ4F_isError(result)) - { - AZ_Error("ZipDirStructures", false, "Error creating lz4 decompression context: %s", LZ4F_getErrorName(result)); - return Z_BUF_ERROR; - } - - size_t dstSize = (size_t)*pDestSize; - size_t srcSize = (size_t)nSrcSize; - result = LZ4F_decompress(dctx, pUncompressed, &dstSize, pCompressed, &srcSize, nullptr); - if (LZ4F_isError(result)) - { - AZ_Error("ZipDirStructures", false, "Error decompressing using lz4: %s", LZ4F_getErrorName(result)); - nReturnCode = Z_BUF_ERROR; - } - else - { - *pDestSize = (long)dstSize; - } - - size_t freeCode = LZ4F_freeDecompressionContext(dctx); - if (LZ4F_isError(freeCode)) - { - //We are not changing the return code in this case, but it is good to record that releasing the - //decompression context failed. - AZ_Error("ZipDirStructures", false, "Error releasing lz4 decompression context: %s", LZ4F_getErrorName(freeCode)); - } - - return nReturnCode; - } - - - //Default to Zlib - z_stream stream; - stream.next_in = (Bytef*)pCompressed; - stream.avail_in = (uInt)nSrcSize; - - int err; - - stream.next_out = (Bytef*)pUncompressed; - stream.avail_out = (uInt) * pDestSize; - - stream.zalloc = Z_NULL; - stream.zfree = Z_NULL; - stream.opaque = Z_NULL; - - err = inflateInit2(&stream, -MAX_WBITS); - if (err != Z_OK) - { - return err; - } - - // for some strange reason, passing Z_FINISH doesn't work - - // it seems the stream isn't finished for some files and - // inflate returns an error due to stream-end-not-reached (though expected) problem - err = inflate(&stream, Z_SYNC_FLUSH); - if (err != Z_STREAM_END && err != Z_OK) - { - inflateEnd(&stream); - return err == Z_OK ? Z_BUF_ERROR : err; - } - - *pDestSize = stream.total_out; - - err = inflateEnd(&stream); - return err; - -} - -// compresses the raw data into raw data. The buffer for compressed data itself with the heap passed. Uses method 8 (deflate) -// returns one of the Z_* errors (Z_OK upon success) -int ZipDir::ZipRawCompress(const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, int nLevel) -{ - z_stream stream; - int err; - - stream.next_out = reinterpret_cast(pCompressed); - - stream.next_in = const_cast(static_cast(pUncompressed)); - stream.avail_in = static_cast(nSrcSize); - - stream.avail_out = static_cast(*pDestSize); - - stream.zalloc = Z_NULL; - stream.zfree = Z_NULL; - stream.opaque = Z_NULL; - - err = deflateInit2 (&stream, nLevel, Z_DEFLATED, -MAX_WBITS, 9, Z_DEFAULT_STRATEGY); - if (err != Z_OK) - { - return err; - } - - err = deflate (&stream, Z_FINISH); - if (err != Z_STREAM_END) - { - deflateEnd(&stream); - return err == Z_OK ? Z_BUF_ERROR : err; - } - *pDestSize = stream.total_out; - - err = deflateEnd(&stream); - return err; -} - -int ZipDir::ZipRawCompressZSTD(const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, int nLevel) -{ - size_t result = ZSTD_compress(pCompressed, *pDestSize, pUncompressed, nSrcSize, nLevel); - - int err = Z_OK; - - if (ZSTD_isError(result)) - { - err = Z_BUF_ERROR; - } - else - { - *pDestSize = static_cast(result); - } - return err; -} - -int ZipDir::ZipRawCompressLZ4(const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, [[maybe_unused]] int nLevel) -{ - int returnCode = Z_OK; - const size_t compressedBufferMaxSize = aznumeric_caster(*pDestSize); - size_t lz4_code = LZ4F_compressFrame(pCompressed, compressedBufferMaxSize, pUncompressed, aznumeric_caster(nSrcSize), nullptr); - - if (LZ4F_isError(lz4_code)) - { - returnCode = Z_BUF_ERROR; - } - else - { - *pDestSize = aznumeric_caster(lz4_code); - } - - return returnCode; -} - -int ZipDir::GetCompressedSizeEstimate(unsigned long uncompressedSize, CompressionCodec::Codec codec) -{ - switch (codec) - { - case CompressionCodec::Codec::ZLIB: - return (uncompressedSize + (uncompressedSize >> 3) + 32); - case CompressionCodec::Codec::ZSTD: - return ZSTD_compressBound(uncompressedSize); - case CompressionCodec::Codec::LZ4: - return LZ4F_compressFrameBound(uncompressedSize, nullptr); - default: - break; - } - return 0; -} - -ZipDir::ValidationResult ZipDir::ValidateZSTDCompressedDataWithOriginalData(const void* pUncompressed, unsigned long uncompressedSize, const void* pCompressed, unsigned long compressedSize) -{ - auto decompressedSize = ZSTD_getDecompressedSize(pCompressed, compressedSize); - ZipDir::ValidationResult testResult = ValidationResult::OK; - - if (decompressedSize != uncompressedSize) - { - testResult = ValidationResult::SIZE_MISMATCH; - } - else - { - void* decompressionBuffer = azmalloc(decompressedSize); - - size_t result = ZSTD_decompress(decompressionBuffer, decompressedSize, pCompressed, compressedSize); - - if (ZSTD_isError(result)) - { - AZ_Warning("Debug", false, "Error decompressing data with zstd: %s", ZSTD_getErrorName(result)); - testResult = ValidationResult::DATA_CORRUPTED; - } - else - { - if (memcmp(decompressionBuffer, pUncompressed, decompressedSize) != 0) - { - testResult = ValidationResult::DATA_NO_MATCH; - } - } - azfree(decompressionBuffer); - } - return testResult; -} - -// finds the subdirectory entry by the name, using the names from the name pool -// assumes: all directories are sorted in alphabetical order. -// case-sensitive (must be lower-case if case-insensitive search in Win32 is performed) -ZipDir::DirEntry* ZipDir::DirHeader::FindSubdirEntry(const char* szName) -{ - if (this->numDirs) - { - const char* pNamePool = GetNamePool(); - DirEntrySortPred pred(pNamePool); - DirEntry* pBegin = GetSubdirEntry(0); - DirEntry* pEnd = pBegin + this->numDirs; - DirEntry* pEntry = std::lower_bound(pBegin, pEnd, szName, pred); -#if defined(LINUX) - if (pEntry != pEnd && !strcasecmp(szName, pEntry->GetName(pNamePool))) -#else - if (pEntry != pEnd && !strcmp(szName, pEntry->GetName(pNamePool))) -#endif - { - return pEntry; - } - } - return NULL; -} - -// finds the file entry by the name, using the names from the name pool -// assumes: all directories are sorted in alphabetical order. -// case-sensitive (must be lower-case if case-insensitive search in Win32 is performed) -ZipDir::FileEntry* ZipDir::DirHeader::FindFileEntry(const char* szName) -{ - if (this->numFiles) - { - const char* pNamePool = GetNamePool(); - DirEntrySortPred pred(pNamePool); - FileEntry* pBegin = GetFileEntry(0); - FileEntry* pEnd = pBegin + this->numFiles; - FileEntry* pEntry = std::lower_bound(pBegin, pEnd, szName, pred); -#if defined(LINUX) - if (pEntry != pEnd && !strcasecmp(szName, pEntry->GetName(pNamePool))) -#else - if (pEntry != pEnd && !strcmp(szName, pEntry->GetName(pNamePool))) -#endif - { - return pEntry; - } - } - return NULL; -} - - -// tries to refresh the file entry from the given file (reads fromthere if needed) -// returns the error code if the operation was impossible to complete -ZipDir::ErrorEnum ZipDir::Refresh(FILE* f, FileEntry* pFileEntry, bool encryptedHeaders) -{ - if (pFileEntry->nFileDataOffset != pFileEntry->INVALID_DATA_OFFSET) - { - return ZD_ERROR_SUCCESS; - } - - if (pFileEntry->desc.lSizeCompressed == 0) - { - return ZD_ERROR_SUCCESS; - } - -#ifdef WIN32 - if (_fseeki64(f, (__int64)pFileEntry->nFileHeaderOffset, SEEK_SET)) -#else - if (fseek(f, pFileEntry->nFileHeaderOffset, SEEK_SET)) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - if (encryptedHeaders) - { - // with encrypted headers FileEntries should always be initialized from CDR. - return ZD_ERROR_IO_FAILED; - } - - // read the local file header and the name (for validation) into the buffer - LocalFileHeader fileHeader; - if (1 != fread (&fileHeader, sizeof(fileHeader), 1, f)) - { - return ZD_ERROR_IO_FAILED; - } - - if (fileHeader.desc != pFileEntry->desc - || fileHeader.nMethod != pFileEntry->nMethod) - { - return ZD_ERROR_IO_FAILED; - } - - pFileEntry->nFileDataOffset = pFileEntry->nFileHeaderOffset + sizeof(LocalFileHeader) + fileHeader.nFileNameLength + fileHeader.nExtraFieldLength; - pFileEntry->nEOFOffset = pFileEntry->nFileDataOffset + pFileEntry->desc.lSizeCompressed; - return ZD_ERROR_SUCCESS; -} - -// writes into the file local header - without Extra data -// puts the new offset to the file data to the file entry -// in case of error can put INVALID_DATA_OFFSET into the data offset field of file entry -ZipDir::ErrorEnum ZipDir::WriteLocalHeader (FILE* f, FileEntry* pFileEntry, const char* szRelativePath, bool encrypt) -{ - size_t nFileNameLength = strlen(szRelativePath); - size_t nHeaderSize = sizeof(LocalFileHeader) + nFileNameLength; - - pFileEntry->nFileDataOffset = pFileEntry->nFileHeaderOffset + nHeaderSize; - pFileEntry->nEOFOffset = pFileEntry->nFileDataOffset + pFileEntry->desc.lSizeCompressed; - -#ifdef WIN32 - if (_fseeki64 (f, (__int64)pFileEntry->nFileHeaderOffset, SEEK_SET)) -#else - if (fseek (f, pFileEntry->nFileHeaderOffset, SEEK_SET)) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - if (encrypt) - { - std::vector garbage; - garbage.resize(nHeaderSize); - for (size_t i = 0; i < nHeaderSize; ++i) - { - garbage[i] = rand() & 0xff; - } - - if (fwrite(&garbage[0], nHeaderSize, 1, f) != 1) - { - return ZD_ERROR_IO_FAILED; - } - } - else - { - LocalFileHeader h; - memset(&h, 0, sizeof(h)); - - h.lSignature = h.SIGNATURE; - h.nVersionNeeded = 10; - h.nFlags = 0; - h.nMethod = pFileEntry->nMethod; -#if defined(AZ_PLATFORM_WINDOWS) - h.nLastModDate = pFileEntry->nLastModDate; - h.nLastModTime = pFileEntry->nLastModTime; -#endif - h.desc = pFileEntry->desc; - h.nFileNameLength = (unsigned short)nFileNameLength; - h.nExtraFieldLength = 0; - - if (1 != fwrite(&h, sizeof(h), 1, f)) - { - return ZD_ERROR_IO_FAILED; - } - - if (nFileNameLength > 0) - { - if (1 != fwrite (szRelativePath, nFileNameLength, 1, f)) - { - return ZD_ERROR_IO_FAILED; - } - } - } - - return ZD_ERROR_SUCCESS; -} - - -// conversion routines for the date/time fields used in Zip -ZipFile::ushort ZipDir::DOSDate(tm* t) -{ - return - ((t->tm_year - 80) << 9) - | (t->tm_mon << 5) - | t->tm_mday; -} - -ZipFile::ushort ZipDir::DOSTime(tm* t) -{ - return - ((t->tm_hour) << 11) - | ((t->tm_min) << 5) - | ((t->tm_sec) >> 1); -} - - - -// sets the current time to modification time -// calculates CRC32 for the new data -void ZipDir::FileEntry::OnNewFileData(void* pUncompressed, unsigned nSize, unsigned nCompressedSize, unsigned nCompressionMethod, bool bContinuous) -{ - time_t nTime; - time(&nTime); -#if defined(AZ_PLATFORM_WINDOWS) - tm t; - localtime_s(&t, &nTime); - this->nLastModTime = DOSTime(&t); - this->nLastModDate = DOSDate(&t); -#else - -#endif - this->nNTFS_LastModifyTime = AZStd::GetTimeUTCMilliSecond(); - - if (!bContinuous) - { - this->desc.lCRC32 = crc32(0L, Z_NULL, 0); - this->desc.lSizeCompressed = nCompressedSize; - this->desc.lSizeUncompressed = nSize; - } - - // we'll need CRC32 of the file to pack it - this->desc.lCRC32 = crc32(this->desc.lCRC32, (Bytef*)pUncompressed, nSize); - - this->nMethod = nCompressionMethod; -} - - -const char* ZipDir::DOSTimeCStr(ZipFile::ushort nTime) -{ - static char szBuf[16]; - azsprintf(szBuf, "%02d:%02d.%02d", (nTime >> 11), ((nTime & ((1 << 11) - 1)) >> 5), ((nTime & ((1 << 5) - 1)) << 1)); - return szBuf; -} - -const char* ZipDir::DOSDateCStr(ZipFile::ushort nTime) -{ - static char szBuf[32]; - azsprintf(szBuf, "%02d.%02d.%04d", (nTime & 0x1F), (nTime >> 5) & 0xF, (nTime >> 9) + 1980); - return szBuf; -} - -uint64 ZipDir::FileEntry::GetModificationTime() -{ - if (nNTFS_LastModifyTime != 0) - { - return nNTFS_LastModifyTime; - } - -#if defined(AZ_PLATFORM_WINDOWS) - // TODO/TIME: check and test - SYSTEMTIME st; - st.wYear = (nLastModDate >> 9) + 1980; - st.wMonth = ((nLastModDate >> 5) & 0xF); - st.wDay = (nLastModDate & 0x1F); - st.wHour = (nLastModTime >> 11); - st.wMinute = (nLastModTime >> 5) & 0x3F; - st.wSecond = (nLastModTime << 1) & 0x3F; - st.wMilliseconds = 0; - FILETIME ft; - SystemTimeToFileTime(&st, &ft); - LARGE_INTEGER lt; - lt.HighPart = ft.dwHighDateTime; - lt.LowPart = ft.dwLowDateTime; - return lt.QuadPart; -#else - return 0; -#endif -} - - -void ZipDir::FileEntry::SetFromFileTimeNTFS(int64 timestamp) -{ -#if defined(AZ_PLATFORM_WINDOWS) - FILETIME ft; - ft.dwHighDateTime = timestamp >> 32; - ft.dwLowDateTime = timestamp & 0xFFFFFFFF; - - WORD dosTime, dosDate; - FileTimeToDosDateTime(&ft, &dosDate, &dosTime); - - nLastModDate = dosDate; - nLastModTime = dosTime; -#endif - nNTFS_LastModifyTime = timestamp; -} - -bool ZipDir::FileEntry::CompareFileTimeNTFS(int64 timestamp) -{ -#if defined(AZ_PLATFORM_WINDOWS) - FILETIME ft; - ft.dwHighDateTime = timestamp >> 32; - ft.dwLowDateTime = timestamp & 0xFFFFFFFF; - - WORD dosTime, dosDate; - FileTimeToDosDateTime(&ft, &dosDate, &dosTime); - - return (nLastModTime == dosTime && nLastModDate == dosDate); -#else - return (nNTFS_LastModifyTime == timestamp); -#endif -} - -const char* ZipDir::Error::getError() -{ - switch (this->nError) - { -#define DECLARE_ERROR(x) case ZD_ERROR_##x: \ - return #x; - DECLARE_ERROR(SUCCESS); - DECLARE_ERROR(IO_FAILED); - DECLARE_ERROR(UNEXPECTED); - DECLARE_ERROR(UNSUPPORTED); - DECLARE_ERROR(INVALID_SIGNATURE); - DECLARE_ERROR(ZIP_FILE_IS_CORRUPT); - DECLARE_ERROR(DATA_IS_CORRUPT); - DECLARE_ERROR(NO_CDR); - DECLARE_ERROR(CDR_IS_CORRUPT); - DECLARE_ERROR(NO_MEMORY); - DECLARE_ERROR(VALIDATION_FAILED); - DECLARE_ERROR(CRC32_CHECK); - DECLARE_ERROR(ZLIB_FAILED); - DECLARE_ERROR(ZLIB_CORRUPTED_DATA); - DECLARE_ERROR(ZLIB_NO_MEMORY); - DECLARE_ERROR(CORRUPTED_DATA); - DECLARE_ERROR(INVALID_CALL); - DECLARE_ERROR(NOT_IMPLEMENTED); - DECLARE_ERROR(FILE_NOT_FOUND); - DECLARE_ERROR(DIR_NOT_FOUND); - DECLARE_ERROR(NAME_TOO_LONG); - DECLARE_ERROR(INVALID_PATH); - DECLARE_ERROR(FILE_ALREADY_EXISTS); -#undef DECLARE_ERROR - default: - return "Unknown ZD_ERROR code"; - } -} - - -inline void btea(uint32* v, int n, uint32 const k[4]) -{ -#define TEA_DELTA 0x9e3779b9 -#define TEA_MX (((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4)) ^ ((sum ^ y) + (k[(p & 3) ^ e] ^ z))) - uint32 y, z, sum; - unsigned p, rounds, e; - if (n > 1) /* Coding Part */ - { - rounds = 6 + 52 / n; - sum = 0; - z = v[n - 1]; - do - { - sum += TEA_DELTA; - e = (sum >> 2) & 3; - for (p = 0; p < n - 1; p++) - { - y = v[p + 1]; - z = v[p] += TEA_MX; - } - y = v[0]; - z = v[n - 1] += TEA_MX; - } while (--rounds); - } - else if (n < -1) /* Decoding Part */ - { - n = -n; - rounds = 6 + 52 / n; - sum = rounds * TEA_DELTA; - y = v[0]; - do - { - e = (sum >> 2) & 3; - for (p = n - 1; p > 0; p--) - { - z = v[p - 1]; - y = v[p] -= TEA_MX; - } - z = v[n - 1]; - y = v[0] -= TEA_MX; - } while ((sum -= TEA_DELTA) != 0); - } -#undef TEA_DELTA -#undef TEA_MX -} - -static inline void SwapByteOrder(uint32* values, size_t count) -{ - for (uint32* w = values, * e = values + count; w != e; ++w) - { - *w = (*w >> 24) + ((*w >> 8) & 0xff00) + ((*w & 0xff00) << 8) + (*w << 24); - } -} - -////////////////////////////////////////////////////////////////////////// -void ZipDir::Encrypt(char* buffer, size_t size, const EncryptionKey& key) -{ - uint32* intBuffer = (uint32*)buffer; - const int encryptedLen = size >> 2; - - SwapByteOrder(intBuffer, encryptedLen); - - btea(intBuffer, encryptedLen, key.key); - - SwapByteOrder(intBuffer, encryptedLen); -} - -////////////////////////////////////////////////////////////////////////// -void ZipDir::Decrypt(char* buffer, size_t size, const EncryptionKey& key) -{ - uint32* intBuffer = (uint32*)buffer; - const int encryptedLen = size >> 2; - - SwapByteOrder(intBuffer, encryptedLen); - - btea(intBuffer, -encryptedLen, key.key); - - SwapByteOrder(intBuffer, encryptedLen); -} - diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.cpp deleted file mode 100644 index b35ae48b2a..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.cpp +++ /dev/null @@ -1,356 +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 "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirTree.h" - - -// Adds or finds the file. Returns non-initialized structure if it was added, -// or an IsInitialized() structure if it was found -ZipDir::FileEntry* ZipDir::FileEntryTree::Add(char* szPath, char* szUnifiedPath) -{ - // find the slash; if we found it, it's a subdirectory - add a subdirectory and - // add the file to it. - // if we didn't find it, it's a file - add the file to this dir - - char* pSlash; - for (pSlash = szPath; *pSlash && *pSlash != '/' && *pSlash != '\\'; ++pSlash) - { - continue; // find the next slash - } - char* pUnifiedSlash = szUnifiedPath + (pSlash - szPath); - assert(*pUnifiedSlash == '\0' || *pUnifiedSlash == '\\' || *pUnifiedSlash == '/'); - - if (*pUnifiedSlash) - { - FileEntryTree* pSubdir; - // we have a subdirectory here - create the file in it - { - char* unifiedDir = szUnifiedPath; - *pUnifiedSlash = '\0'; - - char* dir = szPath; - *pSlash = '\0'; - - SubdirMap::iterator it = m_mapDirs.find (unifiedDir); - if (it == m_mapDirs.end()) - { - pSubdir = new FileEntryTree(dir); - m_mapDirs.insert (SubdirMap::value_type(unifiedDir, pSubdir)); - } - else - { - pSubdir = it->second; - } - } - - return pSubdir->Add(pSlash + 1, pUnifiedSlash + 1); - } - else - { - ZipDir::FileEntry* result = &m_mapFiles[szUnifiedPath]; - result->szOriginalFileName = szPath; - return result; - } -} - -// adds a file to this directory -ZipDir::ErrorEnum ZipDir::FileEntryTree::Add (char* szPath, char* szUnifiedPath, const FileEntry& file) -{ - FileEntry* pFile = Add (szPath, szUnifiedPath); - if (!pFile) - { - return ZD_ERROR_INVALID_PATH; - } - if (pFile->IsInitialized()) - { - return ZD_ERROR_FILE_ALREADY_EXISTS; - } - // preserve original filename - const char* szOriginalFileName = pFile->szOriginalFileName; - *pFile = file; - pFile->szOriginalFileName = szOriginalFileName; - return ZD_ERROR_SUCCESS; -} - -// returns the number of files in this tree, including this and sublevels -unsigned ZipDir::FileEntryTree::NumFilesTotal() const -{ - unsigned numFiles = (unsigned)m_mapFiles.size(); - for (SubdirMap::const_iterator it = m_mapDirs.begin(); it != m_mapDirs.end(); ++it) - { - numFiles += it->second->NumFilesTotal(); - } - return numFiles; -} - -#ifdef _TEST_ -size_t g_nSF = 0, g_nSS = 0, g_nSN = 0, g_nSNa = 0, g_nSH; -size_t g_nGF = 0, g_nGS = 0, g_nGN = 0, g_nGNa = 0, g_nGH; -#endif - -// returns the size required to serialize the tree -size_t ZipDir::FileEntryTree::GetSizeSerialized() const -{ - // the total size of name pool gets aligned on 4-byte boundary - size_t nSizeOfNamePool = 0; - size_t nSizeOfFileEntries = 0, nSizeOfDirEntries = 0; - size_t nSizeOfSubdirs = 0; - - for (SubdirMap::const_iterator itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - nSizeOfDirEntries += sizeof(DirEntry); - const char* dirname = itDir->first; - nSizeOfNamePool += strlen(dirname) + 1; - nSizeOfSubdirs += itDir->second->GetSizeSerialized(); - } - - // for each file, we need to have an entry in the name pool and in the file list - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - nSizeOfFileEntries += sizeof(FileEntry); - const char* fname = itFile->first; - nSizeOfNamePool += strlen(fname) + 1; - } - - if (nSizeOfNamePool > 0xFFFF) - { - // we don't support so long names/directories - THROW_ZIPDIR_ERROR(ZD_ERROR_UNSUPPORTED, "Name pool larger then 65536 bytes"); - } - -#ifdef _TEST_ - g_nGF += nSizeOfFileEntries; - g_nGS += nSizeOfDirEntries; - g_nGN += nSizeOfNamePool; - g_nGNa += ((nSizeOfNamePool + 3) & ~3); - g_nGH += sizeof(DirHeader); -#endif - - return sizeof(DirHeader) + ((nSizeOfNamePool + 3) & ~3) + nSizeOfDirEntries + nSizeOfFileEntries + nSizeOfSubdirs; -} - -// serializes into the memory -size_t ZipDir::FileEntryTree::Serialize (DirHeader* pDirHeader) const -{ - pDirHeader->numDirs = (ZipFile::ushort)m_mapDirs.size(); - pDirHeader->numFiles = (ZipFile::ushort)m_mapFiles.size(); - DirEntry* pDirEntries = (DirEntry*)(pDirHeader + 1); - FileEntry* pFileEntries = (FileEntry*)(pDirEntries + pDirHeader->numDirs); - char* pNamePool = (char*)(pFileEntries + pDirHeader->numFiles); - - char* pName = pNamePool; - DirEntry* pDirEntry = pDirEntries; - FileEntry* pFileEntry = pFileEntries; - - SubdirMap::const_iterator itDir; - for (itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - pDirEntry->nNameOffset = (ZipFile::ulong)(pName - pNamePool); - size_t nNameLen = strlen(itDir->first); - memcpy (pName, itDir->first, nNameLen + 1); - pName += nNameLen + 1; - ++pDirEntry; - } - - assert ((FileEntry*)pDirEntry == pFileEntry); - - // for each file, we need to have an entry in the name pool and in the file list - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - *pFileEntry = itFile->second; - const char* filename = itFile->first; - pFileEntry->nNameOffset = (ZipFile::ushort)(pName - pNamePool); - size_t nNameLen = strlen(filename); - memcpy (pName, filename, nNameLen + 1); - pName += nNameLen + 1; - ++pFileEntry; - } - assert ((const char*)pFileEntry == pNamePool); - - // now the name pool is full. Go on and fill the other directories - const char* pSubdirHeader = (const char*)(((UINT_PTR)(pName + 3)) & ~3); - -#ifdef _TEST_ - g_nSF += pDirHeader->numFiles * sizeof(FileEntry); - g_nSS += pDirHeader->numDirs * sizeof(DirEntry); - g_nSN += pName - pNamePool; - g_nSNa += pSubdirHeader - pNamePool; - g_nSH += sizeof(DirHeader); -#endif - - pDirEntry = pDirEntries; - for (itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - pDirEntry->nDirHeaderOffset = (ZipFile::ulong)(pSubdirHeader - (const char*)pDirEntry); - pSubdirHeader += itDir->second->Serialize ((DirHeader*)pSubdirHeader); - ++pDirEntry; - } - - - return pSubdirHeader - (const char*)pDirHeader; -} - - - -void ZipDir::FileEntryTree::Clear() -{ - for (SubdirMap::iterator it = m_mapDirs.begin(); it != m_mapDirs.end(); ++it) - { - delete it->second; - } - m_mapDirs.clear(); - m_mapFiles.clear(); -} - - -size_t ZipDir::FileEntryTree::GetSize() const -{ - size_t nSize = sizeof(*this); - for (SubdirMap::const_iterator itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - nSize += strlen(itDir->first) + sizeof(*itDir) + itDir->second->GetSize(); - } - - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - nSize += strlen(itFile->first) + sizeof(*itFile); - } - return nSize; -} - -size_t ZipDir::FileEntryTree::GetCompressedFileSize() const -{ - size_t nSize = 0; - for (SubdirMap::const_iterator itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - nSize += itDir->second->GetCompressedFileSize(); - } - - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - nSize += itFile->second.desc.lSizeCompressed; - } - return nSize; -} - -size_t ZipDir::FileEntryTree::GetUncompressedFileSize() const -{ - size_t nSize = 0; - for (SubdirMap::const_iterator itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - nSize += itDir->second->GetUncompressedFileSize(); - } - - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - nSize += itFile->second.desc.lSizeUncompressed; - } - return nSize; -} - -bool ZipDir::FileEntryTree::IsOwnerOf (const FileEntry* pFileEntry) const -{ - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - if (pFileEntry == &itFile->second) - { - return true; - } - } - - for (SubdirMap::const_iterator itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - if (itDir->second->IsOwnerOf (pFileEntry)) - { - return true; - } - } - - return false; -} - -ZipDir::FileEntryTree* ZipDir::FileEntryTree::FindDir(const char* szDirName) -{ - SubdirMap::iterator it = m_mapDirs.find (szDirName); - if (it == m_mapDirs.end()) - { - return NULL; - } - else - { - return it->second; - } -} - -ZipDir::FileEntryTree::FileMap::iterator ZipDir::FileEntryTree::FindFile (const char* szFileName) -{ - return m_mapFiles.find (szFileName); -} - -ZipDir::FileEntry* ZipDir::FileEntryTree::GetFileEntry(FileMap::iterator it) -{ - return it == GetFileEnd() ? NULL : &it->second; -} - -ZipDir::FileEntryTree* ZipDir::FileEntryTree::GetDirEntry(SubdirMap::iterator it) -{ - return it == GetDirEnd() ? NULL : it->second; -} - -const ZipDir::FileEntry* ZipDir::FileEntryTree::GetFileEntry(FileMap::const_iterator it) const -{ - return it == GetFileEnd() ? NULL : &it->second; -} - -const ZipDir::FileEntryTree* ZipDir::FileEntryTree::GetDirEntry(SubdirMap::const_iterator it) const -{ - return it == GetDirEnd() ? NULL : it->second; -} - -ZipDir::ErrorEnum ZipDir::FileEntryTree::RemoveDir (const char* szDirName) -{ - SubdirMap::iterator itRemove = m_mapDirs.find (szDirName); - if (itRemove == m_mapDirs.end()) - { - return ZD_ERROR_FILE_NOT_FOUND; - } - - delete itRemove->second; - m_mapDirs.erase (itRemove); - return ZD_ERROR_SUCCESS; -} - -ZipDir::ErrorEnum ZipDir::FileEntryTree::RemoveFile (const char* szFileName) -{ - FileMap::iterator itRemove = m_mapFiles.find (szFileName); - if (itRemove == m_mapFiles.end()) - { - return ZD_ERROR_FILE_NOT_FOUND; - } - - m_mapFiles.erase (itRemove); - return ZD_ERROR_SUCCESS; -} - -size_t ZipDir::FileEntryTree::NumDirsTotal() const -{ - size_t result = m_mapDirs.size(); - SubdirMap::const_iterator it; - for (it = m_mapDirs.begin(); it != m_mapDirs.end(); ++it) - { - result += it->second->NumDirsTotal(); - } - return result; -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.h deleted file mode 100644 index 0e8af76142..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRTREE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRTREE_H -#pragma once - - -namespace ZipDir -{ - class FileEntryTree - { - public: - FileEntryTree() - : m_originalName(0) {} - FileEntryTree(const char* originalName) - : m_originalName(originalName) {} - ~FileEntryTree () {Clear(); } - - // adds a file to this directory - // Function can modify szPath input - ErrorEnum Add (char* szPath, char* szUnifiedPath, const FileEntry& file); - - // Adds or finds the file. Returns non-initialized structure if it was added, - // or an IsInitialized() structure if it was found - // Function can modify szPath input - FileEntry* Add (char* szPath, char* szUnifiedPath); - - // returns the number of files in this tree, including this and sublevels - unsigned NumFilesTotal() const; - - // returns the size required to serialize the tree - size_t GetSizeSerialized() const; - - // serializes into the memory - size_t Serialize (DirHeader* pDir) const; - - void Clear(); - - void Swap (FileEntryTree& rThat) - { - m_mapDirs.swap (rThat.m_mapDirs); - m_mapFiles.swap (rThat.m_mapFiles); - } - - size_t GetSize() const; - - size_t GetCompressedFileSize() const; - size_t GetUncompressedFileSize() const; - - bool IsOwnerOf (const FileEntry* pFileEntry) const; - - // subdirectories - typedef std::map > SubdirMap; - // file entries - typedef std::map > FileMap; - - FileEntryTree* FindDir(const char* szDirName); - ErrorEnum RemoveDir (const char* szDirName); - ErrorEnum RemoveAll (){Clear(); return ZD_ERROR_SUCCESS; } - FileEntry* FindFileEntry (const char* szFileName); - FileMap::iterator FindFile (const char* szFileName); - ErrorEnum RemoveFile (const char* szFileName); - FileEntryTree* GetDirectory(){return this; } // the FileENtryTree is simultaneously an entry in the dir list AND the directory header - - FileMap::iterator GetFileBegin() {return m_mapFiles.begin(); } - FileMap::iterator GetFileEnd() {return m_mapFiles.end(); } - FileMap::const_iterator GetFileBegin() const {return m_mapFiles.begin(); } - FileMap::const_iterator GetFileEnd() const {return m_mapFiles.end(); } - unsigned NumFiles() const {return (unsigned)m_mapFiles.size(); } - - SubdirMap::iterator GetDirBegin() {return m_mapDirs.begin(); } - SubdirMap::iterator GetDirEnd() {return m_mapDirs.end(); } - SubdirMap::const_iterator GetDirBegin() const {return m_mapDirs.begin(); } - SubdirMap::const_iterator GetDirEnd() const {return m_mapDirs.end(); } - size_t NumDirsTotal() const; - - const char* GetFileName(FileMap::iterator it) {return it->first; } - const char* GetDirName(SubdirMap::iterator it) {return it->first; } - const char* GetOriginalName() const{ return m_originalName; } - - FileEntry* GetFileEntry(FileMap::iterator it); - FileEntryTree* GetDirEntry(SubdirMap::iterator it); - const FileEntry* GetFileEntry(FileMap::const_iterator it) const; - const FileEntryTree* GetDirEntry(SubdirMap::const_iterator it) const; - - protected: - SubdirMap m_mapDirs; - FileMap m_mapFiles; - const char* m_originalName; - }; -} -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRTREE_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipFile.h b/Code/Tools/CryCommonTools/ZipDir/ZipFile.h deleted file mode 100644 index 5e1f78050c..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipFile.h +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILE_H -#pragma once - - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILE_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat.h b/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat.h deleted file mode 100644 index 3f2083de0f..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat.h +++ /dev/null @@ -1,388 +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_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_H -#pragma once - -#include -#include - -#if AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 -#pragma pack(push) -#pragma pack(1) -#define PACK_GCC -#else -#define PACK_GCC __PACKED -#endif - -namespace ZipFile -{ - typedef unsigned int ulong; - typedef unsigned short ushort; - - // General-purpose bit field flags - enum - { - GPF_ENCRYPTED = 1 << 0, // If set, indicates that the file is encrypted. - GPF_DATA_DESCRIPTOR = 1 << 3, // if set, the CRC32 and sizes aren't set in the file header, but only in the data descriptor following compressed data - GPF_RESERVED_8_ENHANCED_DEFLATING = 1 << 4, // Reserved for use with method 8, for enhanced deflating. - GPF_COMPRESSED_PATCHED = 1 << 5, // the file is compressed patched data - }; - - // compression methods - enum - { - METHOD_STORE = 0, // The file is stored (no compression) - METHOD_SHRINK = 1, // The file is Shrunk - METHOD_REDUCE_1 = 2, // The file is Reduced with compression factor 1 - METHOD_REDUCE_2 = 3, // The file is Reduced with compression factor 2 - METHOD_REDUCE_3 = 4, // The file is Reduced with compression factor 3 - METHOD_REDUCE_4 = 5, // The file is Reduced with compression factor 4 - METHOD_IMPLODE = 6, // The file is Imploded - METHOD_TOKENIZE = 7, // Reserved for Tokenizing compression algorithm - METHOD_DEFLATE = 8, // The file is Deflated - METHOD_DEFLATE64 = 9, // Enhanced Deflating using Deflate64(tm) - METHOD_IMPLODE_PKWARE = 10, // PKWARE Date Compression Library Imploding - METHOD_DEFLATE_AND_ENCRYPT = 11 // Deflate + Custom encryption - }; - - // version numbers - enum - { - VERSION_DEFAULT = 10, // Default value - - VERSION_TYPE_VOLUMELABEL = 11, // File is a volume label - VERSION_TYPE_FOLDER = 20, // File is a folder (directory) - VERSION_TYPE_PATCHDATASET = 27, // File is a patch data set - VERSION_TYPE_ZIP64 = 45, // File uses ZIP64 format extensions - - VERSION_COMPRESSION_DEFLATE = 20, // File is compressed using Deflate compression - VERSION_COMPRESSION_DEFLATE64 = 21, // File is compressed using Deflate64(tm) - VERSION_COMPRESSION_DCLIMPLODE = 25, // File is compressed using PKWARE DCL Implode - VERSION_COMPRESSION_BZIP2 = 46, // File is compressed using BZIP2 compression* - VERSION_COMPRESSION_LZMA = 63, // File is compressed using LZMA - VERSION_COMPRESSION_PPMD = 63, // File is compressed using PPMd+ - - VERSION_ENCRYPTION_PKWARE = 20, // File is encrypted using traditional PKWARE encryption - VERSION_ENCRYPTION_DES = 50, // File is encrypted using DES - VERSION_ENCRYPTION_3DES = 50, // File is encrypted using 3DES - VERSION_ENCRYPTION_RC2 = 50, // File is encrypted using original RC2 encryption - VERSION_ENCRYPTION_RC4 = 50, // File is encrypted using RC4 encryption - VERSION_ENCRYPTION_AES = 51, // File is encrypted using AES encryption - VERSION_ENCRYPTION_RC2C = 51, // File is encrypted using corrected RC2 encryption** - VERSION_ENCRYPTION_RC4C = 52, // File is encrypted using corrected RC2-64 encryption** - VERSION_ENCRYPTION_NOOAEP = 61, // File is encrypted using non-OAEP key wrapping*** - VERSION_ENCRYPTION_CDR = 62, // Central directory encryption - VERSION_ENCRYPTION_BLOWFISH = 63, // File is encrypted using Blowfish - VERSION_ENCRYPTION_TWOFISH = 63, // File is encrypted using Twofish - }; - - // creator numbers - enum - { - CREATOR_MSDOS = 0, // MS-DOS and OS/2 (FAT / VFAT / FAT32 file systems) - CREATOR_AMIGA = 1, // Amiga - CREATOR_OpenVMS = 2, // OpenVMS - CREATOR_UNIX = 3, // UNIX - CREATOR_VM = 4, // VM/CMS - CREATOR_ATARI = 5, // Atari ST - CREATOR_OS2 = 6, // OS/2 H.P.F.S. - CREATOR_MACINTOSH = 7, // Macintosh - CREATOR_ZSYSTEM = 8, // Z-System - CREATOR_CPM = 9, // CP/M - CREATOR_WINDOWS = 10, // Windows NTFS - CREATOR_MVS = 11, // MVS (OS/390 - Z/OS) - CREATOR_VSE = 12, // VSE - CREATOR_ACORN = 13, // Acorn Risc - CREATOR_VFAT = 14, // VFAT - CREATOR_AMVS = 15, // alternate MVS - CREATOR_BEOS = 16, // BeOS - CREATOR_TANDEM = 17, // Tandem - CREATOR_OS400 = 18, // OS/400 - CREATOR_OSX = 19, // OS X (Darwin) - - CREATOR_UNUSED = 20, // 20 thru 255 - unused - }; - - enum - { - ZIP64_SEE_EXTENSION = -1 // If an archive is in ZIP64 format - // and a value in a field is 0xFFFFFFFF (or 0xFFFF), the size will be - // in the corresponding 8 byte (or 4 byte) ZIP64 extended information. - }; - - // end of Central Directory Record - // followed by the .zip file comment (variable size, can be empty, obtained from nCommentLength) - struct CDREnd - { - enum - { - SIGNATURE = 0x06054b50 - }; - ulong lSignature; // end of central dir signature 4 bytes (0x06054b50) - ushort nDisk; // number of this disk 2 bytes - ushort nCDRStartDisk; // number of the disk with the start of the central directory 2 bytes - ushort numEntriesOnDisk; // total number of entries in the central directory on this disk 2 bytes - ushort numEntriesTotal; // total number of entries in the central directory 2 bytes - ulong lCDRSize; // size of the central directory 4 bytes - ulong lCDROffset; // offset of start of central directory with respect to the starting disk number 4 bytes - ushort nCommentLength; // .ZIP file comment length 2 bytes - - AUTO_STRUCT_INFO - - // .ZIP file comment (variable size, can be empty) follows - } PACK_GCC; - - // end of Central Directory Record - // followed by the zip64 extensible data sector (variable size, can be empty, obtained from nExtDataLength) - struct CDREnd_ZIP64 - { - enum - { - SIGNATURE = 0x06064b50 - }; - ulong lSignature; // end of central dir signature 4 bytes (0x06064b50) - uint64 nExtDataLength; // The value stored into the "size of zip64 end of central directory record" should be the size of the remaining record and should not include the leading 12 bytes. 8 bytes - ushort nVersionMadeBy; // version made by 2 bytes - ushort nVersionNeeded; // version needed to extract 2 bytes - ulong nDisk; // number of this disk 4 bytes - ulong nCDRStartDisk; // number of the disk with the start of the central directory 4 bytes - uint64 numEntriesOnDisk; // total number of entries in the central directory on this disk 8 bytes - uint64 numEntriesTotal; // total number of entries in the central directory 8 bytes - uint64 lCDRSize; // size of the central directory 8 bytes - uint64 lCDROffset; // offset of start of central directory with respect to the starting disk number 8 bytes - - AUTO_STRUCT_INFO - - // zip64 extensible data sector (variable size, can be empty) follows - } PACK_GCC; - - // end of Central Directory Locator - struct CDRLocator_ZIP64 - { - enum - { - SIGNATURE = 0x07064b50 - }; - ulong lSignature; // end of central loc signature 4 bytes (0x07064b50) - ulong nCDR64StartDisk; // number of the disk with the start of the zip64 end of central directory 4 bytes - uint64 lCDR64EndOffset; // relative offset of the zip64 end of central directory record 8 bytes - ulong nDisks; // number of disks 4 bytes - - AUTO_STRUCT_INFO - } PACK_GCC; - - // This descriptor exists only if bit 3 of the general - // purpose bit flag is set (see below). It is byte aligned - // and immediately follows the last byte of compressed data. - // This descriptor is used only when it was not possible to - // seek in the output .ZIP file, e.g., when the output .ZIP file - // was standard output or a non seekable device. For Zip64 format - // archives, the compressed and uncompressed sizes are 8 bytes each. - struct DataDescriptor - { - ulong lCRC32; // crc-32 4 bytes - ulong lSizeCompressed; // compressed size 4 bytes - ulong lSizeUncompressed; // uncompressed size 4 bytes - - bool operator == (const DataDescriptor& d) const - { - return lCRC32 == d.lCRC32 && lSizeCompressed == d.lSizeCompressed && lSizeUncompressed == d.lSizeUncompressed; - } - bool operator != (const DataDescriptor& d) const - { - return lCRC32 != d.lCRC32 || lSizeCompressed != d.lSizeCompressed || lSizeUncompressed != d.lSizeUncompressed; - } - - bool IsZIP64([[maybe_unused]] const DataDescriptor& d) const - { - return lSizeCompressed == (ulong)ZIP64_SEE_EXTENSION || lSizeUncompressed == (ulong)ZIP64_SEE_EXTENSION; - } - - AUTO_STRUCT_INFO - } PACK_GCC; - - // When compressing files, compressed and uncompressed sizes - // should be stored in ZIP64 format (as 8 byte values) when a - // file's size exceeds 0xFFFFFFFF. However ZIP64 format may be - // used regardless of the size of a file. When extracting, if - // the zip64 extended information extra field is present for - // the file the compressed and uncompressed sizes will be 8 - // byte values. - struct DataDescriptor_ZIP64 - { - ulong lCRC32; // crc-32 4 bytes - uint64 lSizeCompressed; // compressed size 8 bytes - uint64 lSizeUncompressed; // uncompressed size 8 bytes - - bool operator == (const DataDescriptor& d) const - { - return lCRC32 == d.lCRC32 && lSizeCompressed == d.lSizeCompressed && lSizeUncompressed == d.lSizeUncompressed; - } - bool operator != (const DataDescriptor& d) const - { - return lCRC32 != d.lCRC32 || lSizeCompressed != d.lSizeCompressed || lSizeUncompressed != d.lSizeUncompressed; - } - - AUTO_STRUCT_INFO - } PACK_GCC; - - // the File Header as it appears in the CDR - // followed by: - // file name (variable size) - // extra field (variable size) - // file comment (variable size) - struct CDRFileHeader - { - enum - { - SIGNATURE = 0x02014b50 - }; - ulong lSignature; // central file header signature 4 bytes (0x02014b50) - ushort nVersionMadeBy; // version made by 2 bytes - ushort nVersionNeeded; // version needed to extract 2 bytes - ushort nFlags; // general purpose bit flag 2 bytes - ushort nMethod; // compression method 2 bytes - ushort nLastModTime; // last mod file time 2 bytes - ushort nLastModDate; // last mod file date 2 bytes - DataDescriptor desc; - ushort nFileNameLength; // file name length 2 bytes - ushort nExtraFieldLength; // extra field length 2 bytes - ushort nFileCommentLength; // file comment length 2 bytes - ushort nDiskNumberStart; // disk number start 2 bytes - ushort nAttrInternal; // internal file attributes 2 bytes - ulong lAttrExternal; // external file attributes 4 bytes - - // This is the offset from the start of the first disk on - // which this file appears, to where the local header should - // be found. If an archive is in zip64 format and the value - // in this field is 0xFFFFFFFF, the size will be in the - // corresponding 8 byte zip64 extended information extra field. - enum - { - ZIP64_LOCAL_HEADER_OFFSET = 0xFFFFFFFF - }; - ulong lLocalHeaderOffset; // relative offset of local header 4 bytes - - bool IsZIP64([[maybe_unused]] const CDRFileHeader& d) const - { - return desc.IsZIP64(desc) || nDiskNumberStart == (ushort)ZIP64_SEE_EXTENSION || lLocalHeaderOffset == (ulong)ZIP64_SEE_EXTENSION; - } - - AUTO_STRUCT_INFO - } PACK_GCC; - - - // this is the local file header that appears before the compressed data - // followed by: - // file name (variable size) - // extra field (variable size) - struct LocalFileHeader - { - enum - { - SIGNATURE = 0x04034b50 - }; - ulong lSignature; // local file header signature 4 bytes (0x04034b50) - ushort nVersionNeeded; // version needed to extract 2 bytes - ushort nFlags; // general purpose bit flag 2 bytes - ushort nMethod; // compression method 2 bytes - ushort nLastModTime; // last mod file time 2 bytes - ushort nLastModDate; // last mod file date 2 bytes - DataDescriptor desc; - ushort nFileNameLength; // file name length 2 bytes - ushort nExtraFieldLength; // extra field length 2 bytes - - bool IsZIP64([[maybe_unused]] const LocalFileHeader& d) const - { - return desc.IsZIP64(desc); - } - - AUTO_STRUCT_INFO - } PACK_GCC; - - // compression methods - enum EExtraHeaderID - { - EXTRA_ZIP64 = 0x0001, // ZIP64 extended information extra field - EXTRA_NTFS = 0x000a, // NTFS - EXTRA_UNIX = 0x000d, // UNIX - EXTRA_PATCH = 0x000f, // Patch Descriptor - }; - - ////////////////////////////////////////////////////////////////////////// - // header1+data1 + header2+data2 . . . - // Each header should consist of: - // Header ID - 2 bytes - // Data Size - 2 bytes - struct ExtraFieldHeader - { - ushort headerID; - ushort dataSize; - - AUTO_STRUCT_INFO - } PACK_GCC; - - struct ExtraNTFSHeader - { - ulong reserved; // 4 bytes. - ushort attrTag; // 2 bytes. - ushort attrSize; // 2 bytes. - - AUTO_STRUCT_INFO - } PACK_GCC; - - ////////////////////////////////////////////////////////////////////////// - // The following is the layout of the zip64 extended - // information "extra" block. If one of the size or - // offset fields in the Local or Central directory - // record is too small to hold the required data, - // a Zip64 extended information record is created. - // The order of the fields in the zip64 extended - // information record is fixed, but the fields MUST - // only appear if the corresponding Local or Central - // directory record field is set to 0xFFFF or 0xFFFFFFFF. - // - // The extended information in the Local header MUST include - // BOTH original and compressed file size fields. - - struct ExtraZIP64LocalFileHeader - { - // LocalFileHeader overrides - uint64 lSizeUncompressed; // uncompressed size 4->8 bytes - uint64 lSizeCompressed; // compressed size 4->8 bytes - - AUTO_STRUCT_INFO - } PACK_GCC; - - struct ExtraZIP64CDRFileHeader - { - // CDRFileHeader overrides - uint64 lSizeUncompressed; // uncompressed size 4->8 bytes - uint64 lSizeCompressed; // compressed size 4->8 bytes - - uint64 lLocalHeaderOffset; // relative offset of local header 4->8 bytes - ulong nDiskNumberStart; // Number of the disk on which this file starts 2->4 bytes - - AUTO_STRUCT_INFO - } PACK_GCC; -} - -#undef PACK_GCC - -#if AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 -#pragma pack(pop) -#endif - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat_info.h b/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat_info.h deleted file mode 100644 index 9f91eec49b..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat_info.h +++ /dev/null @@ -1,112 +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_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_INFO_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_INFO_H -#pragma once - -#include "ZipFileFormat.h" - -STRUCT_INFO_BEGIN(ZipFile::CDREnd) -STRUCT_VAR_INFO(lSignature, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nDisk, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nCDRStartDisk, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(numEntriesOnDisk, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(numEntriesTotal, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(lCDRSize, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lCDROffset, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nCommentLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_INFO_END(ZipFile::CDREnd) - -STRUCT_INFO_BEGIN(ZipFile::CDREnd_ZIP64) -STRUCT_VAR_INFO(lSignature, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nExtDataLength, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(nVersionMadeBy, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nVersionNeeded, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nDisk, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nCDRStartDisk, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(numEntriesOnDisk, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(numEntriesTotal, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(lCDRSize, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(lCDROffset, TYPE_INFO(ZipFile::uint64)) -STRUCT_INFO_END(ZipFile::CDREnd_ZIP64) - -STRUCT_INFO_BEGIN(ZipFile::CDRLocator_ZIP64) -STRUCT_VAR_INFO(lSignature, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nCDR64StartDisk, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lCDR64EndOffset, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(nDisks, TYPE_INFO(ZipFile::ulong)) -STRUCT_INFO_END(ZipFile::CDRLocator_ZIP64) - -STRUCT_INFO_BEGIN(ZipFile::DataDescriptor) -STRUCT_VAR_INFO(lCRC32, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lSizeCompressed, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lSizeUncompressed, TYPE_INFO(ZipFile::ulong)) -STRUCT_INFO_END(ZipFile::DataDescriptor) - -STRUCT_INFO_BEGIN(ZipFile::DataDescriptor_ZIP64) -STRUCT_VAR_INFO(lCRC32, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lSizeCompressed, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(lSizeUncompressed, TYPE_INFO(ZipFile::uint64)) -STRUCT_INFO_END(ZipFile::DataDescriptor_ZIP64) - -STRUCT_INFO_BEGIN(ZipFile::CDRFileHeader) -STRUCT_VAR_INFO(lSignature, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nVersionMadeBy, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nVersionNeeded, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nFlags, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nMethod, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nLastModTime, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nLastModDate, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(desc, TYPE_INFO(ZipFile::DataDescriptor)) -STRUCT_VAR_INFO(nFileNameLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nExtraFieldLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nFileCommentLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nDiskNumberStart, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nAttrInternal, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(lAttrExternal, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lLocalHeaderOffset, TYPE_INFO(ZipFile::ulong)) -STRUCT_INFO_END(ZipFile::CDRFileHeader) - -STRUCT_INFO_BEGIN(ZipFile::LocalFileHeader) -STRUCT_VAR_INFO(lSignature, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nVersionNeeded, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nFlags, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nMethod, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nLastModTime, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nLastModDate, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(desc, TYPE_INFO(ZipFile::DataDescriptor)) -STRUCT_VAR_INFO(nFileNameLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nExtraFieldLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_INFO_END(ZipFile::LocalFileHeader) - -STRUCT_INFO_BEGIN(ZipFile::ExtraFieldHeader) -STRUCT_VAR_INFO(headerID, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(dataSize, TYPE_INFO(ZipFile::ushort)) -STRUCT_INFO_END(ZipFile::ExtraFieldHeader) - -STRUCT_INFO_BEGIN(ZipFile::ExtraNTFSHeader) -STRUCT_VAR_INFO(reserved, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(attrTag, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(attrSize, TYPE_INFO(ZipFile::ushort)) -STRUCT_INFO_END(ZipFile::ExtraNTFSHeader) - -STRUCT_INFO_BEGIN(ZipFile::ExtraZIP64Data) -STRUCT_VAR_INFO(lSizeUncompressed, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(lSizeCompressed, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(lLocalHeaderOffset, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(nDiskNumberStart, TYPE_INFO(ZipFile::ulong)) -STRUCT_INFO_END(ZipFile::ExtraZIP64Data) - - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_INFO_H diff --git a/Code/Tools/CryCommonTools/ZipDir/zipdirstructures.h b/Code/Tools/CryCommonTools/ZipDir/zipdirstructures.h deleted file mode 100644 index dac298c90c..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/zipdirstructures.h +++ /dev/null @@ -1,426 +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. - -// This file contains only the support definitions for CZipDir class -// implementation. This it to unload the ZipDir.h from secondary stuff. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRSTRUCTURES_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRSTRUCTURES_H -#pragma once - -#include - -namespace ZipDir -{ - // possible errors occuring during the method execution - // to avoid clushing with the global Windows defines, we prefix these with ZD_ - enum ErrorEnum - { - ZD_ERROR_SUCCESS = 0, - ZD_ERROR_IO_FAILED, - ZD_ERROR_UNEXPECTED, - ZD_ERROR_UNSUPPORTED, - ZD_ERROR_INVALID_SIGNATURE, - ZD_ERROR_ZIP_FILE_IS_CORRUPT, - ZD_ERROR_DATA_IS_CORRUPT, - ZD_ERROR_NO_CDR, - ZD_ERROR_CDR_IS_CORRUPT, - ZD_ERROR_NO_MEMORY, - ZD_ERROR_VALIDATION_FAILED, - ZD_ERROR_CRC32_CHECK, - ZD_ERROR_ZLIB_FAILED, - ZD_ERROR_ZLIB_CORRUPTED_DATA, - ZD_ERROR_ZLIB_NO_MEMORY, - ZD_ERROR_CORRUPTED_DATA, - ZD_ERROR_INVALID_CALL, - ZD_ERROR_NOT_IMPLEMENTED, - ZD_ERROR_FILE_NOT_FOUND, - ZD_ERROR_DIR_NOT_FOUND, - ZD_ERROR_NAME_TOO_LONG, - ZD_ERROR_INVALID_PATH, - ZD_ERROR_FILE_ALREADY_EXISTS - }; - - // the error describes the reason of the error, as well as the error code, line of code where it happened etc. - struct Error - { - Error(ErrorEnum _nError, const char* _szDescription, const char* _szFunction, const char* _szFile, unsigned _nLine) - : nError(_nError) - , m_szDescription(_szDescription) - , szFunction(_szFunction) - , szFile(_szFile) - , nLine(_nLine) - { - } - - ErrorEnum nError; - const char* getError(); - - const char* getDescription() {return m_szDescription; } - const char* szFunction, * szFile; - unsigned nLine; - protected: - // the description of the error; if needed, will be made as a dynamic string - const char* m_szDescription; - }; - - //#define THROW_ZIPDIR_ERROR(ZD_ERR,DESC) throw Error (ZD_ERR, DESC, __FUNCTION__, __FILE__, __LINE__) - //#define THROW_ZIPDIR_ERROR(ZD_ERR,DESC) CryWarning( VALIDATOR_MODULE_SYSTEM,VALIDATOR_WARNING,DESC ) - -#define THROW_ZIPDIR_ERROR(ZD_ERR, DESC) - - struct EncryptionKey - { - uint32 key[4]; - - explicit EncryptionKey(const uint32 data[4]) - { - memcpy(key, data, sizeof(key)); - } - - EncryptionKey() - { - memset(key, 0, sizeof(key)); - } - }; - - // possible initialization methods - enum InitMethodEnum - { - // initialize as fast as possible, with minimal validation - ZD_INIT_FAST, - // after initialization, scan through all file headers, precache the actual file data offset values and validate the headers - ZD_INIT_FULL, - // scan all file headers and try to decompress the data, searching for corrupted files - ZD_INIT_VALIDATE, - // maximum level of validation, checks for integrity of the archive - ZD_INIT_VALIDATE_MAX = ZD_INIT_VALIDATE - }; - - typedef void* (* FnAlloc) (void* pUserData, unsigned nItems, unsigned nSize); - typedef void (* FnFree) (void* pUserData, void* pAddress); - - ////////////////////////////////////////////////////////////////////////// - // This structure contains the pointers to functions for memory management - // by default, it's initialized to default malloc/free -#if 0 - struct Allocator - { - FnAlloc fnAlloc; - FnFree fnFree; - void* pOpaque; - - static void* DefaultAlloc (void*, unsigned nItems, unsigned nSize) - { - return malloc (nItems * nSize); - } - - static void DefaultFree (void*, void* pAddress) - { - free (pAddress); - } - - void* Alloc (unsigned nItems, unsigned nSize) - { - return this->fnAlloc(this->pOpaque, nItems, nSize); - } - - void Free (void* pAddress) - { - this->fnFree (this->pOpaque, pAddress); - } - - // constructs the allocator object; by default, the stdlib functions are used - Allocator (FnAlloc fnAllocIn = DefaultAlloc, FnFree fnFreeIn = DefaultFree, void* pOpaqueIn = NULL) - : fnAlloc(fnAllocIn) - , fnFree (fnFreeIn) - , pOpaque(pOpaqueIn) - { - } - }; -#endif - // instance of this class just releases the memory when it's destructed - struct SmartHeapPtr - { - SmartHeapPtr() - : m_pAddress(NULL) - { - } - ~SmartHeapPtr() - { - Release(); - } - - void Attach (void* p) - { - Release(); - m_pAddress = p; - } - - void* Detach() - { - void* p = m_pAddress; - m_pAddress = NULL; - return p; - } - - void Release() - { - if (m_pAddress) - { - free(m_pAddress); - m_pAddress = NULL; - } - } - protected: - // the pointer to free - void* m_pAddress; - }; - - typedef SmartHeapPtr SmartPtr; - - // Uncompresses raw (without wrapping) data that is compressed with method 8 (deflated) in the Zip file - // returns one of the Z_* errors (Z_OK upon success) - extern int ZipRawUncompress (void* pUncompressed, unsigned long* pDestSize, const void* pCompressed, unsigned long nSrcSize); - - // compresses the raw data into raw data. The buffer for compressed data itself with the heap passed. Uses method 8 (deflate) - // returns one of the Z_* errors (Z_OK upon success), and the size in *pDestSize. the pCompressed buffer must be at least nSrcSize*1.001+12 size - - extern int ZipRawCompress (const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, int nLevel); - extern int ZipRawCompressZSTD(const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, int nLevel); - extern int ZipRawCompressLZ4(const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, int nLevel); - - //returns an estimate of the size of the data when compressed - extern int GetCompressedSizeEstimate(unsigned long uncompressedSize, CompressionCodec::Codec codec = CompressionCodec::Codec::ZLIB); - - enum class ValidationResult - { - OK = 0, - SIZE_MISMATCH, - DATA_CORRUPTED, - DATA_NO_MATCH - }; - //decompresses a zstd blob and compares with the original - returns true if original and uncompressed data match - ValidationResult ValidateZSTDCompressedDataWithOriginalData(const void* pUncompressed, unsigned long uncompressedSize, const void* pCompressed, unsigned long compressedSize); - - ////////////////////////////////////////////////////////////////////////// - struct SExtraZipFileData - { - SExtraZipFileData() - : nLastModifyTime(0) {} - - uint64 nLastModifyTime; - }; - - // this is the record about the file in the Zip file. - struct FileEntry - { - enum - { - INVALID_DATA_OFFSET = 0xFFFFFFFF - }; - - ZipFile::DataDescriptor desc; - ZipFile::ulong nFileHeaderOffset; // offset of the local file header - ZipFile::ulong nFileDataOffset; // offset of the packed info inside the file; NOTE: this can be INVALID_DATA_OFFSET, if not calculated yet! - ZipFile::ushort nMethod; // the method of compression (0 if no compression/store) - ZipFile::ushort nNameOffset; // offset of the file name in the name pool for the directory - - // the file modification times - ZipFile::ushort nLastModTime; - ZipFile::ushort nLastModDate; - - uint64 nNTFS_LastModifyTime; - - // the offset to the start of the next file's header - this - // can be used to calculate the available space in zip file - ZipFile::ulong nEOFOffset; - const char* szOriginalFileName; // original filename (for CacheRW) - - FileEntry() - : nFileHeaderOffset(INVALID_DATA_OFFSET) - , szOriginalFileName(0){} - FileEntry(const ZipFile::CDRFileHeader& header, const SExtraZipFileData& extra); - - bool IsInitialized () - { - // structure marked as non-initialized should have nFileHeaderOffset == INVALID_DATA_OFFSET - return nFileHeaderOffset != INVALID_DATA_OFFSET; - } - // returns the name of this file, given the pointer to the name pool - const char* GetName(const char* pNamePool) const - { - return pNamePool + nNameOffset; - } - - // sets the current time to modification time - // calculates CRC32 for the new data - void OnNewFileData(void* pUncompressed, unsigned nSize, unsigned nCompressedSize, unsigned nCompressionMethod, bool bContinuous); - - uint64 GetModificationTime(); - void SetFromFileTimeNTFS(int64 timestamp); - bool CompareFileTimeNTFS(int64 timestamp); - }; - - // tries to refresh the file entry from the given file (reads fromthere if needed) - // returns the error code if the operation was impossible to complete - extern ErrorEnum Refresh (FILE* f, FileEntry* pFileEntry, bool encrpytedHeaders); - - // writes into the file local header - without Extra data - // puts the new offset to the file data to the file entry - // in case of error can put INVALID_DATA_OFFSET into the data offset field of file entry - extern ErrorEnum WriteLocalHeader (FILE* f, FileEntry* pFileEntry, const char* szRelativePath, bool encrypt); - - // conversion routines for the date/time fields used in Zip - extern ZipFile::ushort DOSDate(tm*); - extern ZipFile::ushort DOSTime(tm*); - - extern const char* DOSTimeCStr(ZipFile::ushort nTime); - extern const char* DOSDateCStr(ZipFile::ushort nTime); - - struct DirHeader; - // this structure represents a subdirectory descriptor in the directory record. - // it points to the actual directory info (list of its subdirs and files), as well - // as on its name - struct DirEntry - { - ZipFile::ulong nDirHeaderOffset;// offset, in bytes, relative to this object, of the actual directory record header - ZipFile::ulong nNameOffset; // offset of the dir name in the name pool of the parent directory - // returns the name of this directory, given the pointer to the name pool of hte parent directory - const char* GetName(const char* pNamePool) const - { - return pNamePool + nNameOffset; - } - - // returns the pointer to the actual directory record. - // call this function only for the actual structure instance contained in a directory record and - // followed by the other directory records - const DirHeader* GetDirectory () const - { - return (const DirHeader*)(((const char*)this) + nDirHeaderOffset); - } - DirHeader* GetDirectory () - { - return (DirHeader*)(((char*)this) + nDirHeaderOffset); - } - }; - - // this is the head of the directory record - // the name pool follows straight the directory and file entries. - struct DirHeader - { - ZipFile::ushort numDirs; // number of directory entries - DirEntry structures - ZipFile::ushort numFiles; // number of file entries - FileEntry structures - - // returns the pointer to the name pool that follows this object - // you can only call this method for the structure instance actually followed by the dir record - const char* GetNamePool() const - { - return ((char*)(this + 1)) + (size_t)this->numDirs * sizeof(DirEntry) + (size_t)this->numFiles * sizeof(FileEntry); - } - char* GetNamePool() - { - return ((char*)(this + 1)) + (size_t)this->numDirs * sizeof(DirEntry) + (size_t)this->numFiles * sizeof(FileEntry); - } - - // returns the pointer to the i-th directory - // call this only for the actual instance of the structure at the head of dir record - const DirEntry* GetSubdirEntry(unsigned i) const - { - assert (i < numDirs); - return ((const DirEntry*)(this + 1)) + i; - } - DirEntry* GetSubdirEntry(unsigned i) - { - assert (i < numDirs); - return ((DirEntry*)(this + 1)) + i; - } - - // returns the pointer to the i-th file - // call this only for the actual instance of the structure at the head of dir record - const FileEntry* GetFileEntry (unsigned i) const - { - assert (i < numFiles); - return (const FileEntry*)(((const DirEntry*)(this + 1)) + numDirs) + i; - } - FileEntry* GetFileEntry (unsigned i) - { - assert (i < numFiles); - return (FileEntry*)(((DirEntry*)(this + 1)) + numDirs) + i; - } - - // finds the subdirectory entry by the name, using the names from the name pool - // assumes: all directories are sorted in alphabetical order. - // case-sensitive (must be lower-case if case-insensitive search in Win32 is performed) - DirEntry* FindSubdirEntry(const char* szName); - - // finds the file entry by the name, using the names from the name pool - // assumes: all directories are sorted in alphabetical order. - // case-sensitive (must be lower-case if case-insensitive search in Win32 is performed) - FileEntry* FindFileEntry(const char* szName); - }; - - // this is the sorting predicate for directory entries - struct DirEntrySortPred - { - DirEntrySortPred (const char* pNamePool) - : m_pNamePool (pNamePool) - { - } - - bool operator () (const FileEntry& left, const FileEntry& right) const - { - return strcmp(left.GetName(m_pNamePool), right.GetName(m_pNamePool)) < 0; - } - - bool operator () (const FileEntry& left, const char* szRight) const - { - return strcmp(left.GetName(m_pNamePool), szRight) < 0; - } - - bool operator () (const char* szLeft, const FileEntry& right) const - { - return strcmp(szLeft, right.GetName(m_pNamePool)) < 0; - } - - bool operator () (const DirEntry& left, const DirEntry& right) const - { - return strcmp(left.GetName(m_pNamePool), right.GetName(m_pNamePool)) < 0; - } - - bool operator () (const DirEntry& left, const char* szName) const - { - return strcmp(left.GetName(m_pNamePool), szName) < 0; - } - - bool operator () (const char* szLeft, const DirEntry& right) const - { - return strcmp(szLeft, right.GetName(m_pNamePool)) < 0; - } - - const char* m_pNamePool; - }; - - inline void tolower (string& str) - { - for (size_t i = 0; i < str.length(); ++i) - { - const_cast(str[i]) = ::tolower(str[i]); - } - } - - void Encrypt(char* buffer, size_t size, const EncryptionKey& key); - void Decrypt(char* buffer, size_t size, const EncryptionKey& key); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRSTRUCTURES_H diff --git a/Code/Tools/CryCommonTools/crycommontools_files.cmake b/Code/Tools/CryCommonTools/crycommontools_files.cmake index d68c49836a..204a65f907 100644 --- a/Code/Tools/CryCommonTools/crycommontools_files.cmake +++ b/Code/Tools/CryCommonTools/crycommontools_files.cmake @@ -10,45 +10,6 @@ # set(FILES - PakSystem.cpp - TempFilePakExtraction.cpp - IPakSystem.h - PakSystem.h - PakXmlFileBufferSource.h - TempFilePakExtraction.h - FileUtil.cpp - PathHelpers.cpp StringHelpers.cpp - FileUtil.h - MathHelpers.h - PathHelpers.h - PropertyHelpers.h - PropertyHelpers.cpp - SimpleStringPool.h - StealingThreadPool.cpp - StealingThreadPool.h StringHelpers.h - ThreadUtils.cpp - ZipDir/ZipDirCache.cpp - ZipDir/ZipDirCacheFactory.cpp - ZipDir/ZipDirCacheRW.cpp - ZipDir/ZipDirFind.cpp - ZipDir/ZipDirFindRW.cpp - ZipDir/ZipDirList.cpp - ZipDir/ZipDirStructures.cpp - ZipDir/ZipDirTree.cpp - ThreadUtils.h - ZipDir/ZipDir.h - ZipDir/ZipDirCache.h - ZipDir/ZipDirCacheFactory.h - ZipDir/ZipDirCacheRW.h - ZipDir/ZipDirFind.h - ZipDir/ZipDirFindRW.h - ZipDir/ZipDirList.h - ZipDir/zipdirstructures.h - ZipDir/ZipDirTree.h - ZipDir/ZipFile.h - ZipDir/ZipFileFormat.h - ZipDir/ZipFileFormat_info.h - SuffixUtil.h ) diff --git a/Code/Tools/CryCommonTools/crycommontools_tests_files.cmake b/Code/Tools/CryCommonTools/crycommontools_tests_files.cmake deleted file mode 100644 index 13f6d90d3c..0000000000 --- a/Code/Tools/CryCommonTools/crycommontools_tests_files.cmake +++ /dev/null @@ -1,15 +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 - UnitTests/PathHelpersUnitTests.cpp - UnitTests/StringHelpersUnitTests.cpp -) diff --git a/Code/Tools/CryCommonTools/zlibstatd64.lib b/Code/Tools/CryCommonTools/zlibstatd64.lib deleted file mode 100644 index 779712e946..0000000000 --- a/Code/Tools/CryCommonTools/zlibstatd64.lib +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9d9f51c3e75a4e80f45ba176511a84257146d6bc7c61f0cd582343544fd30e7c -size 277480 diff --git a/Code/Tools/CryXML/CMakeLists.txt b/Code/Tools/CryXML/CMakeLists.txt deleted file mode 100644 index a154fb6bd5..0000000000 --- a/Code/Tools/CryXML/CMakeLists.txt +++ /dev/null @@ -1,32 +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. -# - -if (NOT PAL_TRAIT_BUILD_HOST_TOOLS) - return() -endif() -ly_add_target( - NAME CryXML MODULE - NAMESPACE Legacy - FILES_CMAKE - cryxml_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - . - COMPILE_DEFINITIONS - PRIVATE - CRYTOOLS - RESOURCE_COMPILER - BUILD_DEPENDENCIES - PRIVATE - 3rdParty::expat - Legacy::CryCommon - Legacy::CryCommonTools -) diff --git a/Code/Tools/CryXML/CryXML.cpp b/Code/Tools/CryXML/CryXML.cpp deleted file mode 100644 index 597c751b0d..0000000000 --- a/Code/Tools/CryXML/CryXML.cpp +++ /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 : Defines the entry point for the DLL application. - - -#include "CryXML_precompiled.h" -#include "CryAssert_impl.h" -#include "ICryXML.h" -#include "XMLSerializer.h" -#include -#include - -class CryXML - : public ICryXML -{ -public: - CryXML(); - virtual void AddRef(); - virtual void Release(); - virtual IXMLSerializer* GetXMLSerializer(); - -private: - int nRefCount; - XMLSerializer serializer; -}; - -static CryXML* s_pCryXML = nullptr; - -#if defined(AZ_PLATFORM_WINDOWS) && !defined(AZ_MONOLITHIC_BUILD) -BOOL APIENTRY DllMain([[maybe_unused]] HANDLE hModule, [[maybe_unused]] DWORD ul_reason_for_call, [[maybe_unused]] LPVOID lpReserved) -{ - return TRUE; -} -#endif - -extern "C" DLL_EXPORT ICryXML * __stdcall GetICryXML() -{ - PREVENT_MODULE_AND_ENVIRONMENT_SYMBOL_STRIPPING - - if (!s_pCryXML) - { - s_pCryXML = new CryXML; - } - return s_pCryXML; -} - -CryXML::CryXML() - : nRefCount(0) -{ -} - -void CryXML::AddRef() -{ - ++this->nRefCount; -} - -void CryXML::Release() -{ - --this->nRefCount; - if (this->nRefCount == 0) - { - if (this == s_pCryXML) - { - s_pCryXML = nullptr; - } - delete this; - } -} - -IXMLSerializer* CryXML::GetXMLSerializer() -{ - return &this->serializer; -} - - -// STLPort requires folowing functions defined: - -// when using STL Port _STLP_DEBUG and _STLP_DEBUG_TERMINATE - avoid actually -// crashing (default terminator seems to kill the thread, which isn't nice). -#ifdef _STLP_DEBUG_TERMINATE -void __stl_debug_terminate(void) -{ - assert(0 && "STL Debug Error"); -} -#endif -#ifdef _STLP_DEBUG_MESSAGE -void __stl_debug_message(const char* format_str, ...) -{ - va_list __args; - va_start(__args, format_str); - vprintf(format_str, __args); - va_end(__args); -} -#endif //_STLP_DEBUG_MESSAGE diff --git a/Code/Tools/CryXML/CryXML.def b/Code/Tools/CryXML/CryXML.def deleted file mode 100644 index 6275474eab..0000000000 --- a/Code/Tools/CryXML/CryXML.def +++ /dev/null @@ -1,3 +0,0 @@ -LIBRARY CryXML -EXPORTS - GetICryXML @1 diff --git a/Code/Tools/CryXML/CryXML_precompiled.cpp b/Code/Tools/CryXML/CryXML_precompiled.cpp deleted file mode 100644 index 8bb231ffd1..0000000000 --- a/Code/Tools/CryXML/CryXML_precompiled.cpp +++ /dev/null @@ -1,14 +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 "CryXML_precompiled.h" diff --git a/Code/Tools/CryXML/CryXML_precompiled.h b/Code/Tools/CryXML/CryXML_precompiled.h deleted file mode 100644 index b7f48067b1..0000000000 --- a/Code/Tools/CryXML/CryXML_precompiled.h +++ /dev/null @@ -1,32 +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. - -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// -#pragma once - -#include - -#define CRY_ASSERT(condition) assert(condition) -#define CRY_ASSERT_TRACE(condition, message) assert(condition) -#define CRY_ASSERT_MESSAGE(condition, message) assert(condition) - -// Define this to prevent including CryAssert (there is no proper hook for turning this off, like the above). -#define CRYINCLUDE_CRYCOMMON_CRYASSERT_H - -#define CRY_STRING -#include - -#include "Cry_Math.h" diff --git a/Code/Tools/CryXML/ICryXML.h b/Code/Tools/CryXML/ICryXML.h deleted file mode 100644 index fddc95e60e..0000000000 --- a/Code/Tools/CryXML/ICryXML.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_CRYXML_ICRYXML_H -#define CRYINCLUDE_CRYXML_ICRYXML_H -#pragma once - - -class IXMLSerializer; - -class ICryXML -{ -public: - virtual ~ICryXML() = default; - virtual void AddRef() = 0; - virtual void Release() = 0; - virtual IXMLSerializer* GetXMLSerializer() = 0; -}; - -// Prototype for the function that is exported by the DLL - use this function to -// get a pointer to an ICryXML object. The function is exported by name as GetICryXML(). -typedef ICryXML* (* FnGetICryXML)(); - -#endif // CRYINCLUDE_CRYXML_ICRYXML_H diff --git a/Code/Tools/CryXML/IXMLSerializer.h b/Code/Tools/CryXML/IXMLSerializer.h deleted file mode 100644 index 44347beb5b..0000000000 --- a/Code/Tools/CryXML/IXMLSerializer.h +++ /dev/null @@ -1,68 +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_CRYXML_IXMLSERIALIZER_H -#define CRYINCLUDE_CRYXML_IXMLSERIALIZER_H -#pragma once - - -#include "IXml.h" -#include -class IXMLDataSink; -class IXMLDataSource; - -struct IXmlBufferSource -{ - virtual int Read(void* buffer, int size) const = 0; -}; - -class FileXmlBufferSource - : public IXmlBufferSource -{ -public: - FileXmlBufferSource(const char* path) - { - file = nullptr; - azfopen(&file, path, "r"); - } - ~FileXmlBufferSource() - { - if (file) - { - std::fclose(file); - } - } - - virtual int Read(void* buffer, int size) const - { - if (!file) - { - return 0; - } - return check_cast(std::fread(buffer, 1, size, file)); - } - -private: - mutable std::FILE* file; -}; - -class IXMLSerializer -{ -public: - virtual XmlNodeRef CreateNode(const char* tag) = 0; - virtual bool Write(XmlNodeRef root, const char* szFileName) = 0; - - virtual XmlNodeRef Read(const IXmlBufferSource& source, bool bRemoveNonessentialSpacesFromContent, int nErrorBufferSize, char* szErrorBuffer) = 0; -}; - -#endif // CRYINCLUDE_CRYXML_IXMLSERIALIZER_H diff --git a/Code/Tools/CryXML/XML/xml.cpp b/Code/Tools/CryXML/XML/xml.cpp deleted file mode 100644 index 4c117b54c7..0000000000 --- a/Code/Tools/CryXML/XML/xml.cpp +++ /dev/null @@ -1,1400 +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 "CryXML_precompiled.h" - -//#define _CRT_SECURE_NO_DEPRECATE 1 -//#define _CRT_NONSTDC_NO_DEPRECATE -#include - -#define XML_STATIC -#include -#include "xml.h" -#include "../IXMLSerializer.h" -#include "Util.h" -#include -#include -#include - -#include -#include -#include -#include - -///////////////////////////////////////////////////////////////////// -// String pool implementation (from expat). -///////////////////////////////////////////////////////////////////// -class CSimpleStringPool -{ -public: - enum - { - STD_BLOCK_SIZE = 4096 - }; - struct BLOCK - { - BLOCK* next; - int size; - char s[1]; - }; - unsigned int m_blockSize; - BLOCK* m_blocks; - const char* m_end; - char* m_ptr; - char* m_start; - int nUsedSpace; - int nUsedBlocks; - - CSimpleStringPool() - { - m_blockSize = STD_BLOCK_SIZE; - m_blocks = 0; - m_start = 0; - m_ptr = 0; - m_end = 0; - nUsedSpace = 0; - nUsedBlocks = 0; - } - ~CSimpleStringPool() - { - BLOCK* p = m_blocks; - while (p) - { - BLOCK* temp = p->next; - //nFree++; - CryModuleFree(p); - p = temp; - } - m_blocks = 0; - m_ptr = 0; - m_start = 0; - m_end = 0; - } - void SetBlockSize(unsigned int nBlockSize) - { - if (nBlockSize > 1024 * 1024) - { - nBlockSize = 1024 * 1024; - } - unsigned int size = 512; - while (size < nBlockSize) - { - size *= 2; - } - - m_blockSize = size; - } - char* Append(const char* ptr, int nStrLen) - { - char* ret = m_ptr; - if (m_ptr && nStrLen + 1 < (m_end - m_ptr)) - { - memcpy(m_ptr, ptr, nStrLen); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - } - else - { - int nNewBlockSize = Util::getMax(nStrLen + 1, (int)m_blockSize); - AllocBlock(nNewBlockSize); - memcpy(m_ptr, ptr, nStrLen); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - ret = m_start; - } - nUsedSpace += nStrLen; - return ret; - } - char* ReplaceString(const char* str1, const char* str2) - { - int nStrLen1 = strlen(str1); - int nStrLen2 = strlen(str2); - - // undo ptr1 add. - if (m_ptr != m_start) - { - m_ptr = m_ptr - nStrLen1 - 1; - } - - assert(m_ptr == str1); - - int nStrLen = nStrLen1 + nStrLen2; - - char* ret = m_ptr; - if (m_ptr && nStrLen + 1 < (m_end - m_ptr)) - { - memcpy(m_ptr, str1, nStrLen1); - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - } - else - { - int nNewBlockSize = Util::getMax(nStrLen + 1, (int)m_blockSize); - if (m_ptr == m_start) - { - ReallocBlock(nNewBlockSize * 2); // Reallocate current block. - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - } - else - { - AllocBlock(nNewBlockSize); - memcpy(m_ptr, str1, nStrLen1); - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - } - - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - ret = m_start; - } - nUsedSpace += nStrLen; - return ret; - } -private: - void AllocBlock(int blockSize) - { - //nMallocs++; - BLOCK* pBlock = (BLOCK*)CryModuleMalloc(offsetof(BLOCK, s) + blockSize * sizeof(char)); - if (!pBlock) - { - // no memory. - //CryError( "Out of memory" ); - m_ptr = 0; - m_start = 0; - m_end = 0; - return; - } - pBlock->size = blockSize; - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + blockSize; - nUsedBlocks++; - } - void ReallocBlock(int blockSize) - { - BLOCK* pThisBlock = m_blocks; - BLOCK* pPrevBlock = m_blocks->next; - m_blocks = pPrevBlock; - //nMallocs++; - BLOCK* pBlock = (BLOCK*)CryModuleRealloc(pThisBlock, offsetof(BLOCK, s) + blockSize * sizeof(char)); - if (!pBlock) - { - // no memory. - //CryError( "Out of memory" ); - m_ptr = 0; - m_start = 0; - m_end = 0; - return; - } - pBlock->size = blockSize; - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + blockSize; - } -}; - -////////////////////////////////////////////////////////////////////////// -static int __cdecl ascii_stricmp(const char* dst, const char* src) -{ - int f, l; - do - { - if (((f = (unsigned char)(*(dst++))) >= 'A') && (f <= 'Z')) - { - f -= 'A' - 'a'; - } - if (((l = (unsigned char)(*(src++))) >= 'A') && (l <= 'Z')) - { - l -= 'A' - 'a'; - } - } - while (f && (f == l)); - return(f - l); -} - -////////////////////////////////////////////////////////////////////////// -XmlStrCmpFunc g_pXmlStrCmp = &ascii_stricmp; - -////////////////////////////////////////////////////////////////////////// -class CXmlStringData - : public IXmlStringData -{ -public: - int m_nRefCount; - XmlString m_string; - - CXmlStringData() { m_nRefCount = 0; } - virtual void AddRef() { ++m_nRefCount; } - virtual void Release() - { - if (--m_nRefCount <= 0) - { - delete this; - } - } - - virtual const char* GetString() { return m_string.c_str(); }; - virtual size_t GetStringLength() { return m_string.size(); }; -}; - -class CXmlStringPool - : public IXmlStringPool -{ -public: - char* AddString(const char* str) { return m_stringPool.Append(str, (int)strlen(str)); } -private: - CSimpleStringPool m_stringPool; -}; - -/** -****************************************************************************** -* CXmlNode implementation. -****************************************************************************** -*/ - -void CXmlNode::DeleteThis() -{ - delete this; -} - -CXmlNode::~CXmlNode() -{ - // Clear parent pointer from childs. - for (XmlNodes::const_iterator it = m_childs.begin(); it != m_childs.end(); ++it) - { - IXmlNode* node = *it; - ((CXmlNode*)node)->m_parent = 0; - } - m_pStringPool->Release(); -} - -CXmlNode::CXmlNode() -{ - m_tag = ""; - m_content = ""; - m_parent = 0; - m_nRefCount = 0; - m_pStringPool = 0; // must be changed later. -} - -CXmlNode::CXmlNode(const char* tag) -{ - m_content = ""; - m_parent = 0; - m_nRefCount = 0; - m_pStringPool = new CXmlStringPool; - m_pStringPool->AddRef(); - m_tag = m_pStringPool->AddString(tag); -} - -////////////////////////////////////////////////////////////////////////// -XmlNodeRef CXmlNode::createNode(const char* tag) -{ - CXmlNode* pNewNode = new CXmlNode; - pNewNode->m_pStringPool = m_pStringPool; - m_pStringPool->AddRef(); - pNewNode->m_tag = m_pStringPool->AddString(tag); - return XmlNodeRef(pNewNode); -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::setTag(const char* tag) -{ - m_tag = m_pStringPool->AddString(tag); -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::setContent(const char* str) -{ - m_content = str; -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::isTag(const char* tag) const -{ - return g_pXmlStrCmp(tag, m_tag) == 0; -} - -const char* CXmlNode::getAttr(const char* key) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - return svalue; - } - return ""; -} - -bool CXmlNode::getAttr(const char* key, const char** value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - *value = svalue; - return true; - } - else - { - *value = ""; - return false; - } -} - -bool CXmlNode::haveAttr(const char* key) const -{ - XmlAttrConstIter it = GetAttrConstIterator(key); - if (it != m_attributes.end()) - { - return true; - } - return false; -} - -void CXmlNode::delAttr(const char* key) -{ - XmlAttrIter it = GetAttrIterator(key); - if (it != m_attributes.end()) - { - m_attributes.erase(it); - } -} - -void CXmlNode::removeAllAttributes() -{ - m_attributes.clear(); -} - -void CXmlNode::setAttr(const char* key, const char* value) -{ - XmlAttrIter it = GetAttrIterator(key); - if (it == m_attributes.end()) - { - XmlAttribute tempAttr; - tempAttr.key = m_pStringPool->AddString(key); - tempAttr.value = m_pStringPool->AddString(value); - m_attributes.push_back(tempAttr); - // Sort attributes. - //std::sort( m_attributes.begin(),m_attributes.end() ); - } - else - { - // If already exist, override this member. - it->value = m_pStringPool->AddString(value); - } -} - -void CXmlNode::setAttr(const char* key, int value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%d", value); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, unsigned int value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%d", value); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, float value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g", value); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, double value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%.17g", value); - setAttr(key, str); -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::setAttr(const char* key, int64 value) -{ - char str[32]; - azsnprintf(str, sizeof(str), "%" PRId64, value); - setAttr(key, str); -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::setAttr(const char* key, uint64 value, bool useHexFormat) -{ - char str[32]; - if (useHexFormat) - { - azsnprintf(str, sizeof(str), "%" PRIX64, value); - } - else - { - azsnprintf(str, sizeof(str), "%" PRIu64, value); - } - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Ang3& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g,%g,%g", value.x, value.y, value.z); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Vec2& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g,%g", value.x, value.y); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Vec2d& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%.17g,%.17g", value.x, value.y); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Vec3& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g,%g,%g", value.x, value.y, value.z); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Vec3d& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%.17g,%.17g,%.17g", value.x, value.y, value.z); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Vec4& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g,%g,%g,%g", value.x, value.y, value.z, value.w); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Quat& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g,%g,%g,%g", value.w, value.v.x, value.v.y, value.v.z); - setAttr(key, str); -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::getAttr(const char* key, int& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - value = atoi(svalue); - return true; - } - return false; -} - -bool CXmlNode::getAttr(const char* key, unsigned int& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - value = strtoul(svalue, NULL, 10); - return true; - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::getAttr(const char* key, int64& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - azsscanf(svalue, "%" PRId64, &value); - return true; - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::getAttr(const char* key, uint64& value, bool useHexFormat) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - if (useHexFormat) - { - azsscanf(svalue, "%" PRIX64, &value); - } - else - { - azsscanf(svalue, "%" PRIu64, &value); - } - return true; - } - return false; -} - -bool CXmlNode::getAttr(const char* key, bool& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - value = atoi(svalue) != 0; - return true; - } - return false; -} - -bool CXmlNode::getAttr(const char* key, float& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - value = (float)atof(svalue); - return true; - } - return false; -} - -bool CXmlNode::getAttr(const char* key, double& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - value = atof(svalue); - return true; - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Ang3& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - float x, y, z; - if (azsscanf(svalue, "%f,%f,%f", &x, &y, &z) == 3) - { - value(x, y, z); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Vec2& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - float x, y; - if (azsscanf(svalue, "%f,%f", &x, &y) == 2) - { - value = Vec2(x, y); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Vec2d& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - double x, y; - if (azsscanf(svalue, "%lf,%lf", &x, &y) == 2) - { - value = Vec2d(x, y); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Vec3& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - float x, y, z; - if (azsscanf(svalue, "%f,%f,%f", &x, &y, &z) == 3) - { - value(x, y, z); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Vec4& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - float x, y, z, w; - if (azsscanf(svalue, "%f,%f,%f,%f", &x, &y, &z, &w) == 3) - { - value(x, y, z, w); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Vec3d& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - double x, y, z; - if (azsscanf(svalue, "%lf,%lf,%lf", &x, &y, &z) == 3) - { - value = Vec3d(x, y, z); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Quat& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - float w, x, y, z; - if (azsscanf(svalue, "%f,%f,%f,%f", &w, &x, &y, &z) == 4) - { - if (fabs(w) > VEC_EPSILON || fabs(x) > VEC_EPSILON || fabs(y) > VEC_EPSILON || fabs(z) > VEC_EPSILON) - { - //[AlexMcC|02.03.10] directly assign to members to avoid triggering the assert in Quat() with data from bad assets - value.w = w; - value.v = Vec3(x, y, z); - return value.IsValid(); - } - } - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::getAttr(const char* key, ColorB& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - unsigned int r, g, b, a = 255; - int numFound = azsscanf(svalue, "%u,%u,%u,%u", &r, &g, &b, &a); - if (numFound == 3 || numFound == 4) - { - // If we only found 3 values, a should be unchanged, and still be 255 - if (r < 256 && g < 256 && b < 256 && a < 256) - { - value = ColorB(r, g, b, a); - return true; - } - } - } - return false; -} - - -XmlNodeRef CXmlNode::findChild(const char* tag) const -{ - for (XmlNodes::const_iterator it = m_childs.begin(); it != m_childs.end(); ++it) - { - if ((*it)->isTag(tag)) - { - return *it; - } - } - return 0; -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::deleteChild(const char* tag) -{ - for (XmlNodes::iterator it = m_childs.begin(); it != m_childs.end(); ++it) - { - if ((*it)->isTag(tag)) - { - m_childs.erase(it); - return; - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::deleteChildAt(int nIndex) -{ - if (nIndex >= 0 && nIndex < (int)m_childs.size()) - { - m_childs.erase(m_childs.begin() + nIndex); - } -} - -//! Adds new child node. -void CXmlNode::addChild(const XmlNodeRef& node) -{ - assert(node != 0); - m_childs.push_back(node); - IXmlNode* n = node; - ((CXmlNode*)n)->m_parent = this; -}; - -void CXmlNode::setParent(const XmlNodeRef& inNewParent) -{ - // note, parent ptrs are not ref counted - IXmlNode* n = inNewParent; - m_parent = (CXmlNode*)n; -} - -void CXmlNode::insertChild(int inIndex, const XmlNodeRef& inNewChild) -{ - assert(inIndex >= 0 && inIndex <= getChildCount()); - assert(inNewChild != 0); - if (inIndex >= 0 && inIndex <= getChildCount() && inNewChild) - { - if (getChildCount() == 0) - { - addChild(inNewChild); - } - else - { - IXmlNode* pNode = ((IXmlNode*)inNewChild); - pNode->AddRef(); - m_childs.insert(m_childs.begin() + inIndex, pNode); - pNode->setParent(this); - } - } -} - -void CXmlNode::replaceChild(int inIndex, const XmlNodeRef& inNewChild) -{ - assert(inIndex >= 0 && inIndex < getChildCount()); - assert(inNewChild != 0); - if (inIndex >= 0 && inIndex < getChildCount() && inNewChild) - { - IXmlNode* wasChild = m_childs[inIndex]; - - if (wasChild->getParent() == this) - { - wasChild->setParent(XmlNodeRef()); // child is orphaned, will be freed by Release() below if this parent is last holding a reference to it - } - wasChild->Release(); - inNewChild->AddRef(); - m_childs[inIndex] = inNewChild; - inNewChild->setParent(this); - } -} - -XmlNodeRef CXmlNode::newChild(const char* tagName) -{ - XmlNodeRef node = createNode(tagName); - addChild(node); - return node; -} - -void CXmlNode::removeChild(const XmlNodeRef& node) -{ - XmlNodes::iterator it = std::find(m_childs.begin(), m_childs.end(), (IXmlNode*)node); - if (it != m_childs.end()) - { - m_childs.erase(it); - } -} - -void CXmlNode::removeAllChilds() -{ - m_childs.clear(); -} - -//! Get XML Node child nodes. -XmlNodeRef CXmlNode::getChild(int i) const -{ - assert(i >= 0 && i < (int)m_childs.size()); - return m_childs[i]; -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::copyAttributes(XmlNodeRef fromNode) -{ - IXmlNode* inode = fromNode; - CXmlNode* n = (CXmlNode*)inode; - if (n->m_pStringPool == m_pStringPool) - { - m_attributes = n->m_attributes; - } - else - { - m_attributes.resize(n->m_attributes.size()); - for (int i = 0; i < (int)n->m_attributes.size(); i++) - { - m_attributes[i].key = m_pStringPool->AddString(n->m_attributes[i].key); - m_attributes[i].value = m_pStringPool->AddString(n->m_attributes[i].value); - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::getAttributeByIndex(int index, const char** key, const char** value) -{ - XmlAttributes::iterator it = m_attributes.begin(); - if (it != m_attributes.end()) - { - std::advance(it, index); - if (it != m_attributes.end()) - { - *key = it->key; - *value = it->value; - return true; - } - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -XmlNodeRef CXmlNode::clone() -{ - CXmlNode* node = new CXmlNode; - node->m_pStringPool = m_pStringPool; - m_pStringPool->AddRef(); - node->m_tag = m_tag; - node->m_content = m_content; - // Clone attributes. - CXmlNode* n = (CXmlNode*)(IXmlNode*)node; - n->copyAttributes(this); - // Clone sub nodes. - for (XmlNodes::const_iterator it = m_childs.begin(); it != m_childs.end(); ++it) - { - XmlNodeRef child = (*it)->clone(); - node->addChild(child); - } - - return node; -} - -////////////////////////////////////////////////////////////////////////// -static void AddTabsToString(XmlString& xml, int level) -{ - static const char* tabs[] = { - "", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - }; - // Add tabs. - if (level < sizeof(tabs) / sizeof(tabs[0])) - { - xml += tabs[level]; - } - else - { - for (int i = 0; i < level; i++) - { - xml += " "; - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::IsValidXmlString(const char* str) const -{ - if (strcspn(str, "\"\'&><") == strlen(str)) - { - return true; - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -XmlString CXmlNode::MakeValidXmlString(const XmlString& instr) const -{ - XmlString str = instr; - - // check if str contains any invalid characters - str.replace("&", "&"); - str.replace("\"", """); - str.replace("\'", "'"); - str.replace("<", "<"); - str.replace(">", ">"); - - return str; -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::AddToXmlString(XmlString& xml, int level) const -{ - AddTabsToString(xml, level); - - // Begin Tag - if (m_attributes.empty()) - { - xml += "<"; - xml += m_tag; - if (*m_content == 0 && m_childs.empty()) - { - // Compact tag form. - xml += " />\n"; - return; - } - xml += ">"; - } - else - { - xml += "<"; - xml += m_tag; - xml += " "; - - // Put attributes. - for (XmlAttributes::const_iterator it = m_attributes.begin(); it != m_attributes.end(); ) - { - xml += it->key; - xml += "=\""; - if (IsValidXmlString(it->value)) - { - xml += it->value; - } - else - { - xml += MakeValidXmlString(it->value); - } - it++; - if (it != m_attributes.end()) - { - xml += "\" "; - } - else - { - xml += "\""; - } - } - if (*m_content == 0 && m_childs.empty()) - { - // Compact tag form. - xml += "/>\n"; - return; - } - xml += ">"; - } - - // Put node content. - if (IsValidXmlString(m_content)) - { - xml += m_content; - } - else - { - xml += MakeValidXmlString(m_content); - } - - if (m_childs.empty()) - { - xml += "\n"; - return; - } - - xml += "\n"; - - // Add sub nodes. - for (XmlNodes::const_iterator it = m_childs.begin(); it != m_childs.end(); ++it) - { - IXmlNode* node = *it; - ((CXmlNode*)node)->AddToXmlString(xml, level + 1); - } - - // Add tabs. - AddTabsToString(xml, level); - xml += "\n"; -} - -IXmlStringData* CXmlNode::getXMLData(int nReserveMem) const -{ - CXmlStringData* pStrData = new CXmlStringData; - pStrData->m_string.reserve(nReserveMem); - AddToXmlString(pStrData->m_string, 0); - return pStrData; -} - -XmlString CXmlNode::getXML(int level) const -{ - static XmlString xml; - xml = ""; - xml.reserve(6000000); - - AddToXmlString(xml, level); - return xml; -} - -bool CXmlNode::saveToFile(const char* fileName) -{ - XmlString xml = getXML(); - FILE* file = nullptr; - azfopen(&file, fileName, "wt"); - if (file) - { - const char* sxml = (const char*)xml; - fprintf(file, "%s", sxml); - fclose(file); - return true; - } - return false; -} - -/** -****************************************************************************** -* XmlParserImp class. -****************************************************************************** -*/ -class XmlParserImp - : public IXmlStringPool -{ -public: - explicit XmlParserImp(bool bRemoveNonessentialSpacesFromContent); - ~XmlParserImp(); - void beginParse(); - bool parse(const char* buffer, int bufLen); - XmlNodeRef endParse(XmlString& errorString); - - // Add new string to pool. - char* AddString(const char* str) { return m_stringPool.Append(str, (int)strlen(str)); } - //char* AddString( const char *str ) { return (char*)str; } - -protected: - void onStartElement(const char* tagName, const char** atts); - void onEndElement(const char* tagName); - void onRawData(const char* data); - - static void startElement(void* userData, const char* name, const char** atts) - { - ((XmlParserImp*)userData)->onStartElement(name, atts); - } - static void endElement(void* userData, const char* name) - { - ((XmlParserImp*)userData)->onEndElement(name); - } - static void characterData(void* userData, const char* s, int len) - { - char str[500000]; - if (len > sizeof(str) - 1) - { - assert(0); - len = sizeof(str) - 1; - } - memcpy(str, s, len); - str[len] = 0; - ((XmlParserImp*)userData)->onRawData(str); - } - - // First node will become root node. - std::vector nodeStack; - XmlNodeRef m_root; - - XML_Parser m_parser; - CSimpleStringPool m_stringPool; - bool m_bRemoveNonessentialSpacesFromContent; -}; - -/** -****************************************************************************** -* XmlParserImp -****************************************************************************** -*/ -void XmlParserImp::onStartElement(const char* tagName, const char** atts) -{ - XmlNodeRef parent; - CXmlNode* pCNode = new CXmlNode; - pCNode->m_pStringPool = this; - pCNode->m_pStringPool->AddRef(); - pCNode->m_tag = AddString(tagName); - - XmlNodeRef node = pCNode; - - if (!nodeStack.empty()) - { - parent = nodeStack.back(); - } - else - { - m_root = node; - } - nodeStack.push_back(node); - - if (parent) - { - parent->addChild(node); - } - - uint64 line = XML_GetCurrentLineNumber((XML_Parser)m_parser); - node->setLine(line > INT_MAX ? INT_MAX : (int)line); - - // Call start element callback. - int i = 0; - int numAttrs = 0; - while (atts[i] != 0) - { - numAttrs++; - i += 2; - } - if (numAttrs > 0) - { - i = 0; - pCNode->m_attributes.resize(numAttrs); - int nAttr = 0; - while (atts[i] != 0) - { - pCNode->m_attributes[nAttr].key = AddString(atts[i]); - pCNode->m_attributes[nAttr].value = AddString(atts[i + 1]); - nAttr++; - i += 2; - } - // Sort attributes. - //std::sort( pCNode->m_attributes.begin(),pCNode->m_attributes.end() ); - } -} - -void XmlParserImp::onEndElement([[maybe_unused]] const char* tagName) -{ - assert(!nodeStack.empty()); - if (!nodeStack.empty()) - { - nodeStack.pop_back(); - } -} - -void XmlParserImp::onRawData(const char* const data) -{ - if (data && data[0]) - { - CXmlNode* const node = (CXmlNode*)(IXmlNode*)nodeStack.back(); - - if (!m_bRemoveNonessentialSpacesFromContent) - { - // Implementation note: Skipping spaces in beginning (even although - // m_bRemoveNonessentialSpacesFromContent is false) allows us - // to avoid having lot of "space only" content nodes - if (node->m_content.empty()) - { - const size_t len = strlen(data); - const size_t spaceCount = strspn(data, "\r\n\t "); - - if (spaceCount < len) - { - node->m_content += &data[spaceCount]; - } - } - else - { - node->m_content += data; - } - } - else - { - const size_t len = strlen(data); - const size_t spaceCount = strspn(data, "\r\n\t "); - - if ((spaceCount > 0) && (!node->m_content.empty())) - { - node->m_content += " "; - } - - if (spaceCount < len) - { - node->m_content += &data[spaceCount]; - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -static void* custom_xml_malloc(size_t nSize) -{ - return CryModuleMalloc(nSize); -} -static void* custom_xml_realloc(void* p, size_t nSize) -{ - return CryModuleRealloc(p, nSize); -} -static void custom_xml_free(void* p) -{ - CryModuleFree(p); -} - -namespace CryXML_Internal -{ - XML_Memory_Handling_Suite memHandler; - XML_Memory_Handling_Suite* GetMemoryHandler() - { - memHandler.malloc_fcn = custom_xml_malloc; // CryModuleMalloc; - memHandler.realloc_fcn = custom_xml_realloc; // CryModuleRealloc; - memHandler.free_fcn = custom_xml_free; // CryModuleFree; - return &memHandler; - } -} - -XmlParserImp::XmlParserImp(bool bRemoveNonessentialSpacesFromContent) -{ - m_bRemoveNonessentialSpacesFromContent = bRemoveNonessentialSpacesFromContent; - - m_root = 0; - nodeStack.reserve(100); - - m_parser = XML_ParserCreate_MM(NULL, CryXML_Internal::GetMemoryHandler(), NULL); - - XML_SetUserData(m_parser, this); - XML_SetElementHandler(m_parser, startElement, endElement); - XML_SetCharacterDataHandler(m_parser, characterData); - XML_SetEncoding(m_parser, "utf-8"); -} - -XmlParserImp::~XmlParserImp() -{ - XML_ParserFree(m_parser); -} - -void XmlParserImp::beginParse() -{ - m_root = 0; - - m_stringPool.SetBlockSize(1 << 20); -} - -bool XmlParserImp::parse(const char* buffer, int bufLen) -{ - if (!XML_Parse(m_parser, buffer, (int)bufLen, 0)) - { - m_root = 0; - return false; - } - return true; -} - -XmlNodeRef XmlParserImp::endParse(XmlString& errorString) -{ - errorString = ""; - - if (!XML_Parse(m_parser, "", 0, 1)) - { - m_root = 0; - } - - if (!m_root) - { - const char* const errorText = XML_ErrorString(XML_GetErrorCode(m_parser)); - if (errorText) - { - errorString += "XML Error: "; - errorString += errorText; - // The following code is disabled by 'if (false)' because XML_GetCurrentLineNumber() - // XML_GetCurrentColumnNumber() return incorrect numbers. - // The issue (wrong numbers) might be fixed if/when we upgrade to a newer version - // of the Expat XML library (on 2014/02/26 CryEngine still uses expat version 1.95.2 - // from 2001/07/27, although the latest expat version is 2.1.0 from 2012/03/24). - if (false) - { - char s[64]; - azsprintf(s, " at line %d, column %d", (int)XML_GetCurrentLineNumber(m_parser), (int)XML_GetCurrentColumnNumber(m_parser)); - errorString += s; - } - } - } - - XmlNodeRef root = m_root; - m_root = 0; - return root; -} - -XmlParser::XmlParser(bool bRemoveNonessentialSpacesFromContent) -{ - m_pImpl = new XmlParserImp(bRemoveNonessentialSpacesFromContent); - m_pImpl->AddRef(); -} - -XmlParser::~XmlParser() -{ - m_pImpl->Release(); -} - -//! Parse xml file. -XmlNodeRef XmlParser::parse(const char* fileName) -{ - m_errorString = ""; - - std::vector buf; - auto pPak = GetISystem()->GetIPak(); - AZ::IO::HandleType file = pPak->FOpen(fileName, "rb"); - if (file) - { - pPak->FSeek(file, 0, SEEK_END); - int fileSize = pPak->FTell(file); - pPak->FSeek(file, 0, SEEK_SET); - buf.resize(fileSize); - pPak->FRead(&(buf[0]), fileSize, file); - pPak->FClose(file); - m_pImpl->parse(&buf[0], buf.size()); - return m_pImpl->endParse(m_errorString); - } - else - { - return XmlNodeRef(); - } -} - -//! Parse xml from memory buffer. -XmlNodeRef XmlParser::parseBuffer(const char* buffer) -{ - m_errorString = ""; - m_pImpl->beginParse(); - m_pImpl->parse(buffer, strlen(buffer)); - return m_pImpl->endParse(m_errorString); -} - -XmlNodeRef XmlParser::parseSource(const IXmlBufferSource* source) -{ - m_errorString = ""; - char buffer[40000]; - enum - { - bufferSize = sizeof(buffer) / sizeof(buffer[0]) - }; - m_pImpl->beginParse(); - int bytesRead = source->Read(buffer, bufferSize); - while (bytesRead) - { - if (!m_pImpl->parse(buffer, bytesRead)) - { - break; - } - bytesRead = source->Read(buffer, bufferSize); - } - return m_pImpl->endParse(m_errorString); -} diff --git a/Code/Tools/CryXML/XML/xml.h b/Code/Tools/CryXML/XML/xml.h deleted file mode 100644 index 8e9072acbf..0000000000 --- a/Code/Tools/CryXML/XML/xml.h +++ /dev/null @@ -1,471 +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_CRYXML_XML_XML_H -#define CRYINCLUDE_CRYXML_XML_XML_H -#pragma once - - -#include -#include -#include - -#include "IXml.h" - -struct IXmlBufferSource; - -struct IXmlStringPool -{ -public: - IXmlStringPool() { m_refCount = 0; } - virtual ~IXmlStringPool() {}; - void AddRef() { m_refCount++; }; - void Release() - { - if (--m_refCount <= 0) - { - delete this; - } - }; - virtual char* AddString(const char* str) = 0; -private: - int m_refCount; -}; - -/************************************************************************/ -/* XmlParser class, Parse xml and return root xml node if success. */ -/************************************************************************/ -class XmlParser -{ -public: - explicit XmlParser(bool bRemoveNonessentialSpacesFromContent); - ~XmlParser(); - - //! Parse xml file. - XmlNodeRef parse(const char* fileName); - - //! Parse xml from memory buffer. - XmlNodeRef parseBuffer(const char* buffer); - - XmlNodeRef parseSource(const IXmlBufferSource* source); - - const char* getErrorString() const { return m_errorString; } - -private: - XmlString m_errorString; - class XmlParserImp* m_pImpl; -}; - -// Compare function for string comparasion, can be strcmp or _stricmp -typedef int (__cdecl * XmlStrCmpFunc)(const char* str1, const char* str2); -extern XmlStrCmpFunc g_pXmlStrCmp; - -////////////////////////////////////////////////////////////////////////// -// XmlAttribute class -////////////////////////////////////////////////////////////////////////// -struct XmlAttribute -{ - const char* key; - const char* value; - - bool operator<(const XmlAttribute& attr) const { return g_pXmlStrCmp(key, attr.key) < 0; } - bool operator>(const XmlAttribute& attr) const { return g_pXmlStrCmp(key, attr.key) > 0; } - bool operator==(const XmlAttribute& attr) const { return g_pXmlStrCmp(key, attr.key) == 0; } - bool operator!=(const XmlAttribute& attr) const { return g_pXmlStrCmp(key, attr.key) != 0; } -}; - -//! Xml node attributes class. -typedef std::vector XmlAttributes; -typedef XmlAttributes::iterator XmlAttrIter; -typedef XmlAttributes::const_iterator XmlAttrConstIter; - -/** -****************************************************************************** -* CXmlNode class -* Never use CXmlNode directly instead use reference counted XmlNodeRef. -****************************************************************************** -*/ - -class CXmlNode - : public IXmlNode -{ -public: - //! Constructor. - CXmlNode(); - CXmlNode(const char* tag); - //! Destructor. - ~CXmlNode(); - - virtual void DeleteThis(); - - //! Create new XML node. - XmlNodeRef createNode(const char* tag); - - //! Get XML node tag. - const char* getTag() const { return m_tag; }; - void setTag(const char* tag); - - //! Return true if given tag equal to node tag. - bool isTag(const char* tag) const; - - //! Get XML Node attributes. - virtual int getNumAttributes() const { return (int)m_attributes.size(); }; - //! Return attribute key and value by attribute index. - virtual bool getAttributeByIndex(int index, const char** key, const char** value); - - virtual void copyAttributes(XmlNodeRef fromNode); - - //! Get XML Node attribute for specified key. - const char* getAttr(const char* key) const; - - //! Get XML Node attribute for specified key. - // Returns true if the attribute existes, alse otherwise. - bool getAttr(const char* key, const char** value) const; - - //! Check if attributes with specified key exist. - bool haveAttr(const char* key) const; - - //! Creates new xml node and add it to childs list. - XmlNodeRef newChild(const char* tagName); - - //! Adds new child node. - void addChild(const XmlNodeRef& node); - //! Remove child node. - void removeChild(const XmlNodeRef& node); - - void insertChild(int nIndex, const XmlNodeRef& node); - void replaceChild(int nIndex, const XmlNodeRef& node); - - //! Remove all child nodes. - void removeAllChilds(); - - //! Get number of child XML nodes. - int getChildCount() const { return (int)m_childs.size(); }; - - //! Get XML Node child nodes. - XmlNodeRef getChild(int i) const; - - //! Find node with specified tag. - XmlNodeRef findChild(const char* tag) const; - void deleteChild(const char* tag); - void deleteChildAt(int nIndex); - - //! Get parent XML node. - XmlNodeRef getParent() const { return m_parent; } - void setParent(const XmlNodeRef& inRef); - - //! Returns content of this node. - const char* getContent() const { return m_content.c_str(); }; - void setContent(const char* str); - - XmlNodeRef clone(); - - //! Returns line number for XML tag. - int getLine() const { return m_line; }; - //! Set line number in xml. - void setLine(int line) { m_line = line; }; - - //! Returns XML of this node and sub nodes. - virtual IXmlStringData* getXMLData(int nReserveMem = 0) const; - XmlString getXML(int level = 0) const; - bool saveToFile(const char* fileName) override; - - //! Set new XML Node attribute (or override attribute with same key). - void setAttr(const char* key, const char* value); - void setAttr(const char* key, int value); - void setAttr(const char* key, unsigned int value); - void setAttr(const char* key, int64 value); - void setAttr(const char* key, uint64 value, bool useHexFormat = true); - void setAttr(const char* key, float value); - void setAttr(const char* key, double value); - void setAttr(const char* key, const Vec2& value); - void setAttr(const char* key, const Vec2d& value); - void setAttr(const char* key, const Ang3& value); - void setAttr(const char* key, const Vec3& value); - void setAttr(const char* key, const Vec4& value); - void setAttr(const char* key, const Vec3d& value); - void setAttr(const char* key, const Quat& value); - - //! Delete attrbute. - void delAttr(const char* key); - //! Remove all node attributes. - void removeAllAttributes(); - - //! Get attribute value of node. - bool getAttr(const char* key, int& value) const; - bool getAttr(const char* key, unsigned int& value) const; - bool getAttr(const char* key, int64& value) const; - bool getAttr(const char* key, uint64& value, bool useHexFormat = true /*ignored*/) const; - bool getAttr(const char* key, float& value) const; - bool getAttr(const char* key, double& value) const; - bool getAttr(const char* key, bool& value) const; - bool getAttr(const char* key, XmlString& value) const - { - XmlString v; - if (v = getAttr(key)) - { - value = v; - return true; - } - else - { - return false; - } - } - bool getAttr(const char* key, Vec2& value) const; - bool getAttr(const char* key, Vec2d& value) const; - bool getAttr(const char* key, Ang3& value) const; - bool getAttr(const char* key, Vec3& value) const; - bool getAttr(const char* key, Vec3d& value) const; - bool getAttr(const char* key, Vec4& value) const; - bool getAttr(const char* key, Quat& value) const; - bool getAttr(const char* key, ColorB& value) const; - // bool getAttr( const char *key,string &value ) const { XmlString v; if (getAttr(key,v)) { value = (const char*)v; return true; } else return false; } - -#if !defined(RESOURCE_COMPILER) - // - // Summary: - // Collect all allocated memory - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const { assert(0); }; - - // Summary: - // Copies children to this node from a given node. - // Children are reference copied (shallow copy) and the children's parent is NOT set to this - // node, but left with its original parent (which is still the parent) - void shareChildren([[maybe_unused]] const XmlNodeRef& fromNode) { assert(0); }; - - // Summary: - // Returns XML of this node and sub nodes into tmpBuffer without XML checks (much faster) - XmlString getXMLUnsafe(int level, [[maybe_unused]] char* tmpBuffer, [[maybe_unused]] uint32 sizeOfTmpBuffer) const { return getXML(level); } - - // Notes: - // Save in small memory chunks. - bool saveToFile([[maybe_unused]] const char* fileName, [[maybe_unused]] size_t chunkSizeBytes, [[maybe_unused]] AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle) override { assert(0); return false; }; - // -#endif - -private: - void AddToXmlString(XmlString& xml, int level) const; - XmlString MakeValidXmlString(const XmlString& xml) const; - bool IsValidXmlString(const char* str) const; - XmlAttrConstIter GetAttrConstIterator(const char* key) const - { - XmlAttribute tempAttr; - tempAttr.key = key; - - XmlAttributes::const_iterator it = std::find(m_attributes.begin(), m_attributes.end(), tempAttr); - return it; - - /* - XmlAttributes::const_iterator it = std::lower_bound( m_attributes.begin(),m_attributes.end(),tempAttr ); - if (it != m_attributes.end() && _stricmp(it->key,key) == 0) - return it; - return m_attributes.end(); - */ - } - XmlAttrIter GetAttrIterator(const char* key) - { - XmlAttribute tempAttr; - tempAttr.key = key; - - XmlAttributes::iterator it = std::find(m_attributes.begin(), m_attributes.end(), tempAttr); - return it; - - // XmlAttributes::iterator it = std::lower_bound( m_attributes.begin(),m_attributes.end(),tempAttr ); - //if (it != m_attributes.end() && _stricmp(it->key,key) == 0) - //return it; - //return m_attributes.end(); - } - const char* GetValue(const char* key) const - { - XmlAttrConstIter it = GetAttrConstIterator(key); - if (it != m_attributes.end()) - { - return it->value; - } - return 0; - } - -private: - //! Line in XML file where this node firstly appeared (usefull for debugging). - int m_line; - - //! Tag of XML node. - const char* m_tag; - //! Content of XML node. - XmlString m_content; - //! Parent XML node. - CXmlNode* m_parent; - - // String pool used by this node. - IXmlStringPool* m_pStringPool; - - typedef std::vector XmlNodes; - XmlNodes m_childs; - //! Xml node attributes. - XmlAttributes m_attributes; - - friend class XmlParserImp; -}; - -#endif // __XML_HEADER__ - - -/* -#ifndef __XML_HEADER__ -#define __XML_HEADER__ - - - -class CXmlNode : public IXmlNode -{ -public: - //! Constructor. - CXmlNode( const char *tag ); - //! Destructor. - ~CXmlNode(); - - ////////////////////////////////////////////////////////////////////////// - //! Reference counting. - void AddRef() { m_refCount++; }; - //! When ref count reach zero XML node dies. - void Release(); - - //! Create new XML node. - XmlNodeRef createNode( const char *tag ); - - //! Get XML node tag. - const char *getTag() const { return m_tag; }; - void setTag( const char *tag ) { m_tag = tag; } - - //! Return true if givven tag equal to node tag. - bool isTag( const char *tag ) const; - - //! Get XML Node attributes. - virtual int getNumAttributes() const { return (int)m_attributes.size(); }; - //! Return attribute key and value by attribute index. - virtual bool getAttributeByIndex( int index,const char **key,const char **value ); - - virtual void* getFirstAttribute(); - virtual bool getNextAttribute( void** pIterator,const char **key,const char **value ); - - virtual void copyAttributes( XmlNodeRef fromNode ); - - //! Get XML Node attribute for specified key. - const char* getAttr( const char *key ) const; - //! Check if attributes with specified key exist. - bool haveAttr( const char *key ) const; - - //! Adds new child node. - void addChild( const XmlNodeRef &node ); - - //! Creates new xml node and add it to childs list. - XmlNodeRef newChild( const char *tagName ); - - //! Remove child node. - void removeChild( const XmlNodeRef &node ); - - //! Remove all child nodes. - void removeAllChilds(); - - //! Get number of child XML nodes. - int getChildCount() const { return (int)m_childs.size(); }; - - //! Get XML Node child nodes. - XmlNodeRef getChild( int i ) const; - - //! Find node with specified tag. - XmlNodeRef findChild( const char *tag ) const; - - //! Get parent XML node. - XmlNodeRef getParent() const { return m_parent; } - - //! Returns content of this node. - const char* getContent() const { return m_content; }; - void setContent( const char *str ) { m_content = str; }; - void addContent( const char *str ) { m_content += str; }; - - XmlNodeRef clone(); - - //! Returns line number for XML tag. - int getLine() const { return m_line; }; - //! Set line number in xml. - void setLine( int line ) { m_line = line; }; - - //! Returns XML of this node and sub nodes. - XmlString getXML( int level=0 ) const; - XmlString getBinaryXML() const; - bool saveToFile( const char *fileName, bool bBinary = false ); - bool saveToSink(IXMLDataSink* pSink, bool bBinary = false); - - //! Set new XML Node attribute (or override attribute with same key). - void setAttr( const char* key,const char* value ); - void setAttr( const char* key,int value ); - void setAttr( const char* key,unsigned int value ); - void setAttr( const char* key,uint64 value ); - void setAttr( const char* key,float value ); - void setAttr( const char* key,const Ang3& value ); - void setAttr( const char* key,const Vec3& value ); - void setAttr( const char* key,const Quat &value ); - - //! Delete attribute. - void delAttr( const char* key ); - //! Remove all node attributes. - void removeAllAttributes(); - - //! Get attribute value of node. - bool getAttr( const char *key,int &value ) const; - bool getAttr( const char *key,unsigned int &value ) const; - bool getAttr( const char *key,uint64 &value ) const; - bool getAttr( const char *key,float &value ) const; - bool getAttr( const char *key,Ang3& value ) const; - bool getAttr( const char *key,Vec3& value ) const; - bool getAttr( const char *key,Quat &value ) const; - bool getAttr( const char *key,bool &value ) const; - bool getAttr( const char *key,XmlString &value ) const { XmlString v; if (v=getAttr(key)) { value = v; return true; } else return false; } -// bool getAttr( const char *key,string &value ) const { XmlString v; if (getAttr(key,v)) { value = (const char*)v; return true; } else return false; } - - // Add an attribute structure directly. - void addAttr(XmlAttribute& attribute); - - void SetBuffer(StringBuffer* pStringBuffer); - -private: - void AddToXmlString( XmlString &xml,int level ) const; - -private: - StringBuffer* m_pStringBuffer; - - //! Ref count itself, its zeroed on node creation. - int m_refCount; - - //! Line in XML file where this node firstly appeared (usefull for debuggin). - int m_line; - //! Tag of XML node. - XmlString m_tag; - - //! Content of XML node. - XmlString m_content; - //! Parent XML node. - CXmlNode *m_parent; - //! Next XML node in same hierarchy level. - - typedef std::vector XmlNodes; - XmlNodes m_childs; - //! Xml node attributes. - XmlAttributes m_attributes; - static XmlAttribute tempAttr; -}; - -#endif // CRYINCLUDE_CRYXML_XML_XML_H -*/ diff --git a/Code/Tools/CryXML/XMLSerializer.cpp b/Code/Tools/CryXML/XMLSerializer.cpp deleted file mode 100644 index e1152f93a3..0000000000 --- a/Code/Tools/CryXML/XMLSerializer.cpp +++ /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. - -#include "CryXML_precompiled.h" -#include "XMLSerializer.h" -#include "XML/xml.h" -#include "IXMLSerializer.h" -#include "StringUtils.h" - -XmlNodeRef XMLSerializer::CreateNode(const char* tag) -{ - return new CXmlNode(tag); -} - -bool XMLSerializer::Write(XmlNodeRef root, const char* szFileName) -{ - return root->saveToFile(szFileName); -} - -XmlNodeRef XMLSerializer::Read(const IXmlBufferSource& source, bool bRemoveNonessentialSpacesFromContent, int nErrorBufferSize, char* szErrorBuffer) -{ - XmlParser parser(bRemoveNonessentialSpacesFromContent); - XmlNodeRef root = parser.parseSource(&source); - if (nErrorBufferSize > 0 && szErrorBuffer) - { - const char* const err = parser.getErrorString(); - cry_strcpy(szErrorBuffer, nErrorBufferSize, err ? err : ""); - } - return root; -} diff --git a/Code/Tools/CryXML/XMLSerializer.h b/Code/Tools/CryXML/XMLSerializer.h deleted file mode 100644 index 7730b19963..0000000000 --- a/Code/Tools/CryXML/XMLSerializer.h +++ /dev/null @@ -1,31 +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_CRYXML_XMLSERIALIZER_H -#define CRYINCLUDE_CRYXML_XMLSERIALIZER_H -#pragma once - - -#include "IXMLSerializer.h" - -class XMLSerializer - : public IXMLSerializer -{ -public: - virtual XmlNodeRef CreateNode(const char* tag); - virtual bool Write(XmlNodeRef root, const char* szFileName); - - virtual XmlNodeRef Read(const IXmlBufferSource& source, bool bRemoveNonessentialSpacesFromContent, int nErrorBufferSize, char* szErrorBuffer); -}; - -#endif // CRYINCLUDE_CRYXML_XMLSERIALIZER_H diff --git a/Code/Tools/CryXML/cryxml_files.cmake b/Code/Tools/CryXML/cryxml_files.cmake deleted file mode 100644 index d81ace11b7..0000000000 --- a/Code/Tools/CryXML/cryxml_files.cmake +++ /dev/null @@ -1,22 +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 - CryXML.cpp - XMLSerializer.cpp - ICryXML.h - IXMLSerializer.h - XMLSerializer.h - XML/xml.cpp - XML/xml.h - CryXML_precompiled.h - CryXML_precompiled.cpp -) diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/Bump2NormalHighQ.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/Bump2NormalHighQ.tif.exportsettings deleted file mode 100644 index e7bbaccd46..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/Bump2NormalHighQ.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /bumptype=1 /mipmirror=1 /preset=Bump2Normalmap_highQ /reduce=1 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha256512.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha256512.tif.exportsettings deleted file mode 100644 index 5f78477ca8..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha256512.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Diffuse_highQ /reduce=1 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha512256.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha512256.tif.exportsettings deleted file mode 100644 index 5f78477ca8..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha512256.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Diffuse_highQ /reduce=1 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/LuminanceOnly.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/LuminanceOnly.tif.exportsettings deleted file mode 100644 index 6466dc9099..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/LuminanceOnly.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /mipalphacoverage=0 /mipmirror=1 /preset=Diffuse_highQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPreset3DC_ddn.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPreset3DC_ddn.tif.exportsettings deleted file mode 100644 index acfbe2a750..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPreset3DC_ddn.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=0 /preset=Normalmap_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8.tif.exportsettings deleted file mode 100644 index 00ecf3a56e..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Diffuse_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8WithAlpha.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8WithAlpha.tif.exportsettings deleted file mode 100644 index 00ecf3a56e..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8WithAlpha.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Diffuse_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_bump.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_bump.tif.exportsettings deleted file mode 100644 index cab995b31e..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_bump.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Bump2Normalmap_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_ddn.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_ddn.tif.exportsettings deleted file mode 100644 index c5a53f8bd5..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_ddn.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Normalmap_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings.tif.exportsettings deleted file mode 100644 index 1048249b71..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=Diffuse_lowQ diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings300400.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings300400.tif.exportsettings deleted file mode 100644 index db0b877f24..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings300400.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=ReferenceImage diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettingsGrey_DDNDIF.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettingsGrey_DDNDIF.tif.exportsettings deleted file mode 100644 index 1048249b71..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettingsGrey_DDNDIF.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=Diffuse_lowQ diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings_DDNDIF.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings_DDNDIF.tif.exportsettings deleted file mode 100644 index 84c0416421..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings_DDNDIF.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /ms=0 /preset=Diffuse_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ.tif.exportsettings deleted file mode 100644 index c5a53f8bd5..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Normalmap_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQReduce1_ddn.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQReduce1_ddn.tif.exportsettings deleted file mode 100644 index cb9f25b5d9..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQReduce1_ddn.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Normalmap_lowQ /reduce=1 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ_ddn.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ_ddn.tif.exportsettings deleted file mode 100644 index c5a53f8bd5..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ_ddn.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Normalmap_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/TestColorChart_cch.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/TestColorChart_cch.tif.exportsettings deleted file mode 100644 index 47b9f504fd..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/TestColorChart_cch.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=ColorChart diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/diamand_plate_ddn.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/diamand_plate_ddn.tif.exportsettings deleted file mode 100644 index 3e5edcd652..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/diamand_plate_ddn.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumptype=1 /preset=Bump2Normalmap_lowQ /reduce=0 diff --git a/Gems/Blast/Assets/.p4ignore b/Gems/Blast/Assets/.p4ignore deleted file mode 100644 index 7015097e56..0000000000 --- a/Gems/Blast/Assets/.p4ignore +++ /dev/null @@ -1 +0,0 @@ -*.physx diff --git a/Tools/AnimationTest/assetImportTest.bat b/Tools/AnimationTest/assetImportTest.bat deleted file mode 100644 index 205c17280b..0000000000 --- a/Tools/AnimationTest/assetImportTest.bat +++ /dev/null @@ -1,31 +0,0 @@ -REM -REM -REM All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -REM its licensors. -REM -REM For complete copyright and license terms please see the LICENSE at the root of this -REM distribution (the "License"). All use of this software is governed by the License, -REM or, if provided, by the license below or the license accompanying this file. Do not -REM remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -REM - -TITLE asset import test - -SETLOCAL EnableExtensions -set EXE=AssetProcessor_tmp.exe -FOR /F %%x IN ('tasklist /NH /FI "IMAGENAME eq %EXE%"') DO IF %%x == %EXE% goto FOUND -echo Make sure asset processor is running before run this script. -goto FIN -:FOUND - -SET F="..\..\Cache\SamplesProject\pc\samplesproject\objects" - -IF EXIST %F% ( - RMDIR /S /Q %F% - ECHO Detected folder at %F% - ECHO Make sure there's no fail / crash in asset processor after all job finished. -) ELSE (ECHO folder %F% NOT FOUND) - -:FIN -PAUSE \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/7z.exe b/Tools/DeepBandwidthToExcel/7z.exe deleted file mode 100644 index 85fa5e2917..0000000000 --- a/Tools/DeepBandwidthToExcel/7z.exe +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2ca56c2a96859b5171e7d24c81ed4d281da0ea26a7eaff7eac975d337eb4a2e1 -size 266752 diff --git a/Tools/DeepBandwidthToExcel/DeepBandwidthToExcel.exe b/Tools/DeepBandwidthToExcel/DeepBandwidthToExcel.exe deleted file mode 100644 index b89cb8c457..0000000000 --- a/Tools/DeepBandwidthToExcel/DeepBandwidthToExcel.exe +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6b8dc17c53df32173fd82d8bfc844bc3752bf6cbaf1bf2fd334dd6949f44b04b -size 1050344 diff --git a/Tools/DeepBandwidthToExcel/Template/[Content_Types].xml b/Tools/DeepBandwidthToExcel/Template/[Content_Types].xml deleted file mode 100644 index 3c4fc1468a..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/[Content_Types].xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/_rels/.rels b/Tools/DeepBandwidthToExcel/Template/_rels/.rels deleted file mode 100644 index 74bfd8d955..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/_rels/.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/docProps/app.xml b/Tools/DeepBandwidthToExcel/Template/docProps/app.xml deleted file mode 100644 index 6430cd86f5..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/docProps/app.xml +++ /dev/null @@ -1,2 +0,0 @@ - -Microsoft Excel0falseWorksheets9Group TotalsMessage TotalsPolicy CountPolicy ImpactSerialisation ImpactBandwidth Over TimeSocket Packets Over TimeSocket Bits Over TimeWarningsCrytek UKfalsefalsefalse12.0000 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/docProps/core.xml b/Tools/DeepBandwidthToExcel/Template/docProps/core.xml deleted file mode 100644 index f1efda39ff..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/docProps/core.xml +++ /dev/null @@ -1,2 +0,0 @@ - -leelee2012-03-06T13:44:11Z2012-03-23T08:28:17Z \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/_rels/workbook.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/_rels/workbook.xml.rels deleted file mode 100644 index e9dc190f2c..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/_rels/workbook.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/calcChain.xml b/Tools/DeepBandwidthToExcel/Template/xl/calcChain.xml deleted file mode 100644 index 2fb95911c6..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/calcChain.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart1.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart1.xml deleted file mode 100644 index 3e3737423c..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart1.xml +++ /dev/null @@ -1,2 +0,0 @@ - -Overall By Schedule Group'Group Totals'!###---SHEET1_COL0---###peterpaul'Group Totals'!###---SHEET1_COL1---###General55 diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart2.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart2.xml deleted file mode 100644 index 54d3f0da26..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart2.xml +++ /dev/null @@ -1,2 +0,0 @@ - -Overall By Message'Message Totals'!###---SHEET2_COL0---###peterpaul'Message Totals'!###---SHEET2_COL1---###General55 diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart3.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart3.xml deleted file mode 100644 index f405df758f..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart3.xml +++ /dev/null @@ -1,2 +0,0 @@ - -Overall By Policy Count'Policy Count'!###---SHEET3_COL0---###ui2eid'Policy Count'!###---SHEET3_COL1---###General20801811398975 diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart4.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart4.xml deleted file mode 100644 index 6d461a7cd5..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart4.xml +++ /dev/null @@ -1,2 +0,0 @@ - -Overall By Policy Impact (Bits Per Policy)'Policy Impact'!###---SHEET4_COL0---###wrlddMov'Policy Impact'!###---SHEET4_COL1---###General5354582913312905 diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart5.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart5.xml deleted file mode 100644 index 5276503965..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart5.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - - - - - - - - - - - - - Overall By Serialisation Impact (Bits - - - - Per Serialise) - - - - - - - - - - - - - - - - - - - - 'Serialisation Impact'!###---SHEET5_COL0---### - - - - wrld - - - dMov - - - - - - - 'Serialisation Impact'!###---SHEET5_COL1---### - - General - - - 53545829 - - - 13312905 - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart6.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart6.xml deleted file mode 100644 index 3dbcb710ee..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart6.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - - - - - - - - - - - Bandwidth Over Time - - - - - - - - - - ###---SHEET6_CHART---### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart7.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart7.xml deleted file mode 100644 index 324a3d0296..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart7.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - - - - - - - - - - - - - - Socket - - - - Packets Per Second - - - - - - - - - - - ###---SHEET7_CHART---### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart8.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart8.xml deleted file mode 100644 index 9aed1eaa0b..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart8.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - - - - - - - - - - - Socket - - - - Bits Per Second - - - - - - - - - - ###---SHEET8_CHART---### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing1.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing1.xml.rels deleted file mode 100644 index 91223aab09..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing1.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing2.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing2.xml.rels deleted file mode 100644 index 63233beb83..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing2.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing3.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing3.xml.rels deleted file mode 100644 index c53f6617a5..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing3.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing4.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing4.xml.rels deleted file mode 100644 index 7fe138bac4..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing4.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing5.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing5.xml.rels deleted file mode 100644 index 22864411ec..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing5.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing6.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing6.xml.rels deleted file mode 100644 index 424914396d..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing6.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing7.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing7.xml.rels deleted file mode 100644 index b1404c3db9..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing7.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing8.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing8.xml.rels deleted file mode 100644 index a9e371607f..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing8.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing1.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing1.xml deleted file mode 100644 index 70ea7ed3be..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing1.xml +++ /dev/null @@ -1,2 +0,0 @@ - -43809902857429952440114299 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing2.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing2.xml deleted file mode 100644 index f8a60ce08a..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing2.xml +++ /dev/null @@ -1,2 +0,0 @@ - -338100076199285810254057150 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing3.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing3.xml deleted file mode 100644 index 75e5d9ed25..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing3.xml +++ /dev/null @@ -1,2 +0,0 @@ - -2276225095250283714754019050 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing4.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing4.xml deleted file mode 100644 index de297dbb14..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing4.xml +++ /dev/null @@ -1,2 +0,0 @@ - -3001333492851435040123824 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing5.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing5.xml deleted file mode 100644 index b7c2cf9c02..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing5.xml +++ /dev/null @@ -1,2 +0,0 @@ - -25524500104775284572004095250 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing6.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing6.xml deleted file mode 100644 index c610b4c052..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing6.xml +++ /dev/null @@ -1,2 +0,0 @@ - -338099914287528257174409525 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing7.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing7.xml deleted file mode 100644 index 14d255a242..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing7.xml +++ /dev/null @@ -1,2 +0,0 @@ - -247624310477526533399389525 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing8.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing8.xml deleted file mode 100644 index 1b94acd279..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing8.xml +++ /dev/null @@ -1,2 +0,0 @@ - -23809931047752744767539114301 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/sharedStrings.xml b/Tools/DeepBandwidthToExcel/Template/xl/sharedStrings.xml deleted file mode 100644 index 2fbc1ad0b7..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/sharedStrings.xml +++ /dev/null @@ -1,2 +0,0 @@ - -###---STRINGSTABLE---### diff --git a/Tools/DeepBandwidthToExcel/Template/xl/styles.xml b/Tools/DeepBandwidthToExcel/Template/xl/styles.xml deleted file mode 100644 index 8238b50fd0..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/styles.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/theme/theme1.xml b/Tools/DeepBandwidthToExcel/Template/xl/theme/theme1.xml deleted file mode 100644 index 9944f3ecab..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/theme/theme1.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/workbook.xml b/Tools/DeepBandwidthToExcel/Template/xl/workbook.xml deleted file mode 100644 index 19c26d83b6..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/workbook.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet1.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet1.xml.rels deleted file mode 100644 index 205832e91b..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet1.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet2.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet2.xml.rels deleted file mode 100644 index b48a928346..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet2.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet3.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet3.xml.rels deleted file mode 100644 index c0c5ded4a6..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet3.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet4.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet4.xml.rels deleted file mode 100644 index f34eab954f..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet4.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet5.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet5.xml.rels deleted file mode 100644 index 67118d3a1e..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet5.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet6.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet6.xml.rels deleted file mode 100644 index 656a337f58..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet6.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet7.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet7.xml.rels deleted file mode 100644 index efc518bb3f..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet7.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet8.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet8.xml.rels deleted file mode 100644 index 586d2d3c76..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet8.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet1.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet1.xml deleted file mode 100644 index 1fbfb22964..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet1.xml +++ /dev/null @@ -1,2 +0,0 @@ - -###---SHEET1_DATA---### diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet2.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet2.xml deleted file mode 100644 index 0d72f8c9da..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet2.xml +++ /dev/null @@ -1,2 +0,0 @@ - -###---SHEET2_DATA---### diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet3.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet3.xml deleted file mode 100644 index 18717c6987..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet3.xml +++ /dev/null @@ -1,2 +0,0 @@ - -###---SHEET3_DATA---### diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet4.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet4.xml deleted file mode 100644 index 9442249676..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet4.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - -###---SHEET4_DATA---### - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet5.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet5.xml deleted file mode 100644 index 14f48b192c..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet5.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - -###---SHEET5_DATA---### - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet6.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet6.xml deleted file mode 100644 index fa7a8d800b..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet6.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - -###---SHEET6_DATA---### - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet7.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet7.xml deleted file mode 100644 index 708d01d20c..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet7.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - -###---SHEET7_DATA---### - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet8.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet8.xml deleted file mode 100644 index 164cdcdde2..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet8.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - -###---SHEET8_DATA---### - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet9.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet9.xml deleted file mode 100644 index a3a3b40230..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet9.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - -###---SHEET9_DATA---### - - diff --git a/scripts/build/package/Platform/Windows/package_filelists/atom.json b/scripts/build/package/Platform/Windows/package_filelists/atom.json index f084173cb2..5f3d3b78cb 100644 --- a/scripts/build/package/Platform/Windows/package_filelists/atom.json +++ b/scripts/build/package/Platform/Windows/package_filelists/atom.json @@ -38,24 +38,13 @@ "AzTestRunner/**": "#include", "CrashHandler/**": "#include", "CryCommonTools/**": "#include", - "CrySCompileServer/**": "#include", - "CryXML/**": "#include", "DeltaCataloger/**": "#include", - "GemRegistry/**": "#include", "GridHub/**": "#include", - "HLSLCrossCompiler/**": "#include", - "HLSLCrossCompilerMETAL/**": "#include", - "LyIdentity/**": "#include", - "LyMetrics/**": "#include", "News/**": "#include", "PythonBindingsExample/**": "#include", - "RC/**": "#include", "RemoteConsole/**": "#include", "SceneAPI/**": "#include", "SerializeContextTools/**": "#include", - "ShaderCacheGen/**": "#include", - "SharedQMLResource/**": "#include", - "Woodpecker/**": "#include", "CMakeLists.txt": "#include" }, "CMakeLists.txt": "#include" From 795aa114e69f6846133442da9d74cae56416ca39 Mon Sep 17 00:00:00 2001 From: Tom Hulton-Harrop <82228511+hultonha@users.noreply.github.com> Date: Thu, 13 May 2021 16:19:53 +0100 Subject: [PATCH 100/100] Improve selection in the viewport (#720) * improve selection in the viewport * remove debug code * updates following review feedback - update API comments from /// to //! from - add [[nodiscard]] attribute to member function - move constructor implementations to .cpp files * use lambda instead of ternary operator * fix unit test failure caused by typo --- .../AzFramework/Viewport/CameraInput.cpp | 95 ++++++----- .../AzFramework/Viewport/CameraInput.h | 29 ++-- .../AzFramework/Viewport/ClickDetector.cpp | 68 ++++++++ .../AzFramework/Viewport/ClickDetector.h | 75 ++++++++ .../AzFramework/Viewport/CursorState.h | 56 ++++++ .../AzFramework/azframework_files.cmake | 3 + .../EditorTransformComponentSelection.cpp | 36 +++- .../EditorTransformComponentSelection.h | 160 +++++++++--------- Code/Framework/Tests/ClickDetectorTests.cpp | 142 ++++++++++++++++ Code/Framework/Tests/CursorStateTests.cpp | 54 ++++++ .../Tests/frameworktests_files.cmake | 2 + 11 files changed, 575 insertions(+), 145 deletions(-) create mode 100644 Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp create mode 100644 Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h create mode 100644 Code/Framework/AzFramework/AzFramework/Viewport/CursorState.h create mode 100644 Code/Framework/Tests/ClickDetectorTests.cpp create mode 100644 Code/Framework/Tests/CursorStateTests.cpp diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 8669b58911..daf2c63921 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -156,35 +157,25 @@ namespace AzFramework camera.m_lookAt = transform.GetTranslation() + (camera.Rotation().GetBasisY() * -camera.m_lookDist); } - static ScreenVector CursorDelta(const AZStd::optional& currentPosition, const AZStd::optional& lastPosition) - { - return currentPosition.has_value() && lastPosition.has_value() ? currentPosition.value() - lastPosition.value() - : ScreenVector(0, 0); - } - bool CameraSystem::HandleEvents(const InputEvent& event) { if (const auto& cursor = AZStd::get_if(&event)) { - m_currentCursorPosition = cursor->m_position; + m_cursorState.SetCurrentPosition(cursor->m_position); } else if (const auto& scroll = AZStd::get_if(&event)) { m_scrollDelta = scroll->m_delta; } - return m_cameras.HandleEvents(event, CursorDelta(m_currentCursorPosition, m_lastCursorPosition), m_scrollDelta); + return m_cameras.HandleEvents(event, m_cursorState.CursorDelta(), m_scrollDelta); } Camera CameraSystem::StepCamera(const Camera& targetCamera, const float deltaTime) { - const auto cursorDelta = CursorDelta(m_currentCursorPosition, m_lastCursorPosition); - if (m_currentCursorPosition.has_value()) - { - m_lastCursorPosition = m_currentCursorPosition; - } + const auto nextCamera = m_cameras.StepCamera(targetCamera, m_cursorState.CursorDelta(), m_scrollDelta, deltaTime); - const auto nextCamera = m_cameras.StepCamera(targetCamera, cursorDelta, m_scrollDelta, deltaTime); + m_cursorState.Update(); m_scrollDelta = 0.0f; @@ -236,12 +227,12 @@ namespace AzFramework } } - // accumulate - Camera nextCamera = targetCamera; - for (auto& cameraInput : m_activeCameraInputs) - { - nextCamera = cameraInput->StepCamera(nextCamera, cursorDelta, scrollDelta, deltaTime); - } + const Camera nextCamera = AZStd::accumulate( + AZStd::begin(m_activeCameraInputs), AZStd::end(m_activeCameraInputs), targetCamera, + [cursorDelta, scrollDelta, deltaTime](Camera acc, auto& camera) { + acc = camera->StepCamera(acc, cursorDelta, scrollDelta, deltaTime); + return acc; + }); for (int i = 0; i < m_activeCameraInputs.size();) { @@ -275,34 +266,42 @@ namespace AzFramework } } + RotateCameraInput::RotateCameraInput(const InputChannelId rotateChannelId) + : m_rotateChannelId(rotateChannelId) + { + } + void RotateCameraInput::HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { - if (const auto& input = AZStd::get_if(&event)) - { - if (input->m_channelId == m_rotateChannelId) + const ClickDetector::ClickEvent clickEvent = [&event, this] { + if (const auto& input = AZStd::get_if(&event)) { - if (input->m_state == InputChannel::State::Began) - { - m_tryingToBegin = true; - m_moveAccumulator = 0.0f; - } - else if (input->m_state == InputChannel::State::Ended) + if (input->m_channelId == m_rotateChannelId) { - m_tryingToBegin = false; - EndActivation(); + if (input->m_state == InputChannel::State::Began) + { + return ClickDetector::ClickEvent::Down; + } + else if (input->m_state == InputChannel::State::Ended) + { + return ClickDetector::ClickEvent::Up; + } } } - } + return ClickDetector::ClickEvent::Nil; + }(); - if (m_tryingToBegin) + switch (const auto outcome = m_clickDetector.DetectClick(clickEvent, cursorDelta); outcome) { - // only allow the action to begin if the mouse has been moved a small amount - m_moveAccumulator += ScreenVectorLength(cursorDelta); - if (m_moveAccumulator > ed_cameraSystemLookDeadzone) - { - BeginActivation(); - m_tryingToBegin = false; - } + case ClickDetector::ClickOutcome::Move: + BeginActivation(); + break; + case ClickDetector::ClickOutcome::Release: + EndActivation(); + break; + default: + // noop + break; } } @@ -324,6 +323,12 @@ namespace AzFramework return nextCamera; } + PanCameraInput::PanCameraInput(const InputChannelId panChannelId, PanAxesFn panAxesFn) + : m_panAxesFn(AZStd::move(panAxesFn)) + , m_panChannelId(panChannelId) + { + } + void PanCameraInput::HandleEvents( const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { @@ -400,6 +405,11 @@ namespace AzFramework return TranslationType::Nil; } + TranslateCameraInput::TranslateCameraInput(TranslationAxesFn translationAxesFn) + : m_translationAxesFn(AZStd::move(translationAxesFn)) + { + } + void TranslateCameraInput::HandleEvents( const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { @@ -574,6 +584,11 @@ namespace AzFramework return nextCamera; } + OrbitDollyCursorMoveCameraInput::OrbitDollyCursorMoveCameraInput(const InputChannelId dollyChannelId) + : m_dollyChannelId(dollyChannelId) + { + } + void OrbitDollyCursorMoveCameraInput::HandleEvents( const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index 6475753017..41d7f11385 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -17,6 +17,8 @@ #include #include #include +#include +#include #include #include @@ -188,26 +190,21 @@ namespace AzFramework Cameras m_cameras; private: + CursorState m_cursorState; float m_scrollDelta = 0.0f; - AZStd::optional m_lastCursorPosition; - AZStd::optional m_currentCursorPosition; }; class RotateCameraInput : public CameraInput { public: - explicit RotateCameraInput(const InputChannelId rotateChannelId) - : m_rotateChannelId(rotateChannelId) - { - } + explicit RotateCameraInput(InputChannelId rotateChannelId); void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; private: InputChannelId m_rotateChannelId; - float m_moveAccumulator = 0.0f; - bool m_tryingToBegin = false; + ClickDetector m_clickDetector; }; struct PanAxes @@ -240,11 +237,8 @@ namespace AzFramework class PanCameraInput : public CameraInput { public: - PanCameraInput(const InputChannelId panChannelId, PanAxesFn panAxesFn) - : m_panAxesFn(AZStd::move(panAxesFn)) - , m_panChannelId(panChannelId) - { - } + PanCameraInput(InputChannelId panChannelId, PanAxesFn panAxesFn); + void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; @@ -283,10 +277,8 @@ namespace AzFramework class TranslateCameraInput : public CameraInput { public: - explicit TranslateCameraInput(TranslationAxesFn translationAxesFn) - : m_translationAxesFn(AZStd::move(translationAxesFn)) - { - } + explicit TranslateCameraInput(TranslationAxesFn translationAxesFn); + void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; void ResetImpl() override; @@ -363,8 +355,7 @@ namespace AzFramework class OrbitDollyCursorMoveCameraInput : public CameraInput { public: - explicit OrbitDollyCursorMoveCameraInput(const InputChannelId dollyChannelId) - : m_dollyChannelId(dollyChannelId) {} + explicit OrbitDollyCursorMoveCameraInput(InputChannelId dollyChannelId); void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp new file mode 100644 index 0000000000..5af44a81bc --- /dev/null +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp @@ -0,0 +1,68 @@ +/* + * 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 + +namespace AzFramework +{ + ClickDetector::ClickOutcome ClickDetector::DetectClick(const ClickEvent clickEvent, const ScreenVector& cursorDelta) + { + if (clickEvent == ClickEvent::Down) + { + const auto now = std::chrono::steady_clock::now(); + if (m_tryBeginTime) + { + const std::chrono::duration diff = now - m_tryBeginTime.value(); + if (diff.count() < m_doubleClickInterval) + { + return ClickOutcome::Nil; + } + } + + m_detectionState = DetectionState::WaitingForMove; + m_moveAccumulator = 0.0f; + + m_tryBeginTime = now; + } + else if (clickEvent == ClickEvent::Up) + { + const auto clickOutcome = [detectionState = m_detectionState] { + if (detectionState == DetectionState::WaitingForMove) + { + return ClickOutcome::Click; + } + if (detectionState == DetectionState::Moved) + { + return ClickOutcome::Release; + } + return ClickOutcome::Nil; + }(); + + m_detectionState = DetectionState::Nil; + return clickOutcome; + } + + if (m_detectionState == DetectionState::WaitingForMove) + { + // only allow the action to begin if the mouse has been moved a small amount + m_moveAccumulator += ScreenVectorLength(cursorDelta); + if (m_moveAccumulator > m_deadZone) + { + m_detectionState = DetectionState::Moved; + return ClickOutcome::Move; + } + } + + return ClickOutcome::Nil; + } +} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h new file mode 100644 index 0000000000..997ccd07d9 --- /dev/null +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h @@ -0,0 +1,75 @@ +/* + * 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 + +namespace AzFramework +{ + struct ScreenVector; + + //! Utility class to help detect different types of mouse click (mouse down and up with + //! no movement), mouse move (down and initial move after some threshold) and mouse release + //! (mouse down with movement and then mouse up). + class ClickDetector + { + //! Alias for recording time of mouse down events + using Time = std::chrono::time_point; + + public: + //! Internal representation of click event (map from external event for this when + //! calling DetectClick). + enum class ClickEvent + { + Nil, + Down, + Up + }; + + //! The type of mouse click. + enum class ClickOutcome + { + Nil, //!< Not recognized. + Move, //!< Initial move after mouse down. + Click, //!< Mouse down and up with no intermediate movement. + Release //!< Mouse down with movement and then mouse up. + }; + + //! Called from any type of 'handle event' function. + ClickOutcome DetectClick(ClickEvent clickEvent, const ScreenVector& cursorDelta); + + void SetDoubleClickInterval(float doubleClickInterval); + + private: + //! Internal state of ClickDetector based on incoming events. + enum class DetectionState + { + Nil, //!< Initial state + WaitingForMove, //! Mouse down has happened but mouse hasn't yet moved. + Moved //! Mouse has moved, no longer will be counted as a click. + }; + + float m_moveAccumulator = 0.0f; //!< How far the mouse has moved after mouse down. + float m_deadZone = 2.0f; //!< How far to move before a click is cancelled (when Move will fire). + float m_doubleClickInterval = 0.4f; //!< Default double click interval, can be overridden. + DetectionState m_detectionState; //!< Internal state of ClickDetector. + AZStd::optional